Merge branch 'simp/hclia-runtime' into simp/integration
This commit is contained in:
+1
-6
@@ -1,8 +1,3 @@
|
||||
"""Agent internals -- extracted modules from run_agent.py.
|
||||
|
||||
These modules contain pure utility functions and self-contained classes
|
||||
that were previously embedded in the 3,600-line run_agent.py. Extracting
|
||||
them makes run_agent.py focused on the AIAgent orchestrator class.
|
||||
"""
|
||||
"""Agent internals extracted from run_agent.py so it stays focused on AIAgent."""
|
||||
|
||||
from . import jiter_preload as _jiter_preload # noqa: F401
|
||||
|
||||
+16
-37
@@ -1,13 +1,9 @@
|
||||
"""System-battery read-out for the CLI/TUI status bar.
|
||||
|
||||
Reads the host battery through ``psutil`` (already a Hermes dependency) and
|
||||
exposes a compact, colour-coded label. Everything degrades to "unavailable"
|
||||
when there is no battery (desktops, servers, VMs) or when the read fails, so
|
||||
callers can render the result unconditionally and simply show nothing.
|
||||
|
||||
The status bar repaints often (every keystroke and on a ~1s idle refresh), so
|
||||
:func:`read_battery` memoises the last reading for a few seconds instead of
|
||||
hitting ``psutil`` on every frame.
|
||||
Reads the host battery through ``psutil`` and exposes a compact, colour-coded
|
||||
label. Everything degrades to "unavailable" (no battery / read failure) so
|
||||
callers can render unconditionally. The status bar repaints on every keystroke,
|
||||
so :func:`read_battery` memoises the reading for a few seconds.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,12 +15,8 @@ from typing import Optional
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BatteryStatus:
|
||||
"""A single battery reading.
|
||||
|
||||
``available`` is False on machines without a battery (or when the read
|
||||
failed). ``percent`` is clamped to 0-100. ``plugged`` is True when on AC
|
||||
power, False on battery, and None when the platform can't tell.
|
||||
"""
|
||||
"""One reading: ``percent`` clamped 0-100; ``plugged`` None when the
|
||||
platform can't tell."""
|
||||
|
||||
available: bool
|
||||
percent: Optional[int] = None
|
||||
@@ -45,6 +37,9 @@ CATEGORY_BAD = "bad"
|
||||
CATEGORY_CRITICAL = "critical"
|
||||
CATEGORY_DIM = "dim"
|
||||
|
||||
# (upper bound inclusive, category) for a discharging battery; first match wins.
|
||||
_LEVEL_CATEGORIES = ((10, CATEGORY_CRITICAL), (20, CATEGORY_BAD), (50, CATEGORY_WARN))
|
||||
|
||||
_CACHE_TTL_SECONDS = 8.0
|
||||
_cache: Optional[tuple[float, BatteryStatus]] = None
|
||||
|
||||
@@ -52,19 +47,11 @@ _cache: Optional[tuple[float, BatteryStatus]] = None
|
||||
def _read_battery_uncached() -> BatteryStatus:
|
||||
try:
|
||||
import psutil
|
||||
|
||||
# ``sensors_battery`` is missing on some platforms/builds of psutil.
|
||||
batt = getattr(psutil, "sensors_battery")()
|
||||
except Exception:
|
||||
return UNAVAILABLE
|
||||
|
||||
# ``sensors_battery`` is missing on some platforms/builds of psutil.
|
||||
reader = getattr(psutil, "sensors_battery", None)
|
||||
if reader is None:
|
||||
return UNAVAILABLE
|
||||
|
||||
try:
|
||||
batt = reader()
|
||||
except Exception:
|
||||
return UNAVAILABLE
|
||||
|
||||
if batt is None:
|
||||
return UNAVAILABLE
|
||||
|
||||
@@ -75,12 +62,8 @@ def _read_battery_uncached() -> BatteryStatus:
|
||||
percent = max(0, min(100, int(round(float(raw_percent)))))
|
||||
except (TypeError, ValueError):
|
||||
percent = None
|
||||
|
||||
plugged = getattr(batt, "power_plugged", None)
|
||||
if plugged is not None:
|
||||
plugged = bool(plugged)
|
||||
|
||||
return BatteryStatus(available=True, percent=percent, plugged=plugged)
|
||||
return BatteryStatus(available=True, percent=percent, plugged=None if plugged is None else bool(plugged))
|
||||
|
||||
|
||||
def read_battery(use_cache: bool = True) -> BatteryStatus:
|
||||
@@ -109,13 +92,9 @@ def battery_category(status: BatteryStatus) -> str:
|
||||
# On AC power the level isn't a concern — always read as healthy.
|
||||
if status.charging:
|
||||
return CATEGORY_GOOD
|
||||
pct = status.percent
|
||||
if pct <= 10:
|
||||
return CATEGORY_CRITICAL
|
||||
if pct <= 20:
|
||||
return CATEGORY_BAD
|
||||
if pct <= 50:
|
||||
return CATEGORY_WARN
|
||||
for bound, category in _LEVEL_CATEGORIES:
|
||||
if status.percent <= bound:
|
||||
return category
|
||||
return CATEGORY_GOOD
|
||||
|
||||
|
||||
|
||||
+103
-337
@@ -1,63 +1,21 @@
|
||||
"""Unified deadline layer — one bounded-execution primitive, one timeout resolver.
|
||||
|
||||
Phase 1 of the architectural fix for the timeout/hang backlog
|
||||
(https://github.com/NousResearch/hermes-agent/issues/85125).
|
||||
Shared foundation for the site-local deadline mechanisms (#85125):
|
||||
|
||||
The tree currently carries at least six site-local deadline mechanisms, each
|
||||
built for one incident, none shared (tool_executor batch deadline, telegram
|
||||
``_await_with_thread_deadline``, gateway turn lease, reasoning stale floors,
|
||||
``human_wait_ceiling``, per-MCP-handler timeouts). Every new stall report
|
||||
grows that list by one. This module is the shared foundation the call sites
|
||||
migrate onto in later phases:
|
||||
* :func:`resolve_timeout` — config-first timeout resolution
|
||||
(``timeouts:`` in config.yaml > legacy env var > default).
|
||||
* :func:`clamp_timeout` — platform-safe clamping (huge timeouts overflow
|
||||
``time_t`` in ``Lock.acquire`` / ``Thread.join`` on macOS, #83220).
|
||||
* :func:`run_bounded_async` — wall-clock deadline for awaitables driven by a
|
||||
daemon ``threading.Timer``, so a blocked event loop cannot disable it (the
|
||||
telegram adapter's ``_await_with_thread_deadline`` generalized).
|
||||
* :func:`run_bounded_sync` — same contract for synchronous callables.
|
||||
* :func:`kill_process_tree` — portable whole-tree termination.
|
||||
|
||||
* :func:`resolve_timeout` — one config-first resolution path for timeout
|
||||
values (``timeouts:`` section in config.yaml > legacy env var > default),
|
||||
so new surfaces stop inventing ``HERMES_*_TIMEOUT`` env vars (".env is for
|
||||
secrets only") and hardcoded literals stop ignoring user config
|
||||
(#63302, #53161, #43272 class).
|
||||
|
||||
* :func:`clamp_timeout` — platform-safe clamping. Large user-supplied
|
||||
timeouts overflow ``time_t`` inside ``threading.Lock.acquire(timeout=...)``
|
||||
/ ``Thread.join(timeout=...)`` on macOS and kill whole tool batches
|
||||
(#83220). Clamping at the shared boundary fixes that class once, for
|
||||
every consumer.
|
||||
|
||||
* :func:`run_bounded_async` — a wall-clock deadline for awaitables that does
|
||||
NOT depend on event-loop timers. ``asyncio.wait_for`` schedules its expiry
|
||||
on the loop; when the loop thread itself is blocked in a synchronous call
|
||||
(family A of the #84047 stall triage), every asyncio-based timeout in the
|
||||
process is silently disabled. This helper drives the deadline from a
|
||||
daemon ``threading.Timer`` (generalizing the proven telegram-adapter
|
||||
primitive) and abandons cancellation-shielded tasks instead of waiting for
|
||||
cancellation to complete. The telegram adapter's private copy
|
||||
(``plugins/platforms/telegram/adapter.py:_await_with_thread_deadline``)
|
||||
migrates onto this in Phase 2 of #85125 — do not let the two drift in the
|
||||
meantime; fix bugs here first.
|
||||
|
||||
* :func:`run_bounded_sync` — the same contract for synchronous callables
|
||||
bounded from a synchronous context (daemon worker thread, abandoned on
|
||||
expiry).
|
||||
|
||||
* :func:`kill_process_tree` — portable whole-tree termination so
|
||||
kill-on-timeout stops orphaning descendants (#71148, #59549, #84967,
|
||||
#68139 class). Existing site-local tree-kills that migrate onto this in
|
||||
Phase 4 of #85125: ``gateway/status.py`` (taskkill wrapper + psutil
|
||||
snapshot/reap pair) and ``tools/code_execution_tool.py`` (psutil
|
||||
recursive children kill).
|
||||
|
||||
Design invariants:
|
||||
|
||||
* Exceptions raised by the bounded operation propagate unchanged — callers
|
||||
keep their existing error handling. Only the *timeout* outcome is
|
||||
reified (as :class:`BoundedResult`), because that is the outcome the
|
||||
call sites keep getting wrong.
|
||||
* A timeout produced by this layer is OUR deadline, not the provider's.
|
||||
Callers that feed errors into ``agent/error_classifier.py`` should
|
||||
classify :class:`DeadlineExpired` distinctly from transport timeouts
|
||||
(the #59549 / #80323 misattribution class).
|
||||
* ``None`` timeout means unbounded, and non-positive resolved values are
|
||||
normalized to ``None`` (matching the existing
|
||||
``HERMES_CONCURRENT_TOOL_TIMEOUT_S`` convention).
|
||||
Invariants: operation exceptions propagate unchanged (only the *timeout*
|
||||
outcome is reified as :class:`BoundedResult`); a timeout from this layer is
|
||||
OUR deadline, not the provider's (classify :class:`DeadlineExpired` distinctly
|
||||
from transport timeouts); ``None`` / non-positive timeout means unbounded.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -87,35 +45,20 @@ __all__ = [
|
||||
"kill_process_tree",
|
||||
]
|
||||
|
||||
# Upper bound for any timeout handed to platform wait primitives.
|
||||
#
|
||||
# CPython converts ``threading.Lock.acquire(timeout=...)`` /
|
||||
# ``Thread.join(timeout=...)`` deadlines to an absolute timestamp; very large
|
||||
# relative timeouts overflow ``time_t`` on macOS and raise
|
||||
# ``OverflowError: timestamp out of range for platform time_t`` (#83220).
|
||||
# One year is semantically "unbounded" for every wait in this codebase while
|
||||
# staying far below any platform conversion limit.
|
||||
MAX_SAFE_TIMEOUT_S = 31_536_000.0 # 365 days
|
||||
# One year: semantically "unbounded" yet far below any platform time_t limit
|
||||
# (#83220: larger relative timeouts overflow inside Lock.acquire/Thread.join on macOS).
|
||||
MAX_SAFE_TIMEOUT_S = 31_536_000.0
|
||||
|
||||
# Grace period after a deadline fires before concluding the event loop thread
|
||||
# is blocked in a synchronous call and dumping stacks (family A diagnostics).
|
||||
# Grace after a deadline fires before concluding the loop thread is blocked and dumping stacks.
|
||||
_LOOP_BLOCKED_DUMP_GRACE_S = 5.0
|
||||
|
||||
# ``Event.wait`` is a C-level block: KeyboardInterrupt / SetAsyncExc only
|
||||
# land when the thread returns to Python. Slice the wait so a /stop or
|
||||
# SIGINT during a bounded sync call is observed within this window rather
|
||||
# than at the full deadline (#94285, tools/test_local_interrupt_cleanup).
|
||||
# ``Event.wait`` is a C-level block: KeyboardInterrupt / SetAsyncExc only land when the
|
||||
# thread returns to Python, so the sync wait is sliced to observe /stop or SIGINT promptly.
|
||||
_BOUNDED_SYNC_WAIT_SLICE_S = 0.2
|
||||
|
||||
|
||||
class DeadlineExpired(TimeoutError):
|
||||
"""A deadline enforced by this layer expired.
|
||||
|
||||
Distinct from transport/provider timeout types on purpose: when this is
|
||||
raised (or a :class:`BoundedResult` reports ``timed_out``), the timeout
|
||||
was Hermes's own bound — error classification must not attribute it to
|
||||
the provider (#59549 / #80323 misattribution class).
|
||||
"""
|
||||
"""A deadline enforced by this layer expired (Hermes's own bound, not the provider's)."""
|
||||
|
||||
def __init__(self, label: str, timeout_s: float):
|
||||
super().__init__(f"deadline expired after {timeout_s:.1f}s: {label}")
|
||||
@@ -124,21 +67,13 @@ class DeadlineExpired(TimeoutError):
|
||||
|
||||
|
||||
class SuspectableBackend(Protocol):
|
||||
"""Phase 3a (#85125): a stateful backend the deadline layer can flag.
|
||||
"""A stateful backend (MCP connection, browser session, LSP client) the deadline layer can flag.
|
||||
|
||||
A timed-out stateful backend (MCP connection, browser session, LSP
|
||||
client) may be left wedged by the abandoned half-finished operation.
|
||||
``run_bounded_*`` calls ``mark_suspect`` on timeout so the OWNER can
|
||||
health-check or recycle the backend before reuse (``ensure_healthy``)
|
||||
instead of returning a poisoned handle to the cache. Consumers adopt
|
||||
incrementally (Phase 3b, one backend per PR), so the layer fails open:
|
||||
backends without the protocol are simply never marked.
|
||||
|
||||
Adopter contract: ``mark_suspect`` MUST be cheap, non-blocking, and
|
||||
must not acquire locks the guarded operation may hold. It runs inline —
|
||||
on the event loop in the async flavor, and on the caller's thread in
|
||||
the sync flavor while the wedged worker is still alive. Set a flag;
|
||||
do the expensive health-check/recycle work in ``ensure_healthy``.
|
||||
``run_bounded_*`` calls ``mark_suspect`` on timeout so the owner can health-check or
|
||||
recycle the backend (``ensure_healthy``) before reuse. Backends without the protocol
|
||||
are simply never marked. ``mark_suspect`` MUST be cheap, non-blocking, and must not
|
||||
acquire locks the guarded operation may hold — it runs inline on the event loop /
|
||||
caller's thread while the wedged worker is still alive.
|
||||
"""
|
||||
|
||||
def mark_suspect(self, reason: str) -> None: ...
|
||||
@@ -147,13 +82,7 @@ class SuspectableBackend(Protocol):
|
||||
|
||||
|
||||
def _mark_backend_suspect(backend: object | None, label: str, timeout_s: float) -> None:
|
||||
"""Best-effort ``mark_suspect`` on a timed-out call's backend.
|
||||
|
||||
Never raises: adoption state must not be able to weaken the deadline
|
||||
bound or corrupt the ``BoundedResult`` the caller is about to receive.
|
||||
A non-adopting backend (no ``mark_suspect``) is tolerated silently —
|
||||
Phase 3b lands per-backend, so absence is the norm during adoption.
|
||||
"""
|
||||
"""Best-effort ``mark_suspect``; never raises, non-adopting backends tolerated."""
|
||||
if backend is None:
|
||||
return
|
||||
try:
|
||||
@@ -166,12 +95,7 @@ def _mark_backend_suspect(backend: object | None, label: str, timeout_s: float)
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
class BoundedResult:
|
||||
"""Outcome of a bounded operation.
|
||||
|
||||
``timed_out`` is the reified outcome; on completion ``value`` holds the
|
||||
operation's return value. Operation exceptions are never captured here —
|
||||
they propagate to the caller unchanged.
|
||||
"""
|
||||
"""Outcome of a bounded operation; operation exceptions are never captured here."""
|
||||
|
||||
timed_out: bool
|
||||
value: Any
|
||||
@@ -179,33 +103,21 @@ class BoundedResult:
|
||||
timeout_s: Optional[float]
|
||||
label: str
|
||||
|
||||
def raise_if_timed_out(self) -> Any:
|
||||
"""Return ``value``, raising :class:`DeadlineExpired` on timeout."""
|
||||
if self.timed_out:
|
||||
raise DeadlineExpired(self.label, float(self.timeout_s or 0.0))
|
||||
return self.value
|
||||
|
||||
def _result(start: float, timeout_s: Optional[float], label: str, *, value: Any = None, timed_out: bool = False) -> BoundedResult:
|
||||
return BoundedResult(
|
||||
timed_out=timed_out, value=value, elapsed_s=time.monotonic() - start, timeout_s=timeout_s, label=label
|
||||
)
|
||||
|
||||
|
||||
def clamp_timeout(timeout: Optional[float]) -> Optional[float]:
|
||||
"""Normalize a timeout value for platform wait primitives.
|
||||
|
||||
* ``None`` stays ``None`` (unbounded).
|
||||
* Non-positive values become ``None`` (unbounded) — matching the existing
|
||||
``HERMES_CONCURRENT_TOOL_TIMEOUT_S`` "0 disables the bound" convention.
|
||||
* Values above :data:`MAX_SAFE_TIMEOUT_S` are capped so they can never
|
||||
overflow ``time_t`` inside ``Lock.acquire`` / ``Thread.join`` on macOS
|
||||
(#83220).
|
||||
* Non-numeric values are treated as unset (``None``) with a warning
|
||||
rather than crashing the call path they were meant to protect.
|
||||
"""
|
||||
"""Normalize a timeout: None/non-positive/non-numeric/NaN -> None (unbounded), else capped."""
|
||||
if timeout is None:
|
||||
return None
|
||||
try:
|
||||
value = float(timeout)
|
||||
except (TypeError, ValueError):
|
||||
logger.warning(
|
||||
"clamp_timeout: non-numeric timeout %r; treating as unbounded", timeout
|
||||
)
|
||||
logger.warning("clamp_timeout: non-numeric timeout %r; treating as unbounded", timeout)
|
||||
return None
|
||||
if value != value: # NaN
|
||||
logger.warning("clamp_timeout: NaN timeout; treating as unbounded")
|
||||
@@ -215,18 +127,11 @@ def clamp_timeout(timeout: Optional[float]) -> Optional[float]:
|
||||
return min(value, MAX_SAFE_TIMEOUT_S)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Timeout resolution: config.yaml ``timeouts:`` section > legacy env var >
|
||||
# registered default.
|
||||
# ---------------------------------------------------------------------------
|
||||
# --- Timeout resolution: config ``timeouts:`` > legacy env var > default ------
|
||||
|
||||
|
||||
def _timeouts_section() -> dict:
|
||||
"""Read the ``timeouts:`` root section from config.yaml (read-only).
|
||||
|
||||
Isolated for testability and so a broken config read can never take down
|
||||
the call path the timeout was protecting.
|
||||
"""
|
||||
"""Read the ``timeouts:`` root section from config.yaml (read-only, fail-open)."""
|
||||
try:
|
||||
from hermes_cli.config import load_config_readonly
|
||||
|
||||
@@ -253,30 +158,16 @@ def resolve_timeout(
|
||||
default: Optional[float],
|
||||
env_var: Optional[str] = None,
|
||||
) -> Optional[float]:
|
||||
"""Resolve a timeout in seconds for a dotted config key.
|
||||
"""Resolve a timeout (seconds) for dotted ``timeouts.<key>`` > ``env_var`` > ``default``.
|
||||
|
||||
Precedence (established by the ``providers.*.request_timeout_seconds``
|
||||
pattern — config wins over the legacy env var):
|
||||
|
||||
1. ``timeouts.<key>`` in config.yaml (dotted key walks nested maps, e.g.
|
||||
``tools.concurrent_batch`` reads ``timeouts: {tools: {concurrent_batch: ...}}``)
|
||||
2. ``env_var`` when set and non-empty (legacy bridge — internal mechanism
|
||||
and back-compat only; new surfaces must not grow new user-facing
|
||||
``HERMES_*`` timeout env vars)
|
||||
3. ``default``
|
||||
|
||||
The winning value is passed through :func:`clamp_timeout`, so ``0`` or a
|
||||
negative value means "unbounded" and oversized values are made
|
||||
platform-safe. Invalid (non-numeric) config/env values fall through to
|
||||
the next source with a warning instead of breaking the protected path.
|
||||
The winner goes through :func:`clamp_timeout`; invalid config/env values fall
|
||||
through to the next source with a warning.
|
||||
"""
|
||||
raw = _lookup_dotted(_timeouts_section(), key)
|
||||
if raw is not None:
|
||||
# Explicit float() (clamp_timeout would also convert) so that invalid
|
||||
# config values FALL THROUGH to the env var / default instead of
|
||||
# resolving as unbounded — do not "simplify" this away. bool is
|
||||
# rejected because YAML `true` would silently become a 1-second
|
||||
# deadline; NaN is rejected for the same fall-through reason.
|
||||
# Explicit float() so invalid config values FALL THROUGH to env/default instead of
|
||||
# resolving as unbounded. bool rejected (YAML `true` would become a 1s deadline);
|
||||
# NaN rejected for the same fall-through reason.
|
||||
if not isinstance(raw, bool):
|
||||
try:
|
||||
value = float(raw)
|
||||
@@ -284,9 +175,7 @@ def resolve_timeout(
|
||||
return clamp_timeout(value)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
logger.warning(
|
||||
"timeouts.%s: invalid value %r in config.yaml; ignoring", key, raw
|
||||
)
|
||||
logger.warning("timeouts.%s: invalid value %r in config.yaml; ignoring", key, raw)
|
||||
|
||||
if env_var:
|
||||
env_raw = os.getenv(env_var, "").strip()
|
||||
@@ -299,15 +188,9 @@ def resolve_timeout(
|
||||
return clamp_timeout(default)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Bounded execution — async flavor.
|
||||
#
|
||||
# Generalizes plugins/platforms/telegram/adapter.py:_await_with_thread_deadline
|
||||
# (the #63309 fix): the deadline is driven by a daemon threading.Timer so a
|
||||
# blocked event loop cannot disable it, and a second timer dumps all thread
|
||||
# stacks when the loop provably failed to process the expiry — the one piece
|
||||
# of information loop-blocked hangs otherwise never surface.
|
||||
# ---------------------------------------------------------------------------
|
||||
# --- Bounded execution — async flavor ------------------------------------------
|
||||
# The deadline is a daemon threading.Timer so a blocked event loop cannot disable it; a
|
||||
# second timer dumps all thread stacks when the loop provably failed to process the expiry.
|
||||
|
||||
|
||||
def _consume_abandoned(task: "asyncio.Future[Any]") -> None:
|
||||
@@ -319,8 +202,14 @@ def _consume_abandoned(task: "asyncio.Future[Any]") -> None:
|
||||
pass
|
||||
|
||||
|
||||
def _abandon(task: "asyncio.Future[Any]") -> None:
|
||||
"""Cancel ``task`` and never await it; its outcome is consumed so it stays unobserved-safe."""
|
||||
task.cancel()
|
||||
task.add_done_callback(_consume_abandoned)
|
||||
|
||||
|
||||
async def _run_abandon_cleanup(on_abandon: Callable[[], Awaitable[Any]]) -> None:
|
||||
"""Run abandonment cleanup fully fire-and-forget (its failures swallowed)."""
|
||||
"""Run abandonment cleanup fire-and-forget (its failures swallowed)."""
|
||||
try:
|
||||
await on_abandon()
|
||||
except Exception:
|
||||
@@ -355,30 +244,15 @@ async def run_bounded_async(
|
||||
) -> BoundedResult:
|
||||
"""Await ``awaitable`` under a wall-clock deadline independent of loop timers.
|
||||
|
||||
On completion returns ``BoundedResult(timed_out=False, value=...)``;
|
||||
exceptions from the operation (including ``asyncio.CancelledError`` from a
|
||||
caller cancelling *us*) propagate unchanged.
|
||||
|
||||
On timeout the underlying task is cancelled and **abandoned** — we do not
|
||||
await cancellation completion, because cancellation-shielded scopes (anyio,
|
||||
httpcore init, MCP SDK teardown) are exactly the paths that wedge forever.
|
||||
``on_abandon`` (zero-arg callable returning an awaitable) is scheduled as
|
||||
detached best-effort cleanup for the half-built state the abandoned task
|
||||
may leave behind. Returns ``BoundedResult(timed_out=True, value=None)``.
|
||||
|
||||
``timeout=None`` (or a non-positive resolved value) awaits unbounded.
|
||||
Operation exceptions (incl. ``CancelledError`` from a caller cancelling *us*)
|
||||
propagate unchanged. On timeout the task is cancelled and **abandoned** (never
|
||||
awaited — cancellation-shielded scopes are exactly the paths that wedge), and
|
||||
``on_abandon`` is scheduled as detached best-effort cleanup.
|
||||
"""
|
||||
timeout_s = clamp_timeout(timeout)
|
||||
start = time.monotonic()
|
||||
if timeout_s is None:
|
||||
value = await awaitable
|
||||
return BoundedResult(
|
||||
timed_out=False,
|
||||
value=value,
|
||||
elapsed_s=time.monotonic() - start,
|
||||
timeout_s=None,
|
||||
label=label,
|
||||
)
|
||||
return _result(start, None, label, value=await awaitable)
|
||||
|
||||
task = asyncio.ensure_future(awaitable)
|
||||
loop = asyncio.get_running_loop()
|
||||
@@ -390,84 +264,44 @@ async def run_bounded_async(
|
||||
if not deadline.done():
|
||||
deadline.set_result(None)
|
||||
|
||||
def _expire_from_thread() -> None:
|
||||
loop.call_soon_threadsafe(_mark_expired)
|
||||
|
||||
def _watchdog_check() -> None:
|
||||
if not loop_processed_expiry.is_set():
|
||||
_dump_blocked_loop_diagnostics(label, timeout_s)
|
||||
|
||||
timer = threading.Timer(timeout_s, _expire_from_thread)
|
||||
timer.daemon = True
|
||||
timer.start()
|
||||
watchdog: Optional[threading.Timer] = None
|
||||
timers = [threading.Timer(timeout_s, lambda: loop.call_soon_threadsafe(_mark_expired))]
|
||||
if dump_on_blocked_loop:
|
||||
watchdog = threading.Timer(
|
||||
timeout_s + _LOOP_BLOCKED_DUMP_GRACE_S, _watchdog_check
|
||||
)
|
||||
watchdog.daemon = True
|
||||
watchdog.start()
|
||||
timers.append(threading.Timer(timeout_s + _LOOP_BLOCKED_DUMP_GRACE_S, _watchdog_check))
|
||||
for t in timers:
|
||||
t.daemon = True
|
||||
t.start()
|
||||
try:
|
||||
try:
|
||||
done, _ = await asyncio.wait(
|
||||
{task, deadline}, return_when=asyncio.FIRST_COMPLETED
|
||||
)
|
||||
done, _ = await asyncio.wait({task, deadline}, return_when=asyncio.FIRST_COMPLETED)
|
||||
except asyncio.CancelledError:
|
||||
# The CALLER cancelled us. Without this, `task` would keep running
|
||||
# unobserved (and later log "exception was never retrieved") —
|
||||
# a leak the telegram original also had. Cancel + abandon it, then
|
||||
# let the cancellation propagate.
|
||||
task.cancel()
|
||||
task.add_done_callback(_consume_abandoned)
|
||||
_abandon(task) # the CALLER cancelled us; `task` must not run unobserved
|
||||
raise
|
||||
if task in done:
|
||||
if not deadline.done():
|
||||
deadline.cancel()
|
||||
value = await task
|
||||
return BoundedResult(
|
||||
timed_out=False,
|
||||
value=value,
|
||||
elapsed_s=time.monotonic() - start,
|
||||
timeout_s=timeout_s,
|
||||
label=label,
|
||||
)
|
||||
return _result(start, timeout_s, label, value=await task)
|
||||
|
||||
task.cancel()
|
||||
task.add_done_callback(_consume_abandoned)
|
||||
_abandon(task)
|
||||
if on_abandon is not None:
|
||||
cleanup = asyncio.ensure_future(_run_abandon_cleanup(on_abandon))
|
||||
cleanup.add_done_callback(_consume_abandoned)
|
||||
# Phase 3a (#85125): the abandoned task may leave the backend
|
||||
# half-wedged; flag it so the owner recycles before reuse.
|
||||
# Deliberately INLINE on the loop (adopter contract: mark_suspect is
|
||||
# cheap and non-blocking). Running it synchronously guarantees the
|
||||
# mark happens-before this BoundedResult returns AND before the
|
||||
# ensure_future'd on_abandon cleanup can start (next loop tick) — an
|
||||
# offloaded mark would race both.
|
||||
asyncio.ensure_future(_run_abandon_cleanup(on_abandon)).add_done_callback(_consume_abandoned)
|
||||
# Deliberately INLINE on the loop: the mark must happen-before this result returns
|
||||
# AND before the ensure_future'd on_abandon cleanup starts (next tick).
|
||||
_mark_backend_suspect(backend, label, timeout_s)
|
||||
logger.warning(
|
||||
"[deadline] %r timed out after %.1fs; task abandoned", label, timeout_s
|
||||
)
|
||||
return BoundedResult(
|
||||
timed_out=True,
|
||||
value=None,
|
||||
elapsed_s=time.monotonic() - start,
|
||||
timeout_s=timeout_s,
|
||||
label=label,
|
||||
)
|
||||
logger.warning("[deadline] %r timed out after %.1fs; task abandoned", label, timeout_s)
|
||||
return _result(start, timeout_s, label, timed_out=True)
|
||||
finally:
|
||||
timer.cancel()
|
||||
if watchdog is not None:
|
||||
watchdog.cancel()
|
||||
# cancel() cannot stop a Timer whose callback is already running;
|
||||
# setting the event closes that race so a completed await can never
|
||||
# be misreported as a blocked loop.
|
||||
for t in timers:
|
||||
t.cancel()
|
||||
# cancel() cannot stop a Timer whose callback is already running; setting the
|
||||
# event closes that race so a completed await is never misreported as blocked.
|
||||
loop_processed_expiry.set()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Bounded execution — sync flavor.
|
||||
# ---------------------------------------------------------------------------
|
||||
# --- Bounded execution — sync flavor -------------------------------------------
|
||||
|
||||
|
||||
def run_bounded_sync(
|
||||
@@ -480,37 +314,15 @@ def run_bounded_sync(
|
||||
) -> BoundedResult:
|
||||
"""Run ``fn`` in a daemon worker thread under a wall-clock deadline.
|
||||
|
||||
On completion returns its value (exceptions re-raised in the caller).
|
||||
On expiry the worker thread is **abandoned** (daemon, so it cannot block
|
||||
interpreter exit), ``on_timeout`` (if given) runs best-effort in the
|
||||
caller's thread — e.g. to mark a backend suspect or kill a subprocess —
|
||||
and ``BoundedResult(timed_out=True)`` is returned.
|
||||
|
||||
Intended for infrequent, seconds-scale blocking backend calls. Do NOT
|
||||
use per-item in hot loops: each call spawns a thread, and every timeout
|
||||
permanently leaks an abandoned daemon thread — a wedged backend called
|
||||
in a retry loop would accumulate them.
|
||||
|
||||
``timeout=None`` (or non-positive) blocks until ``fn`` returns.
|
||||
|
||||
The worker runs under ``contextvars.copy_context()`` so profile secret
|
||||
scope, session id, and delegated-child guards set on the caller survive
|
||||
the thread hop (terminal env.execute — #94285 CI).
|
||||
|
||||
The caller's wait is sliced (``_BOUNDED_SYNC_WAIT_SLICE_S``) so a
|
||||
``KeyboardInterrupt`` or ``PyThreadState_SetAsyncExc`` lands within
|
||||
that window instead of only at the full deadline.
|
||||
Exceptions re-raise in the caller. On expiry the worker is **abandoned** and
|
||||
``on_timeout`` runs best-effort in the caller's thread. Every timeout leaks one
|
||||
daemon thread, so do NOT use per-item in hot loops. The worker runs under
|
||||
``contextvars.copy_context()`` so secret scope / session id survive the hop.
|
||||
"""
|
||||
timeout_s = clamp_timeout(timeout)
|
||||
start = time.monotonic()
|
||||
if timeout_s is None:
|
||||
return BoundedResult(
|
||||
timed_out=False,
|
||||
value=fn(),
|
||||
elapsed_s=time.monotonic() - start,
|
||||
timeout_s=None,
|
||||
label=label,
|
||||
)
|
||||
return _result(start, None, label, value=fn())
|
||||
|
||||
box: dict[str, Any] = {}
|
||||
done = threading.Event()
|
||||
@@ -534,67 +346,35 @@ def run_bounded_sync(
|
||||
done.wait(min(_BOUNDED_SYNC_WAIT_SLICE_S, remaining))
|
||||
|
||||
if not done.is_set():
|
||||
logger.warning(
|
||||
"[deadline] %r timed out after %.1fs; worker abandoned", label, timeout_s
|
||||
)
|
||||
# Phase 3a (#85125), ordering: mark suspect BEFORE owner cleanup so a
|
||||
# recycle/re-init in on_timeout never gets a stale flag on the healed
|
||||
# replacement. The sync flavor runs the mark inline — the protocol
|
||||
# contract requires mark_suspect to be cheap.
|
||||
logger.warning("[deadline] %r timed out after %.1fs; worker abandoned", label, timeout_s)
|
||||
# Mark suspect BEFORE owner cleanup so a recycle in on_timeout never
|
||||
# inherits a stale flag on the healed replacement.
|
||||
_mark_backend_suspect(backend, label, timeout_s)
|
||||
if on_timeout is not None:
|
||||
try:
|
||||
on_timeout()
|
||||
except Exception:
|
||||
logger.debug("deadline on_timeout callback failed", exc_info=True)
|
||||
return BoundedResult(
|
||||
timed_out=True,
|
||||
value=None,
|
||||
elapsed_s=time.monotonic() - start,
|
||||
timeout_s=timeout_s,
|
||||
label=label,
|
||||
)
|
||||
return _result(start, timeout_s, label, timed_out=True)
|
||||
|
||||
if "exc" in box:
|
||||
raise box["exc"]
|
||||
return BoundedResult(
|
||||
timed_out=False,
|
||||
value=box.get("value"),
|
||||
elapsed_s=time.monotonic() - start,
|
||||
timeout_s=timeout_s,
|
||||
label=label,
|
||||
)
|
||||
return _result(start, timeout_s, label, value=box.get("value"))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Whole-tree process termination.
|
||||
# ---------------------------------------------------------------------------
|
||||
# --- Whole-tree process termination --------------------------------------------
|
||||
|
||||
|
||||
def kill_process_tree(pid: int, *, sig: Optional[int] = None) -> bool:
|
||||
"""Terminate ``pid`` and all its descendants, portably.
|
||||
|
||||
Kill-on-timeout that signals only the direct child orphans process trees
|
||||
(cron scripts, in-container shells, browser daemons — #71148 class).
|
||||
Windows: ``taskkill /F /T`` (``sig`` ignored). POSIX: descendants are snapshotted
|
||||
via psutil BEFORE signalling (once the parent dies they reparent and a parent walk
|
||||
finds nothing), then the process group is signalled when ``pid`` leads one, and
|
||||
every snapshotted descendant individually — which also reaches children that
|
||||
``setsid`` into their own session. ``sig`` defaults to ``SIGKILL``.
|
||||
|
||||
* Windows: ``taskkill /F /T`` terminates the tree (``sig`` ignored;
|
||||
Windows has no equivalent). Console-window flash is suppressed via
|
||||
``windows_hide_flags`` and the exit code is checked, so a dead or
|
||||
inaccessible PID reports ``False`` like the POSIX path.
|
||||
* POSIX: the descendant set is snapshotted via psutil (a hard
|
||||
dependency) BEFORE any signal — once the parent dies its children are
|
||||
reparented and can no longer be found by a parent walk. Then the
|
||||
process group is signalled when ``pid`` leads one (covers
|
||||
grandchildren in the same session in one syscall), and every
|
||||
snapshotted descendant is signalled individually — which also reaches
|
||||
descendants that created their OWN sessions (a child that called
|
||||
``setsid``, exactly what user shell commands do; see
|
||||
tools/environments/base.py). ``sig`` defaults to ``SIGKILL``.
|
||||
psutil's identity-aware ``Process`` (PID + create time) means a
|
||||
recycled PID is never signalled.
|
||||
|
||||
Returns True when the target (or any of its tree) was signalled, False
|
||||
when the process was already gone or every termination call failed.
|
||||
Returns True when the target (or any of its tree) was signalled.
|
||||
"""
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
@@ -611,13 +391,10 @@ def kill_process_tree(pid: int, *, sig: Optional[int] = None) -> bool:
|
||||
check=False,
|
||||
creationflags=creationflags,
|
||||
)
|
||||
# taskkill exits non-zero for not-found / access-denied; keep the
|
||||
# cross-platform contract (False = nothing was terminated).
|
||||
# taskkill exits non-zero for not-found / access-denied (False = nothing terminated).
|
||||
return proc.returncode == 0
|
||||
except Exception:
|
||||
logger.debug(
|
||||
"kill_process_tree: taskkill failed for pid %s", pid, exc_info=True
|
||||
)
|
||||
logger.debug("kill_process_tree: taskkill failed for pid %s", pid, exc_info=True)
|
||||
return False
|
||||
|
||||
import signal as _signal
|
||||
@@ -625,34 +402,25 @@ def kill_process_tree(pid: int, *, sig: Optional[int] = None) -> bool:
|
||||
if sig is None:
|
||||
sig = _signal.SIGKILL
|
||||
|
||||
# Snapshot descendants while the parent is still alive — after it dies
|
||||
# they reparent to init/subreaper and a parent walk finds nothing.
|
||||
descendants: list = []
|
||||
try:
|
||||
import psutil
|
||||
|
||||
descendants = psutil.Process(int(pid)).children(recursive=True)
|
||||
except Exception:
|
||||
# Already gone, or psutil unavailable in a stripped env — the
|
||||
# group-signal below still covers same-session descendants.
|
||||
# Already gone, or psutil unavailable — the group signal still covers same-session descendants.
|
||||
descendants = []
|
||||
|
||||
signalled = False
|
||||
try:
|
||||
# NOTE: getpgid→killpg has an inherent TOCTOU (pid could be reaped and
|
||||
# recycled between the calls). All existing killpg sites share it; the
|
||||
# psutil sweep below is identity-aware and does not.
|
||||
# getpgid→killpg has an inherent TOCTOU shared by every killpg site; the psutil
|
||||
# sweep below is identity-aware (PID + create time) and does not.
|
||||
pgid = os.getpgid(pid)
|
||||
except (ProcessLookupError, PermissionError, OSError):
|
||||
pgid = None
|
||||
try:
|
||||
if pgid is not None and pgid == pid:
|
||||
# pid leads its own group: one syscall covers the whole group.
|
||||
# (The == check guards against signalling the caller's own group
|
||||
# when pid is not a leader.)
|
||||
os.killpg( # windows-footgun: ok — POSIX-only branch (win32 returns above)
|
||||
pgid, sig
|
||||
)
|
||||
# pid leads its own group (the == check avoids signalling the caller's group).
|
||||
os.killpg(pgid, sig) # windows-footgun: ok — POSIX-only branch (win32 returns above)
|
||||
else:
|
||||
os.kill(pid, sig)
|
||||
signalled = True
|
||||
@@ -661,8 +429,6 @@ def kill_process_tree(pid: int, *, sig: Optional[int] = None) -> bool:
|
||||
except (PermissionError, OSError):
|
||||
logger.debug("kill_process_tree: signal failed for pid %s", pid, exc_info=True)
|
||||
|
||||
# Sweep the snapshot: reaches descendants outside the parent's group
|
||||
# (their own setsid sessions) and the non-group-leader case.
|
||||
for child in descendants:
|
||||
try:
|
||||
if child.is_running(): # identity-aware: recycled PIDs skipped
|
||||
|
||||
+39
-87
@@ -1,36 +1,23 @@
|
||||
"""Context-local state for delegate_task child execution.
|
||||
|
||||
The parent Hermes process may itself be a Kanban dispatcher worker with
|
||||
HERMES_KANBAN_* variables in process env. delegate_task children run inside the
|
||||
same Python process, but they are not dispatcher-owned Kanban workers. This
|
||||
module lets code paths that resolve tool schemas or spawn subprocesses fail
|
||||
closed for delegated children without mutating global os.environ for the parent.
|
||||
|
||||
Cron jobs need the same treatment for the same reason: ``cronjob(action="run")``
|
||||
executes ``run_job()`` in-process, so a cron agent fired from inside a Kanban
|
||||
worker would otherwise inherit that worker's dispatcher identity.
|
||||
``non_dispatcher_owned_context()`` covers both cases.
|
||||
A Hermes process may itself be a Kanban dispatcher worker with HERMES_KANBAN_*
|
||||
in os.environ. delegate_task children (in-process) and cron jobs fired via
|
||||
``cronjob(action="run")`` are NOT dispatcher-owned, so identity gates must
|
||||
fail closed for them without mutating the process-global environment.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar, Token
|
||||
from typing import Iterator, Mapping, MutableMapping
|
||||
|
||||
_DELEGATED_CHILD_CONTEXT: ContextVar[bool] = ContextVar(
|
||||
"hermes_delegated_child_context",
|
||||
default=False,
|
||||
)
|
||||
_DELEGATED_CHILD_CONTEXT: ContextVar[bool] = ContextVar("hermes_delegated_child_context", default=False)
|
||||
|
||||
# Set for any in-process execution that is NOT the dispatcher-owned worker even
|
||||
# though the worker's HERMES_KANBAN_* vars are legitimately in os.environ (cron
|
||||
# jobs fired via the `cronjob` tool). Kept separate from
|
||||
# _DELEGATED_CHILD_CONTEXT so the delegate_task-specific behaviour attached to
|
||||
# that flag (subprocess env scrubbing, its own error strings) is unchanged.
|
||||
_NON_DISPATCHER_OWNED_CONTEXT: ContextVar[bool] = ContextVar(
|
||||
"hermes_non_dispatcher_owned_context",
|
||||
default=False,
|
||||
)
|
||||
# Any in-process execution that is NOT the dispatcher-owned worker (cron jobs).
|
||||
# Kept separate from _DELEGATED_CHILD_CONTEXT so delegate_task-specific
|
||||
# behaviour (subprocess env scrubbing, its error strings) is unchanged.
|
||||
_NON_DISPATCHER_OWNED_CONTEXT: ContextVar[bool] = ContextVar("hermes_non_dispatcher_owned_context", default=False)
|
||||
|
||||
DELEGATED_CHILD_ENV_MARKER = "HERMES_DELEGATED_CHILD_CONTEXT"
|
||||
|
||||
@@ -49,14 +36,12 @@ KANBAN_ENV_KEYS: tuple[str, ...] = (
|
||||
def delegated_child_context(session_id: str | None = None) -> Iterator[None]:
|
||||
"""Mark child execution and isolate its task-local session identity.
|
||||
|
||||
Child construction calls ``set_current_session_id`` internally, so even a
|
||||
context entered without an id must restore the parent's ContextVar. Child
|
||||
execution passes its explicit id and receives it only for this scope.
|
||||
Even a context entered without an id must restore the parent's session
|
||||
ContextVar (child construction calls ``set_current_session_id``).
|
||||
"""
|
||||
token = _DELEGATED_CHILD_CONTEXT.set(True)
|
||||
try:
|
||||
# Import lazily: session_context calls is_delegated_child_context() when
|
||||
# deciding whether the compatibility os.environ mirror is safe.
|
||||
# Lazy: session_context calls is_delegated_child_context().
|
||||
from gateway.session_context import scoped_current_session_id
|
||||
|
||||
with scoped_current_session_id(session_id):
|
||||
@@ -70,49 +55,8 @@ def is_delegated_child_context() -> bool:
|
||||
return bool(_DELEGATED_CHILD_CONTEXT.get())
|
||||
|
||||
|
||||
@contextmanager
|
||||
def non_dispatcher_owned_context() -> Iterator[None]:
|
||||
"""Mark in-process execution that does NOT own the dispatcher's Kanban task.
|
||||
|
||||
A Kanban worker is a normal CLI agent whose default toolset includes
|
||||
``cronjob``; ``cronjob(action="run")`` runs ``run_job()`` inside the worker's
|
||||
own process, where ``HERMES_KANBAN_TASK`` is legitimately set. Without this
|
||||
marker the cron agent is misread as that worker: the kanban toolset is
|
||||
force-added, the worker protocol is injected into its system prompt, and
|
||||
``kanban_complete`` defaults ``task_id`` to ``$HERMES_KANBAN_TASK`` — letting
|
||||
an unrelated cron job close the worker's task and overwrite real results.
|
||||
|
||||
Scoped via ContextVar rather than by clearing ``os.environ``: the env is
|
||||
process-global and shared with the worker's own claim heartbeat, the
|
||||
gateway's Kanban watchers, and concurrent cron jobs on the parallel pool, so
|
||||
mutating it would starve the worker's claim and race those readers.
|
||||
"""
|
||||
token = _NON_DISPATCHER_OWNED_CONTEXT.set(True)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_NON_DISPATCHER_OWNED_CONTEXT.reset(token)
|
||||
|
||||
|
||||
def is_dispatcher_owned_worker_context() -> bool:
|
||||
"""Return True only when this execution owns the dispatcher's Kanban task.
|
||||
|
||||
The single predicate every ``HERMES_KANBAN_*`` identity gate should use
|
||||
before trusting those vars. False for delegate_task children and for cron
|
||||
jobs fired in-process from a worker.
|
||||
"""
|
||||
if _DELEGATED_CHILD_CONTEXT.get():
|
||||
return False
|
||||
return not _NON_DISPATCHER_OWNED_CONTEXT.get()
|
||||
|
||||
|
||||
def enter_non_dispatcher_owned_context() -> Token[bool]:
|
||||
"""Token-based form of :func:`non_dispatcher_owned_context`.
|
||||
|
||||
For callers whose scope is a long ``try`` with a matching ``finally`` rather
|
||||
than a ``with`` block (``cron.scheduler.run_job``). Pair with
|
||||
:func:`exit_non_dispatcher_owned_context`.
|
||||
"""
|
||||
"""Token form of :func:`non_dispatcher_owned_context` for long try/finally scopes."""
|
||||
return _NON_DISPATCHER_OWNED_CONTEXT.set(True)
|
||||
|
||||
|
||||
@@ -121,13 +65,30 @@ def exit_non_dispatcher_owned_context(token: Token[bool]) -> None:
|
||||
_NON_DISPATCHER_OWNED_CONTEXT.reset(token)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def non_dispatcher_owned_context() -> Iterator[None]:
|
||||
"""Mark in-process execution that does NOT own the dispatcher's Kanban task.
|
||||
|
||||
Without it a cron agent run inside a worker is misread as that worker
|
||||
(kanban toolset force-added, ``kanban_complete`` defaulting to its task).
|
||||
ContextVar-scoped rather than clearing os.environ, which the worker's claim
|
||||
heartbeat and concurrent readers share.
|
||||
"""
|
||||
token = enter_non_dispatcher_owned_context()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
exit_non_dispatcher_owned_context(token)
|
||||
|
||||
|
||||
def is_dispatcher_owned_worker_context() -> bool:
|
||||
"""The single predicate every ``HERMES_KANBAN_*`` identity gate should use."""
|
||||
return not (_DELEGATED_CHILD_CONTEXT.get() or _NON_DISPATCHER_OWNED_CONTEXT.get())
|
||||
|
||||
|
||||
def is_delegated_child_process_context() -> bool:
|
||||
"""Return True in this process or a subprocess spawned by a child."""
|
||||
import os
|
||||
|
||||
return bool(_DELEGATED_CHILD_CONTEXT.get()) or bool(
|
||||
os.environ.get(DELEGATED_CHILD_ENV_MARKER)
|
||||
)
|
||||
return bool(_DELEGATED_CHILD_CONTEXT.get()) or bool(os.environ.get(DELEGATED_CHILD_ENV_MARKER))
|
||||
|
||||
|
||||
def scrub_kanban_env(env: Mapping[str, str] | MutableMapping[str, str]) -> dict[str, str]:
|
||||
@@ -144,18 +105,9 @@ def delegated_child_subprocess_env(
|
||||
) -> dict[str, str] | None:
|
||||
"""Return an env override only when delegated-child lineage must cross fork.
|
||||
|
||||
Most subprocess call sites historically used ``env=None`` to inherit the
|
||||
process environment. In a ``delegate_task`` child, inheriting as-is leaks
|
||||
parent dispatcher ``HERMES_KANBAN_*`` vars while losing the ContextVar in
|
||||
the new process. This helper preserves normal ``env=None`` semantics for
|
||||
non-delegated calls, and only materializes a scrubbed env when the lineage
|
||||
marker must be propagated across a child-process boundary.
|
||||
Preserves ``env=None`` inherit semantics for non-delegated calls; in a
|
||||
child, materializes a scrubbed env carrying the lineage marker.
|
||||
"""
|
||||
if not is_delegated_child_process_context():
|
||||
return None if env is None else dict(env)
|
||||
|
||||
if env is None:
|
||||
import os
|
||||
|
||||
env = os.environ
|
||||
return scrub_kanban_env(env)
|
||||
return scrub_kanban_env(os.environ if env is None else env)
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
class SSLConfigurationError(Exception):
|
||||
"""Raised when SSL/TLS certificate bundle configuration fails."""
|
||||
pass
|
||||
|
||||
|
||||
class EmptyStreamError(RuntimeError):
|
||||
"""Raised when a provider closes a stream without yielding a response."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class MoAPresetNotFoundError(ValueError):
|
||||
"""Raised when a persisted MoA preset no longer exists in config."""
|
||||
|
||||
+26
-96
@@ -1,78 +1,43 @@
|
||||
"""Global emergency stop (ESTOP) — a resumable pause for NEW work only.
|
||||
|
||||
``hermes pause`` writes a sentinel file at ``$HERMES_HOME/ESTOP``;
|
||||
``hermes resume`` removes it. While the sentinel exists:
|
||||
|
||||
* the cron scheduler skips dispatching due jobs (``cron/scheduler.py:tick``),
|
||||
* the embedded kanban dispatcher skips spawning workers
|
||||
(``gateway/kanban_watchers.py``),
|
||||
* new gateway turns get a brief "Hermes is paused" reply instead of an
|
||||
agent run (``gateway/run.py:_handle_message``).
|
||||
|
||||
In-flight work is NEVER killed — this is pause-new-work, not panic/exit.
|
||||
The check is one or two ``os.stat`` calls (process home + fleet root when
|
||||
they differ) so callers may run it every tick; no caching beyond the OS is
|
||||
performed, so engaging/disengaging takes effect on the very next check.
|
||||
|
||||
The sentinel body is optional JSON ``{"reason": ..., "engaged_at": ...}``.
|
||||
A corrupt or empty file still counts as engaged (fail safe): the pause must
|
||||
hold even if the file was created by ``touch ~/.hermes/ESTOP``.
|
||||
|
||||
Ported from: gastownhall/gastown estop.go (MIT). Related prior art:
|
||||
#26778 (/panic — kill/exit semantics; deliberately different, ours is
|
||||
resumable) and #44617 (interrupting in-flight cron; deliberately out of
|
||||
scope here).
|
||||
``hermes pause`` writes a sentinel at ``$HERMES_HOME/ESTOP``; ``hermes resume``
|
||||
removes it. While it exists the cron scheduler, kanban dispatcher and new
|
||||
gateway turns skip work; in-flight work is never killed. The check is one or
|
||||
two ``os.stat`` calls (process home + fleet root when they differ), uncached,
|
||||
so engaging/disengaging binds on the next check. The sentinel body is optional
|
||||
JSON ``{"reason", "engaged_at"}``; a corrupt/empty file still counts as engaged
|
||||
(fail safe, e.g. ``touch ~/.hermes/ESTOP``). Ported from gastownhall/gastown
|
||||
estop.go (MIT).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
# Same profile-aware / fleet-root resolvers the file-safety guards use (fail-open to ~/.hermes).
|
||||
from agent.file_safety import _hermes_home_path as _hermes_home, _hermes_root_path as _canonical_root
|
||||
|
||||
SENTINEL_NAME = "ESTOP"
|
||||
|
||||
# Per-component "logged already for this engagement" flags so a paused
|
||||
# dispatch loop logs once per engagement instead of once per tick.
|
||||
# Per-component "logged already for this engagement" flags: log once per
|
||||
# engagement, not once per tick.
|
||||
_log_lock = threading.Lock()
|
||||
_logged_components: set[str] = set()
|
||||
|
||||
|
||||
def _hermes_home() -> Path:
|
||||
"""Resolve the active HERMES_HOME (profile-aware) at call time."""
|
||||
try:
|
||||
from hermes_constants import get_hermes_home
|
||||
return get_hermes_home()
|
||||
except Exception:
|
||||
return Path(os.path.expanduser("~/.hermes"))
|
||||
|
||||
|
||||
def _canonical_root() -> Path:
|
||||
"""Fleet-wide Hermes root, even when this process is a profile gateway.
|
||||
|
||||
Profile gateways launch with HERMES_HOME=~/.hermes/profiles/<name>.
|
||||
``hermes pause`` from an operator seat writes ~/.hermes/ESTOP. If we
|
||||
only inspect the profile home, the emergency stop does not bind
|
||||
(jarvis-os/t_7b65ff88: fleet-analyst kept dispatching through pause).
|
||||
"""
|
||||
try:
|
||||
from hermes_constants import get_default_hermes_root
|
||||
return Path(get_default_hermes_root())
|
||||
except Exception:
|
||||
return Path(os.path.expanduser("~/.hermes"))
|
||||
|
||||
|
||||
def sentinel_path() -> Path:
|
||||
"""Path of the ESTOP sentinel this process would write on `hermes pause`."""
|
||||
return _hermes_home() / SENTINEL_NAME
|
||||
|
||||
|
||||
def _candidate_sentinel_paths() -> list:
|
||||
"""Profile home first, then the fleet root if it is a different directory."""
|
||||
"""Profile home first, then the fleet root if it is a different directory: a profile
|
||||
gateway (HERMES_HOME=~/.hermes/profiles/<n>) must still honor an operator's ~/.hermes/ESTOP."""
|
||||
primary = sentinel_path()
|
||||
paths = [primary]
|
||||
try:
|
||||
@@ -83,20 +48,14 @@ def _candidate_sentinel_paths() -> list:
|
||||
if root.resolve() != primary.resolve():
|
||||
paths.append(root)
|
||||
except Exception:
|
||||
# Non-Path test doubles (fail-safe stat fixture) fail .resolve();
|
||||
# the generic comparison below still dedupes plain equal paths.
|
||||
# Non-Path test doubles fail .resolve(); plain equality still dedupes.
|
||||
if root != primary:
|
||||
paths.append(root)
|
||||
return paths
|
||||
|
||||
|
||||
def is_engaged() -> bool:
|
||||
"""Cheap check: is the global emergency stop engaged?
|
||||
|
||||
Engaged if ANY candidate sentinel exists: the process HERMES_HOME
|
||||
(profile-local) or the fleet canonical root (~/.hermes). Fail SAFE on
|
||||
stat errors so an unreadable sentinel still holds the pause.
|
||||
"""
|
||||
"""True if ANY candidate sentinel exists; fail SAFE (True) on stat errors."""
|
||||
saw_stat_error = False
|
||||
for path in _candidate_sentinel_paths():
|
||||
try:
|
||||
@@ -110,10 +69,7 @@ def is_engaged() -> bool:
|
||||
def engage(reason: Optional[str] = None) -> Path:
|
||||
"""Create the ESTOP sentinel. Idempotent; re-engaging updates the file."""
|
||||
path = sentinel_path()
|
||||
payload = {
|
||||
"engaged_at": datetime.now(timezone.utc).isoformat(),
|
||||
"reason": reason or None,
|
||||
}
|
||||
payload = {"engaged_at": datetime.now(timezone.utc).isoformat(), "reason": reason or None}
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
|
||||
@@ -127,34 +83,25 @@ def engage(reason: Optional[str] = None) -> Path:
|
||||
|
||||
|
||||
def disengage() -> bool:
|
||||
"""Remove ESTOP sentinels this process can see.
|
||||
|
||||
Lifts both the process-local sentinel and the fleet-root sentinel so
|
||||
``hermes resume`` from a profile gateway still clears an operator pause
|
||||
written at ~/.hermes/ESTOP.
|
||||
"""
|
||||
"""Remove every visible sentinel (process-local and fleet-root)."""
|
||||
lifted = False
|
||||
for path in _candidate_sentinel_paths():
|
||||
try:
|
||||
path.unlink()
|
||||
lifted = True
|
||||
except FileNotFoundError:
|
||||
continue
|
||||
except (OSError, AttributeError):
|
||||
continue
|
||||
return lifted
|
||||
|
||||
|
||||
def get_state() -> Optional[dict]:
|
||||
"""Return ``{"reason": ..., "engaged_at": ...}`` or None when not engaged.
|
||||
"""Return ``{"reason", "engaged_at"}`` or None when not engaged.
|
||||
|
||||
A sentinel with an unreadable/corrupt body still reports engaged, with
|
||||
both fields None — the pause is authoritative, the metadata is not.
|
||||
An unreadable/corrupt body still reports engaged with both fields None.
|
||||
"""
|
||||
if not is_engaged():
|
||||
return None
|
||||
reason = None
|
||||
engaged_at = None
|
||||
reason = engaged_at = None
|
||||
found = False
|
||||
for path in _candidate_sentinel_paths():
|
||||
try:
|
||||
@@ -185,24 +132,13 @@ def paused_reply() -> Optional[str]:
|
||||
if state is None:
|
||||
return None
|
||||
reason = state.get("reason")
|
||||
if reason:
|
||||
return (
|
||||
f"⏸️ Hermes is paused ({reason}). New work is on hold; "
|
||||
"run `hermes resume` to pick things back up."
|
||||
)
|
||||
return (
|
||||
"⏸️ Hermes is paused. New work is on hold; "
|
||||
"run `hermes resume` to pick things back up."
|
||||
)
|
||||
tag = f" ({reason})" if reason else ""
|
||||
return f"⏸️ Hermes is paused{tag}. New work is on hold; run `hermes resume` to pick things back up."
|
||||
|
||||
|
||||
def check_paused(component: str, logger: logging.Logger) -> bool:
|
||||
"""Return True when engaged, logging once per engagement per component.
|
||||
|
||||
Dispatch loops call this every tick; the log fires on the disengaged→
|
||||
engaged transition for that component and re-arms after a resume, so a
|
||||
long pause doesn't spam one line per tick.
|
||||
"""
|
||||
"""Return True when engaged, logging once per engagement per component
|
||||
(re-armed after a resume)."""
|
||||
if not is_engaged():
|
||||
with _log_lock:
|
||||
_logged_components.discard(component)
|
||||
@@ -223,9 +159,3 @@ def check_paused(component: str, logger: logging.Logger) -> bool:
|
||||
sentinel_path(),
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def _reset_log_state_for_tests() -> None:
|
||||
"""Clear the log-once bookkeeping (test isolation helper)."""
|
||||
with _log_lock:
|
||||
_logged_components.clear()
|
||||
|
||||
+215
-510
@@ -1,4 +1,9 @@
|
||||
"""Shared file safety rules used by both tools and ACP shims."""
|
||||
"""Shared file safety rules used by both tools and ACP shims.
|
||||
|
||||
Every guard here is defense-in-depth, NOT a security boundary: the terminal
|
||||
tool runs as the same OS user and can read/write anything. The value is a
|
||||
clear denial for models that respect tool errors plus a visible audit trail.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -7,22 +12,58 @@ from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def _hermes_home_path() -> Path:
|
||||
"""Resolve the active HERMES_HOME (profile-aware) without circular imports."""
|
||||
def _constants_path(getter_name: str) -> Path:
|
||||
"""Call ``hermes_constants.<getter_name>()`` (local import avoids cycles); ``~/.hermes`` on any failure."""
|
||||
try:
|
||||
from hermes_constants import get_hermes_home # local import to avoid cycles
|
||||
return get_hermes_home()
|
||||
import hermes_constants
|
||||
|
||||
return getattr(hermes_constants, getter_name)()
|
||||
except Exception:
|
||||
return Path(os.path.expanduser("~/.hermes"))
|
||||
|
||||
|
||||
def _hermes_home_path() -> Path:
|
||||
"""Active HERMES_HOME (profile-aware). Tests monkeypatch this name."""
|
||||
return _constants_path("get_hermes_home")
|
||||
|
||||
|
||||
def _hermes_root_path() -> Path:
|
||||
"""Resolve the Hermes root dir (always the parent of any profile, never per-profile)."""
|
||||
"""Hermes root dir (parent of any profile, never per-profile)."""
|
||||
return _constants_path("get_default_hermes_root")
|
||||
|
||||
|
||||
def _hermes_dirs() -> list[Path]:
|
||||
"""Resolved active HERMES_HOME and global root, deduplicated.
|
||||
|
||||
Both are checked so credential stores at <root>/... stay guarded when
|
||||
running under a profile (HERMES_HOME = <root>/profiles/<name>).
|
||||
"""
|
||||
dirs: list[Path] = []
|
||||
for base in (_hermes_home_path(), _hermes_root_path()):
|
||||
try:
|
||||
real = base.resolve()
|
||||
except Exception:
|
||||
continue
|
||||
if real not in dirs:
|
||||
dirs.append(real)
|
||||
return dirs
|
||||
|
||||
|
||||
def _is_under(resolved: str, prefix: str) -> bool:
|
||||
return resolved == prefix or resolved.startswith(prefix + os.sep)
|
||||
|
||||
|
||||
def _under_any(resolved: Path, base: Path) -> bool:
|
||||
try:
|
||||
from hermes_constants import get_default_hermes_root # local import to avoid cycles
|
||||
return get_default_hermes_root()
|
||||
except Exception:
|
||||
return Path(os.path.expanduser("~/.hermes"))
|
||||
resolved.relative_to(base)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def _home_and_resolved(path: str) -> tuple[str, str]:
|
||||
"""``(realpath(~), realpath(expanduser(path)))`` — the write-guard coordinate pair."""
|
||||
return os.path.realpath(os.path.expanduser("~")), os.path.realpath(os.path.expanduser(str(path)))
|
||||
|
||||
|
||||
def build_write_denied_paths(home: str) -> set[str]:
|
||||
@@ -35,26 +76,16 @@ def build_write_denied_paths(home: str) -> set[str]:
|
||||
os.path.join(home, ".ssh", "authorized_keys"),
|
||||
os.path.join(home, ".ssh", "id_rsa"),
|
||||
os.path.join(home, ".ssh", "id_ed25519"),
|
||||
# NOTE: ``~/.ssh/config`` is deliberately NOT hard-denied here.
|
||||
# It carries no private-key bytes and editing it (host aliases,
|
||||
# ProxyJump, VS Code Remote-SSH targets) is a routine, expected
|
||||
# task. Free-writing it is still wrong -- it can carry
|
||||
# ProxyCommand / Match exec directives -- so it is routed through
|
||||
# an approval gate in tools/file_tools.py instead (the same
|
||||
# approve-once/session/always flow the terminal tool already uses
|
||||
# for ~/.ssh writes). See build_write_approval_paths() below and
|
||||
# _check_ssh_config_write() in tools/file_tools.py. Hard-denying
|
||||
# it while the terminal only *asked* was an inconsistency that
|
||||
# made writes look like they flip-flopped between denied and OK.
|
||||
# Active profile .env (or top-level .env when not in profile mode).
|
||||
# ``~/.ssh/config`` is deliberately NOT hard-denied: no key bytes, and
|
||||
# editing it is routine. It can carry ProxyCommand / Match exec, so it
|
||||
# goes through the approval gate instead (build_write_approval_paths).
|
||||
# Both the active-profile and top-level .env: overwriting the root .env
|
||||
# leaks credentials across every profile that inherits from it.
|
||||
str(hermes_home / ".env"),
|
||||
# Top-level .env, even when running under a profile — overwriting it
|
||||
# leaks credentials across every profile that inherits from root (#15981).
|
||||
str(hermes_root / ".env"),
|
||||
# Active profile Anthropic PKCE credential store.
|
||||
# Anthropic PKCE credential stores; the root copy is still read by
|
||||
# default/non-profile sessions when a profile is active.
|
||||
str(hermes_home / ".anthropic_oauth.json"),
|
||||
# Top-level Anthropic PKCE credential store remains sensitive even
|
||||
# when a profile is active; default/non-profile sessions still read it.
|
||||
str(hermes_root / ".anthropic_oauth.json"),
|
||||
# Bitwarden Secrets Manager encrypted disk cache.
|
||||
str(hermes_home / "cache" / "bws_cache.enc.json"),
|
||||
@@ -91,9 +122,7 @@ def build_write_denied_prefixes(home: str) -> list[str]:
|
||||
|
||||
|
||||
def get_safe_write_roots() -> set[str]:
|
||||
"""Return resolved HERMES_WRITE_SAFE_ROOT paths. Supports multiple directories
|
||||
separated by ``os.pathsep`` (``:`` on Unix, ``;`` on Windows).
|
||||
E.g., ``/opt/data:/var/www/html`` on Unix, ``C:\\data;D:\\www`` on Windows."""
|
||||
"""Resolved HERMES_WRITE_SAFE_ROOT paths (``os.pathsep``-separated list)."""
|
||||
env = os.getenv("HERMES_WRITE_SAFE_ROOT", "")
|
||||
if not env:
|
||||
return set()
|
||||
@@ -101,98 +130,55 @@ def get_safe_write_roots() -> set[str]:
|
||||
for path in env.split(os.pathsep):
|
||||
if path:
|
||||
try:
|
||||
resolved = os.path.realpath(os.path.expanduser(path))
|
||||
roots.add(resolved)
|
||||
roots.add(os.path.realpath(os.path.expanduser(path)))
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
return roots
|
||||
|
||||
|
||||
def build_write_approval_paths(home: str) -> set[str]:
|
||||
"""Return paths that require human APPROVAL to write, but are not
|
||||
hard-denied credentials.
|
||||
"""Paths that need human APPROVAL to write but are not hard-denied credentials.
|
||||
|
||||
``~/.ssh/config`` lives here: it is routine to edit (host aliases,
|
||||
ProxyJump, VS Code Remote-SSH targets) and holds no private-key bytes,
|
||||
but it CAN carry ``ProxyCommand`` / ``Match exec`` directives, so a
|
||||
free write is inappropriate. The interactive file tools gate these
|
||||
through an approve-once/session/always prompt (mirroring the terminal
|
||||
tool's existing ``~/.ssh`` write approval); non-interactive callers
|
||||
that cannot prompt (ACP shims, background jobs) treat an
|
||||
approval-required path as denied and fail closed.
|
||||
``~/.ssh/config`` is routine to edit and holds no key bytes, but can carry
|
||||
``ProxyCommand`` / ``Match exec``. Interactive file tools prompt
|
||||
(approve-once/session/always, like the terminal tool's ``~/.ssh`` gate);
|
||||
non-interactive callers (ACP shims, background jobs) fail closed.
|
||||
"""
|
||||
return {
|
||||
os.path.realpath(p)
|
||||
for p in [
|
||||
os.path.join(home, ".ssh", "config"),
|
||||
]
|
||||
}
|
||||
return {os.path.realpath(os.path.join(home, ".ssh", "config"))}
|
||||
|
||||
|
||||
# HERMES_HOME / root subpaths that the agent's generic file tools must not
|
||||
# rewrite. Session transcripts (state.db, sessions/) are application-owned
|
||||
# state whose rewrite can falsify history and break resume/compression;
|
||||
# mcp-tokens/ and pairing/ hold credential material.
|
||||
_HERMES_PROTECTED_SUBPATHS = ("state.db", "sessions", "mcp-tokens", "pairing")
|
||||
|
||||
|
||||
def _classify_write_denial(path: str) -> Optional[str]:
|
||||
"""Return ``'credential'``, ``'safe_root'``, or ``None`` if writes are allowed."""
|
||||
home = os.path.realpath(os.path.expanduser("~"))
|
||||
resolved = os.path.realpath(os.path.expanduser(str(path)))
|
||||
home, resolved = _home_and_resolved(path)
|
||||
|
||||
# Approval-gated paths (e.g. ~/.ssh/config) are NOT hard-denied here:
|
||||
# they are allowed at this layer so the interactive file tools can run
|
||||
# their approval prompt, and only blocked for non-interactive callers
|
||||
# via get_write_approval_error(). Checked before the credential deny so
|
||||
# the ``.ssh/`` directory prefix below doesn't swallow the config file.
|
||||
# Approval-gated paths are allowed at this layer so interactive tools can
|
||||
# prompt; checked first so the ``.ssh/`` prefix deny doesn't swallow them.
|
||||
if resolved in build_write_approval_paths(home):
|
||||
return None
|
||||
|
||||
if resolved in build_write_denied_paths(home):
|
||||
if resolved in build_write_denied_paths(home) or any(
|
||||
resolved.startswith(prefix) for prefix in build_write_denied_prefixes(home)
|
||||
):
|
||||
return "credential"
|
||||
for prefix in build_write_denied_prefixes(home):
|
||||
if resolved.startswith(prefix):
|
||||
return "credential"
|
||||
|
||||
mcp_tokens_dir_name = "mcp-tokens"
|
||||
|
||||
hermes_dirs = []
|
||||
for base in (_hermes_home_path(), _hermes_root_path()):
|
||||
try:
|
||||
real = os.path.realpath(base)
|
||||
if real not in hermes_dirs:
|
||||
hermes_dirs.append(real)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
for base_real in hermes_dirs:
|
||||
# Session transcripts are application-owned state. Letting the agent's
|
||||
# generic file tools rewrite state.db or legacy JSON snapshots can
|
||||
# falsify conversation history and invalidate resume/compression state.
|
||||
try:
|
||||
if resolved == os.path.realpath(os.path.join(base_real, "state.db")):
|
||||
return True
|
||||
sessions_real = os.path.realpath(os.path.join(base_real, "sessions"))
|
||||
if resolved == sessions_real or resolved.startswith(sessions_real + os.sep):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
mcp_real = os.path.realpath(os.path.join(base_real, mcp_tokens_dir_name))
|
||||
if resolved == mcp_real or resolved.startswith(mcp_real + os.sep):
|
||||
return "credential"
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
pairing_real = os.path.realpath(os.path.join(base_real, "pairing"))
|
||||
if resolved == pairing_real or resolved.startswith(pairing_real + os.sep):
|
||||
return "credential"
|
||||
except Exception:
|
||||
pass
|
||||
for base in _hermes_dirs():
|
||||
for sub in _HERMES_PROTECTED_SUBPATHS:
|
||||
try:
|
||||
if _is_under(resolved, os.path.realpath(os.path.join(str(base), sub))):
|
||||
return "credential"
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
safe_roots = get_safe_write_roots()
|
||||
if safe_roots:
|
||||
allowed = False
|
||||
for safe_root in safe_roots:
|
||||
if resolved == safe_root or resolved.startswith(safe_root + os.sep):
|
||||
allowed = True
|
||||
break
|
||||
if not allowed:
|
||||
return "safe_root"
|
||||
if safe_roots and not any(_is_under(resolved, root) for root in safe_roots):
|
||||
return "safe_root"
|
||||
|
||||
return None
|
||||
|
||||
@@ -217,22 +203,13 @@ def get_write_denied_error(path: str, *, verb: str = "Write") -> Optional[str]:
|
||||
|
||||
|
||||
def is_write_approval_required(path: str) -> bool:
|
||||
"""Return True if ``path`` is an approval-gated write target.
|
||||
|
||||
These paths (currently ``~/.ssh/config``) are not credentials and are
|
||||
not hard-denied, but a write to them must be confirmed by a human
|
||||
because they can influence process execution (e.g. an SSH
|
||||
``ProxyCommand``). Callers with an interactive/gateway channel should
|
||||
prompt; callers without one should treat this as a block (fail closed).
|
||||
"""
|
||||
home = os.path.realpath(os.path.expanduser("~"))
|
||||
resolved = os.path.realpath(os.path.expanduser(str(path)))
|
||||
"""True if ``path`` is approval-gated (``~/.ssh/config``): interactive callers
|
||||
prompt, callers without a channel treat it as a block (fail closed)."""
|
||||
home, resolved = _home_and_resolved(path)
|
||||
return resolved in build_write_approval_paths(home)
|
||||
|
||||
|
||||
# Common secret-bearing project-local environment file basenames.
|
||||
# These are blocked because .env files routinely contain API keys,
|
||||
# database passwords, and other credentials.
|
||||
# Secret-bearing project-local env file basenames, blocked anywhere on disk.
|
||||
_BLOCKED_PROJECT_ENV_BASENAMES: set[str] = {
|
||||
".env",
|
||||
".env.local",
|
||||
@@ -243,101 +220,67 @@ _BLOCKED_PROJECT_ENV_BASENAMES: set[str] = {
|
||||
".envrc",
|
||||
}
|
||||
|
||||
_DID_SUFFIX = (
|
||||
" (Defense-in-depth — not a security boundary; the terminal tool can still bypass.)"
|
||||
)
|
||||
|
||||
# Exact-file credential stores under HERMES_HOME / <root>. The agent never
|
||||
# needs these directly — provider tools consume them through internal channels.
|
||||
_CREDENTIAL_FILE_NAMES = (
|
||||
"auth.json",
|
||||
"auth.lock",
|
||||
".anthropic_oauth.json",
|
||||
".env",
|
||||
"webhook_subscriptions.json",
|
||||
os.path.join("auth", "google_oauth.json"),
|
||||
# Bitwarden Secrets Manager disk cache: plaintext secret values.
|
||||
os.path.join("cache", "bws_cache.json"),
|
||||
)
|
||||
|
||||
# Directory-prefix read denies under HERMES_HOME / <root>: (subdir, message for
|
||||
# the directory itself, message for a file inside). browser-profile/ is a copy
|
||||
# of the user's Cookies / Login Data — the same credential class as auth.json.
|
||||
_READ_DENIED_DIRS = (
|
||||
(
|
||||
"mcp-tokens",
|
||||
"is the Hermes MCP token directory and cannot be read directly.",
|
||||
"is a Hermes MCP token file and cannot be read directly.",
|
||||
),
|
||||
(
|
||||
"browser-profile",
|
||||
"is the Hermes real-profile browser snapshot directory (copied "
|
||||
"cookies/logins) and cannot be read directly.",
|
||||
"is inside the Hermes real-profile browser snapshot (copied "
|
||||
"cookies/logins) and cannot be read directly.",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def get_read_block_error(path: str) -> Optional[str]:
|
||||
"""Return an error message when a read targets a denied Hermes path.
|
||||
|
||||
Three categories are blocked:
|
||||
Blocked: internal skill-hub caches (prompt-injection carriers), credential
|
||||
stores under HERMES_HOME and the global root (exact files, plus anything
|
||||
under ``mcp-tokens/`` and ``browser-profile/``), and project-local ``.env``
|
||||
files anywhere on disk (``.env.example`` is the documented-shape substitute).
|
||||
|
||||
* Internal Hermes cache files under ``HERMES_HOME/skills/.hub`` —
|
||||
readable metadata that an attacker could use as a prompt-injection
|
||||
carrier.
|
||||
* Credential / secret stores under HERMES_HOME and the global Hermes
|
||||
root: ``auth.json``, ``auth.lock``, ``.anthropic_oauth.json``,
|
||||
``.env``, ``webhook_subscriptions.json``, ``auth/google_oauth.json``,
|
||||
and anything under ``mcp-tokens/``. These hold plaintext provider keys,
|
||||
OAuth tokens, and HMAC secrets that the agent never needs to read
|
||||
directly — provider tools / gateway adapters consume them through
|
||||
internal channels.
|
||||
* Project-local environment files anywhere on disk: ``.env``,
|
||||
``.env.local``, ``.env.development``, ``.env.production``,
|
||||
``.env.test``, ``.env.staging``, ``.envrc``. These routinely hold
|
||||
API keys, database passwords, and other credentials for the user's
|
||||
own projects. The agent helping debug a project shouldn't normally
|
||||
need to read these — ``.env.example`` is the documented-shape
|
||||
substitute.
|
||||
|
||||
**This is NOT a security boundary.** The terminal tool runs as the
|
||||
same OS user with shell access; the agent can still ``cat auth.json``
|
||||
or ``cat ~/.hermes/.env`` and exfiltrate the file. The read-deny exists
|
||||
as defense-in-depth that:
|
||||
|
||||
* Returns a clear error to models that respect tool denials, which
|
||||
empirically prompts most modern models to stop rather than reach
|
||||
for the shell.
|
||||
* Surfaces a visible audit trail when something tries to read
|
||||
credentials — easier to spot in logs than a generic ``cat``.
|
||||
|
||||
Treat any user-visible framing around this as "may help" rather than
|
||||
"stops attackers." A determined model or malicious instruction can
|
||||
always shell out.
|
||||
|
||||
Callers that resolve relative paths against a non-process cwd
|
||||
(e.g. ``TERMINAL_CWD`` in ``tools/file_tools.py``) MUST pre-resolve
|
||||
and pass the absolute path string. This function's own ``resolve()``
|
||||
is anchored at the Python process cwd, so a relative input like
|
||||
``"auth.json"`` would otherwise miss the denylist when the task's
|
||||
terminal cwd differs from the process cwd.
|
||||
Callers that resolve relative paths against a non-process cwd (e.g.
|
||||
``TERMINAL_CWD``) MUST pass an absolute path: ``resolve()`` here anchors at
|
||||
the process cwd, so a relative ``"auth.json"`` would miss the denylist.
|
||||
"""
|
||||
resolved = Path(path).expanduser().resolve()
|
||||
hermes_dirs = _hermes_dirs()
|
||||
|
||||
# Resolve BOTH the active HERMES_HOME (profile-aware) AND the global
|
||||
# Hermes root so credential stores at <root>/auth.json etc. are also
|
||||
# blocked when running under a profile (HERMES_HOME points at
|
||||
# <root>/profiles/<name> in profile mode). Same shape as the write
|
||||
# deny widening (#15981, #14157).
|
||||
hermes_dirs: list[Path] = []
|
||||
for base in (_hermes_home_path(), _hermes_root_path()):
|
||||
try:
|
||||
real = base.resolve()
|
||||
if real not in hermes_dirs:
|
||||
hermes_dirs.append(real)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# Skills .hub: prompt-injection carriers.
|
||||
for hd in hermes_dirs:
|
||||
blocked_dirs = [
|
||||
hd / "skills" / ".hub" / "index-cache",
|
||||
hd / "skills" / ".hub",
|
||||
]
|
||||
for blocked in blocked_dirs:
|
||||
try:
|
||||
resolved.relative_to(blocked)
|
||||
except ValueError:
|
||||
continue
|
||||
if _under_any(resolved, hd / "skills" / ".hub"):
|
||||
return (
|
||||
f"Access denied: {path} is an internal Hermes cache file "
|
||||
"and cannot be read directly to prevent prompt injection. "
|
||||
"Use the skills_list or skill_view tools instead."
|
||||
)
|
||||
|
||||
# Credential / secret stores. Exact-file matches under either
|
||||
# HERMES_HOME or <root>.
|
||||
credential_file_names = (
|
||||
"auth.json",
|
||||
"auth.lock",
|
||||
".anthropic_oauth.json",
|
||||
".env",
|
||||
"webhook_subscriptions.json",
|
||||
os.path.join("auth", "google_oauth.json"),
|
||||
# Bitwarden Secrets Manager disk cache: stores plaintext secret values
|
||||
# to avoid re-fetching across back-to-back CLI invocations. The file
|
||||
# was introduced by #31968 but not added to this guard.
|
||||
os.path.join("cache", "bws_cache.json"),
|
||||
)
|
||||
for hd in hermes_dirs:
|
||||
for name in credential_file_names:
|
||||
for name in _CREDENTIAL_FILE_NAMES:
|
||||
try:
|
||||
blocked = (hd / name).resolve()
|
||||
except Exception:
|
||||
@@ -346,93 +289,36 @@ def get_read_block_error(path: str) -> Optional[str]:
|
||||
return (
|
||||
f"Access denied: {path} is a Hermes credential store "
|
||||
"and cannot be read directly. Provider tools consume "
|
||||
"these credentials through internal channels. "
|
||||
"(Defense-in-depth — not a security boundary; the "
|
||||
"terminal tool can still bypass.)"
|
||||
"these credentials through internal channels." + _DID_SUFFIX
|
||||
)
|
||||
|
||||
# mcp-tokens/: directory prefix match — anything inside is OAuth
|
||||
# token material.
|
||||
for hd in hermes_dirs:
|
||||
try:
|
||||
mcp_tokens = (hd / "mcp-tokens").resolve()
|
||||
except Exception:
|
||||
continue
|
||||
if resolved == mcp_tokens:
|
||||
return (
|
||||
f"Access denied: {path} is the Hermes MCP token directory "
|
||||
"and cannot be read directly. (Defense-in-depth — not a "
|
||||
"security boundary; the terminal tool can still bypass.)"
|
||||
)
|
||||
try:
|
||||
resolved.relative_to(mcp_tokens)
|
||||
except ValueError:
|
||||
continue
|
||||
return (
|
||||
f"Access denied: {path} is a Hermes MCP token file "
|
||||
"and cannot be read directly. (Defense-in-depth — not a "
|
||||
"security boundary; the terminal tool can still bypass.)"
|
||||
)
|
||||
for subdir, dir_msg, file_msg in _READ_DENIED_DIRS:
|
||||
for hd in hermes_dirs:
|
||||
try:
|
||||
blocked_dir = (hd / subdir).resolve()
|
||||
except Exception:
|
||||
continue
|
||||
if resolved == blocked_dir:
|
||||
return f"Access denied: {path} {dir_msg}{_DID_SUFFIX}"
|
||||
if _under_any(resolved, blocked_dir):
|
||||
return f"Access denied: {path} {file_msg}{_DID_SUFFIX}"
|
||||
|
||||
# browser-profile/: real-profile browsing snapshot (browser.use_real_profile).
|
||||
# A copy of the user's Cookies / Login Data / Web Data lives here — the same
|
||||
# credential class as auth.json, so it gets the same directory-prefix read
|
||||
# deny. Prefix (not a finite filename list) so future Chromium files are
|
||||
# covered too.
|
||||
for hd in hermes_dirs:
|
||||
try:
|
||||
browser_profile = (hd / "browser-profile").resolve()
|
||||
except Exception:
|
||||
continue
|
||||
if resolved == browser_profile:
|
||||
return (
|
||||
f"Access denied: {path} is the Hermes real-profile browser "
|
||||
"snapshot directory (copied cookies/logins) and cannot be read "
|
||||
"directly. (Defense-in-depth — not a security boundary; the "
|
||||
"terminal tool can still bypass.)"
|
||||
)
|
||||
try:
|
||||
resolved.relative_to(browser_profile)
|
||||
except ValueError:
|
||||
continue
|
||||
return (
|
||||
f"Access denied: {path} is inside the Hermes real-profile browser "
|
||||
"snapshot (copied cookies/logins) and cannot be read directly. "
|
||||
"(Defense-in-depth — not a security boundary; the terminal tool "
|
||||
"can still bypass.)"
|
||||
)
|
||||
|
||||
# Block common secret-bearing project-local .env files anywhere on disk.
|
||||
# The agent helping a user with their project rarely needs to read raw
|
||||
# .env contents — .env.example is the documented-shape substitute. The
|
||||
# terminal tool can still ``cat .env``; this is defense-in-depth, not a
|
||||
# boundary (see module docstring).
|
||||
if resolved.name.lower() in _BLOCKED_PROJECT_ENV_BASENAMES:
|
||||
return (
|
||||
f"Access denied: {path} is a secret-bearing environment file "
|
||||
"and cannot be read to prevent credential leakage. "
|
||||
"If you need to check the file structure, read .env.example instead. "
|
||||
"(Defense-in-depth — not a security boundary; the terminal tool can still bypass.)"
|
||||
"If you need to check the file structure, read .env.example instead." + _DID_SUFFIX
|
||||
)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def raise_if_read_blocked(path: str) -> None:
|
||||
"""Raise ``ValueError`` if ``path`` is a denied Hermes read (see
|
||||
:func:`get_read_block_error`), else return.
|
||||
"""Raise ``ValueError`` if ``path`` is a denied Hermes read (see ``get_read_block_error``).
|
||||
|
||||
Shared chokepoint for provider input-loading sites that read a local
|
||||
file the model/tool supplied (e.g. image-gen ``image_url`` /
|
||||
``reference_image_urls`` paths). Centralizes the guard so every provider
|
||||
enforces the same read boundary with identical semantics instead of each
|
||||
open-coding the try/except block (#57698).
|
||||
|
||||
Best-effort by design: if ``agent.file_safety`` machinery is somehow
|
||||
unavailable at the call site the guard no-ops rather than breaking local
|
||||
image loading — consistent with the defense-in-depth (not security
|
||||
boundary) framing of the denylist itself. The blocking ``ValueError`` from
|
||||
a real hit still propagates; only unexpected internal errors are swallowed.
|
||||
Shared chokepoint for provider input-loading sites (e.g. image-gen local
|
||||
paths). Best-effort: unexpected internal errors no-op rather than break
|
||||
local-file loading; a real block still propagates.
|
||||
"""
|
||||
try:
|
||||
blocked = get_read_block_error(path)
|
||||
@@ -442,192 +328,53 @@ def raise_if_read_blocked(path: str) -> None:
|
||||
raise ValueError(blocked)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Cross-profile write guard (#TBD)
|
||||
#
|
||||
# Hermes profiles are separate HERMES_HOME dirs under
|
||||
# ``<root>/profiles/<name>/``. Each profile has its own skills/, plugins/,
|
||||
# cron/, memories/. When an agent runs under one profile, writing into
|
||||
# ANOTHER profile's directories is almost always wrong — those skills /
|
||||
# plugins / cron jobs / memories affect a different session the user runs
|
||||
# from a different shell.
|
||||
#
|
||||
# Soft guard, NOT a security boundary: the agent runs as the same OS user
|
||||
# and has unrestricted terminal access, so this returns a warning the model
|
||||
# can choose to honor or override with ``cross_profile=True``. Same shape
|
||||
# as the dangerous-command approval flow — the agent is told the boundary
|
||||
# exists, and explicit user direction is required to cross it.
|
||||
#
|
||||
# Reference: May 2026 incident where a hermes-security profile session
|
||||
# edited skills under both ``~/.hermes/profiles/hermes-security/skills/``
|
||||
# AND ``~/.hermes/skills/`` (the default profile's skills) without realizing
|
||||
# the second path belonged to a different profile.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Profile-scoped directories under HERMES_HOME / <root> / <root>/profiles/<X>/
|
||||
# that should be guarded. Adding a new area here extends the guard with no
|
||||
# other code change.
|
||||
PROFILE_SCOPED_AREAS = ("skills", "plugins", "cron", "memories")
|
||||
|
||||
|
||||
def _resolve_active_profile_name() -> str:
|
||||
"""Return the active profile name derived from HERMES_HOME.
|
||||
|
||||
``~/.hermes`` -> ``"default"``
|
||||
``~/.hermes/profiles/X`` -> ``"X"``
|
||||
|
||||
Falls back to ``"default"`` on any resolution failure so the guard
|
||||
never raises into the tool path.
|
||||
"""
|
||||
"""Active profile name from HERMES_HOME: ``~/.hermes`` -> ``"default"``,
|
||||
``~/.hermes/profiles/X`` -> ``"X"``; ``"default"`` on any resolution failure."""
|
||||
try:
|
||||
home_real = _hermes_home_path().resolve()
|
||||
root_real = _hermes_root_path().resolve()
|
||||
except (OSError, RuntimeError):
|
||||
return "default"
|
||||
profiles_dir = root_real / "profiles"
|
||||
try:
|
||||
rel = home_real.relative_to(profiles_dir)
|
||||
parts = rel.parts
|
||||
if len(parts) >= 1:
|
||||
parts = home_real.relative_to(root_real / "profiles").parts
|
||||
if parts:
|
||||
return parts[0]
|
||||
except ValueError:
|
||||
pass
|
||||
return "default"
|
||||
|
||||
|
||||
def classify_cross_profile_target(path: str) -> Optional[dict]:
|
||||
"""Classify a write target as cross-profile if it lands in another
|
||||
profile's scoped area (skills/plugins/cron/memories).
|
||||
|
||||
Returns ``None`` when the target is outside Hermes scope, or is inside
|
||||
the ACTIVE profile, or doesn't hit a profile-scoped area. Otherwise
|
||||
returns a dict with:
|
||||
|
||||
* ``active_profile``: name of the profile the agent is running as
|
||||
* ``target_profile``: name of the profile the path belongs to
|
||||
* ``area``: which scoped area (``"skills"``, ``"plugins"``, etc.)
|
||||
* ``target_path``: the resolved path string
|
||||
|
||||
The caller decides what to do with the result — surface a warning to
|
||||
the model, prompt the user, or (with explicit consent /
|
||||
``cross_profile=True``) proceed anyway.
|
||||
"""
|
||||
try:
|
||||
target = Path(os.path.expanduser(str(path))).resolve()
|
||||
root_real = _hermes_root_path().resolve()
|
||||
except (OSError, RuntimeError):
|
||||
return None
|
||||
|
||||
target_profile: Optional[str] = None
|
||||
area: Optional[str] = None
|
||||
|
||||
try:
|
||||
rel = target.relative_to(root_real)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
parts = rel.parts
|
||||
if not parts:
|
||||
return None
|
||||
|
||||
if parts[0] in PROFILE_SCOPED_AREAS:
|
||||
# ``<root>/<area>/...`` → default profile.
|
||||
target_profile = "default"
|
||||
area = parts[0]
|
||||
elif (
|
||||
parts[0] == "profiles"
|
||||
and len(parts) >= 3
|
||||
and parts[2] in PROFILE_SCOPED_AREAS
|
||||
):
|
||||
# ``<root>/profiles/<name>/<area>/...`` → named profile.
|
||||
target_profile = parts[1]
|
||||
area = parts[2]
|
||||
else:
|
||||
return None
|
||||
|
||||
active_profile = _resolve_active_profile_name()
|
||||
if target_profile == active_profile:
|
||||
# In-profile write — not a cross-profile event.
|
||||
return None
|
||||
|
||||
return {
|
||||
"active_profile": active_profile,
|
||||
"target_profile": target_profile,
|
||||
"area": area,
|
||||
"target_path": str(target),
|
||||
}
|
||||
|
||||
|
||||
def get_cross_profile_warning(path: str) -> Optional[str]:
|
||||
"""RETIRED (maintainer decision): always returns ``None``.
|
||||
|
||||
The cross-profile write guard was removed — profiles were never
|
||||
isolated (same OS user; the terminal tool writes anywhere), so the
|
||||
block was ceremony that cost every schema real tokens and taught a
|
||||
bypass arg. The system prompt's active-profile hint remains the only
|
||||
steering; the classifier below survives for that hint and for
|
||||
diagnostics. Kept as a stub so external callers/plugins fail soft.
|
||||
"""
|
||||
"""RETIRED: always ``None``. Profiles were never isolated (same OS user), so
|
||||
the guard was ceremony that taught a bypass arg. Stub kept so external
|
||||
callers/plugins fail soft; the system prompt's active-profile hint remains."""
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Sandbox-mirror write guard (#32049)
|
||||
#
|
||||
# Non-local terminal backends (Docker, Daytona, etc.) bind a sandbox-local
|
||||
# directory to the container's ``$HOME``. The on-disk layout looks like
|
||||
#
|
||||
# --- Sandbox-mirror write guard ---
|
||||
# Non-local terminal backends bind a sandbox-local dir to the container's $HOME:
|
||||
# <HERMES_HOME>/profiles/<name>/sandboxes/<backend>/<task>/home/.hermes/...
|
||||
#
|
||||
# When the agent (running host-side) speculates that authoritative profile
|
||||
# state lives at one of those sandbox-mirror paths, the write lands on the
|
||||
# mirror — never read by the host process — while the host file is left
|
||||
# untouched. The agent reports success, the user sees no change, and on
|
||||
# disk two divergent copies accumulate. See #32049 for evidence.
|
||||
#
|
||||
# This guard is path-shape-only: it detects the
|
||||
# ``…/sandboxes/<backend>/<task>/home/.hermes/…`` segment and warns
|
||||
# regardless of which Hermes profile is active. It does NOT cover the
|
||||
# inner-container case where the bind mount strips the ``sandboxes/`` prefix
|
||||
# (the agent's view inside the container is plain ``/root/.hermes/...``);
|
||||
# that case needs a separate dispatch-layer or host-side ``profile_state``
|
||||
# tool.
|
||||
# ---------------------------------------------------------------------------
|
||||
# A host-side write there lands on a mirror the host never reads: silent
|
||||
# success, divergent copies. Path-shape-only detection, independent of the
|
||||
# active profile. Does NOT cover the inner-container case where the bind mount
|
||||
# strips the prefix — that is classify_container_mirror_target below.
|
||||
|
||||
|
||||
def _find_sandbox_mirror_segments(parts: tuple) -> Optional[int]:
|
||||
"""Return the index of the inner ``.hermes`` part in a sandbox-mirror path.
|
||||
|
||||
Matches ``…/sandboxes/<backend>/<task>/home/.hermes/…`` and returns the
|
||||
index where the inner Hermes-state portion starts. Returns ``None`` for
|
||||
paths that do not contain the sandbox-mirror shape.
|
||||
"""
|
||||
for i, part in enumerate(parts):
|
||||
if part != "sandboxes":
|
||||
continue
|
||||
# Need at least: sandboxes / <backend> / <task> / home / .hermes / <thing>
|
||||
if i + 5 >= len(parts):
|
||||
continue
|
||||
if parts[i + 3] == "home" and parts[i + 4] == ".hermes":
|
||||
return i + 4
|
||||
return None
|
||||
_SANDBOX_MIRROR_WARNING = (
|
||||
"Sandbox-mirror write blocked by soft guard: {target_path} "
|
||||
"sits under {mirror_root!r}, which is {body} "
|
||||
"Use the host-side tool for authoritative state (e.g. ``memory`` for memories), "
|
||||
"or address the host path directly. To bypass {bypass} with ``cross_profile=True``. "
|
||||
"(Defense-in-depth — not a security boundary; the terminal tool can still bypass.)"
|
||||
)
|
||||
|
||||
|
||||
def classify_sandbox_mirror_target(path: str) -> Optional[dict]:
|
||||
"""Classify a write target as a sandbox-mirror of authoritative Hermes state.
|
||||
|
||||
Returns ``None`` when the path does not match the sandbox-mirror shape.
|
||||
Otherwise returns a dict with:
|
||||
|
||||
* ``target_path``: the resolved path string
|
||||
* ``mirror_root``: the ``…/sandboxes/<backend>/<task>/home/.hermes``
|
||||
prefix (so callers can show users which sandbox owns the mirror)
|
||||
* ``inner_path``: the portion under the mirror's ``.hermes`` (what the
|
||||
agent likely meant to address on the host)
|
||||
|
||||
Detection is path-shape-only — does not require any Hermes resolver to
|
||||
succeed, so it works correctly even when called from contexts where
|
||||
HERMES_HOME resolution would be ambiguous.
|
||||
Returns ``None`` for non-mirror paths, else ``target_path`` (resolved),
|
||||
``mirror_root`` (the ``…/home/.hermes`` prefix) and ``inner_path`` (what
|
||||
the agent likely meant to address on the host).
|
||||
"""
|
||||
try:
|
||||
target = Path(os.path.expanduser(str(path))).resolve()
|
||||
@@ -635,66 +382,44 @@ def classify_sandbox_mirror_target(path: str) -> Optional[dict]:
|
||||
return None
|
||||
|
||||
parts = target.parts
|
||||
inner_idx = _find_sandbox_mirror_segments(parts)
|
||||
if inner_idx is None:
|
||||
# Need at least: sandboxes / <backend> / <task> / home / .hermes / <thing>; inner_idx = the .hermes part.
|
||||
for i, part in enumerate(parts):
|
||||
if part == "sandboxes" and i + 5 < len(parts) and parts[i + 3] == "home" and parts[i + 4] == ".hermes":
|
||||
inner_idx = i + 4
|
||||
break
|
||||
else:
|
||||
return None
|
||||
|
||||
mirror_root = str(Path(*parts[: inner_idx + 1]))
|
||||
inner_path = str(Path(*parts[inner_idx + 1 :])) if inner_idx + 1 < len(parts) else ""
|
||||
|
||||
return {
|
||||
"target_path": str(target),
|
||||
"mirror_root": mirror_root,
|
||||
"inner_path": inner_path,
|
||||
"mirror_root": str(Path(*parts[: inner_idx + 1])),
|
||||
"inner_path": str(Path(*parts[inner_idx + 1 :])) if inner_idx + 1 < len(parts) else "",
|
||||
}
|
||||
|
||||
|
||||
def get_sandbox_mirror_warning(path: str) -> Optional[str]:
|
||||
"""Return a model-facing warning when ``path`` lands in a sandbox mirror.
|
||||
|
||||
Returns ``None`` when the path is not a sandbox-mirror target. Caller
|
||||
is expected to surface the warning to the agent as a tool-result
|
||||
error. The bypass kwarg (``cross_profile=True``) is shared with the
|
||||
cross-profile guard: both are soft "I know what I'm doing" overrides
|
||||
a user can authorise.
|
||||
|
||||
Defense-in-depth, NOT a security boundary: the terminal tool runs as
|
||||
the same OS user and can write the mirror path directly. The guard
|
||||
exists to surface the misclassification before the silent-success +
|
||||
divergent-copy footgun in #32049 fires.
|
||||
"""
|
||||
info = classify_sandbox_mirror_target(path)
|
||||
def _mirror_warning(info: Optional[dict], body: str, bypass: str) -> Optional[str]:
|
||||
"""Render ``_SANDBOX_MIRROR_WARNING`` for a classify_* result (``body`` may use ``{inner_path}``)."""
|
||||
if info is None:
|
||||
return None
|
||||
return (
|
||||
f"Sandbox-mirror write blocked by soft guard: {info['target_path']} "
|
||||
f"sits under {info['mirror_root']!r}, which is a per-task mirror "
|
||||
f"created by a non-local terminal backend (docker/daytona/etc.). "
|
||||
f"Writes here land on a copy that the host Hermes process never "
|
||||
f"reads — the authoritative file is likely {info['inner_path']!r} "
|
||||
f"under the real HERMES_HOME. Use the host-side tool for "
|
||||
f"authoritative state (e.g. ``memory`` for memories), or address "
|
||||
f"the host path directly. To bypass this guard after explicit "
|
||||
f"user direction, retry the call with ``cross_profile=True``. "
|
||||
f"(Defense-in-depth — not a security boundary; the terminal tool "
|
||||
f"can still bypass.)"
|
||||
return _SANDBOX_MIRROR_WARNING.format(
|
||||
target_path=info["target_path"],
|
||||
mirror_root=info["mirror_root"],
|
||||
body=body.format(inner_path=info["inner_path"]),
|
||||
bypass=bypass,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Container-context mirror guard (inner-container case — #32049 follow-up)
|
||||
#
|
||||
# Brian's shape-based detector (#32213) catches paths that still carry the
|
||||
# full ``…/sandboxes/<backend>/<task>/home/.hermes/…`` prefix on the host.
|
||||
# But when file tools execute *inside* the container the bind-mount strips
|
||||
# that prefix: the agent sees plain ``/root/.hermes/…``. The root:root
|
||||
# ownership on the divergent SOUL.md in #32049 confirms this is the primary
|
||||
# failure mode.
|
||||
#
|
||||
# Fix: file_tools passes the active Docker mirror prefix when the terminal
|
||||
# backend is docker + persistent. This catches the very first file-tool call,
|
||||
# before a DockerEnvironment object necessarily exists.
|
||||
# ---------------------------------------------------------------------------
|
||||
def get_sandbox_mirror_warning(path: str) -> Optional[str]:
|
||||
"""Model-facing soft-guard warning when ``path`` lands in a sandbox mirror, else ``None``.
|
||||
|
||||
Caller surfaces it as a tool-result error; ``cross_profile=True`` bypasses.
|
||||
"""
|
||||
return _mirror_warning(
|
||||
classify_sandbox_mirror_target(path),
|
||||
"a per-task mirror created by a non-local terminal backend (docker/daytona/etc.). "
|
||||
"Writes here land on a copy that the host Hermes process never reads — the "
|
||||
"authoritative file is likely {inner_path!r} under the real HERMES_HOME.",
|
||||
"this guard after explicit user direction, retry the call",
|
||||
)
|
||||
|
||||
|
||||
def classify_container_mirror_target(
|
||||
@@ -703,15 +428,11 @@ def classify_container_mirror_target(
|
||||
) -> Optional[dict]:
|
||||
"""Classify a write target as a container-side sandbox mirror.
|
||||
|
||||
``mirror_prefix`` must be supplied by the caller after it has established
|
||||
that file tools are executing in a container whose home is a sandbox
|
||||
mirror. Returns ``None`` when no such context is active or the path is not
|
||||
under the mirror prefix. Otherwise returns:
|
||||
|
||||
* ``target_path``: resolved path string
|
||||
* ``mirror_root``: the declared container mirror prefix
|
||||
* ``inner_path``: portion under the mirror root (what the agent
|
||||
likely meant to address in the host HERMES_HOME)
|
||||
Inside the container the bind mount strips the ``sandboxes/`` prefix (the
|
||||
agent sees plain ``/root/.hermes/…``), so the caller must supply
|
||||
``mirror_prefix`` once it knows file tools run in a docker sandbox.
|
||||
Returns ``None`` without a prefix or when the path is outside it, else
|
||||
``target_path``, ``mirror_root`` and ``inner_path``.
|
||||
"""
|
||||
if not mirror_prefix:
|
||||
return None
|
||||
@@ -732,27 +453,11 @@ def get_container_mirror_warning(
|
||||
path: str,
|
||||
mirror_prefix: str | None = None,
|
||||
) -> Optional[str]:
|
||||
"""Return a model-facing warning when *path* lands in the container's
|
||||
sandbox mirror of authoritative Hermes state.
|
||||
|
||||
The caller supplies ``mirror_prefix`` only when the current file-tool
|
||||
backend is known to execute inside a Docker sandbox. Same contract as
|
||||
``get_cross_profile_warning``: soft guard, returns ``None`` for
|
||||
non-mirror paths, caller surfaces as a tool-result error. Bypass via
|
||||
``cross_profile=True`` after explicit user direction.
|
||||
"""
|
||||
info = classify_container_mirror_target(path, mirror_prefix)
|
||||
if info is None:
|
||||
return None
|
||||
return (
|
||||
f"Sandbox-mirror write blocked by soft guard: {info['target_path']} "
|
||||
f"sits under {info['mirror_root']!r}, which is the container's "
|
||||
f"bind-mounted home — a per-task mirror that the host Hermes "
|
||||
f"process never reads. The authoritative file is "
|
||||
f"{info['inner_path']!r} under the real HERMES_HOME. Use the "
|
||||
f"host-side tool for authoritative state (e.g. ``memory`` for "
|
||||
f"memories), or address the host path directly. To bypass after "
|
||||
f"explicit user direction, retry with ``cross_profile=True``. "
|
||||
f"(Defense-in-depth — not a security boundary; the terminal tool "
|
||||
f"can still bypass.)"
|
||||
"""Model-facing soft-guard warning when ``path`` lands in the container's mirror, else ``None``."""
|
||||
return _mirror_warning(
|
||||
classify_container_mirror_target(path, mirror_prefix),
|
||||
"the container's bind-mounted home — a per-task mirror that the host Hermes "
|
||||
"process never reads. The authoritative file is {inner_path!r} under "
|
||||
"the real HERMES_HOME.",
|
||||
"after explicit user direction, retry",
|
||||
)
|
||||
|
||||
+17
-30
@@ -1,14 +1,9 @@
|
||||
"""Turn-end guard for kanban workers.
|
||||
|
||||
Kanban workers must end with ``kanban_complete`` or ``kanban_block``. Models
|
||||
(especially GLM / Qwen families) sometimes narrate the next step
|
||||
("Let me write the report now") and stop with ``finish_reason=stop`` and no
|
||||
tool calls. Hermes treats that as a clean exit → ``rc=0`` → dispatcher
|
||||
``protocol_violation``.
|
||||
|
||||
This module is policy-only: when a kanban worker tries to finish without a
|
||||
terminal board tool, return a bounded synthetic nudge so the conversation
|
||||
loop continues instead of exiting.
|
||||
Kanban workers must end with ``kanban_complete`` or ``kanban_block``. Some
|
||||
models narrate the next step and stop with no tool calls; Hermes treats that
|
||||
as a clean exit → ``rc=0`` → dispatcher ``protocol_violation``. Policy-only:
|
||||
return a bounded synthetic nudge so the loop continues instead of exiting.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,16 +18,11 @@ _DEFAULT_MAX_ATTEMPTS = 2
|
||||
|
||||
|
||||
def kanban_stop_nudge_enabled() -> bool:
|
||||
"""Return whether the kanban stop-guard is active for this process.
|
||||
|
||||
On when ``HERMES_KANBAN_TASK`` is set (dispatcher-spawned worker), unless
|
||||
``HERMES_KANBAN_STOP_NUDGE`` explicitly disables it.
|
||||
"""
|
||||
"""On when ``HERMES_KANBAN_TASK`` is set, unless ``HERMES_KANBAN_STOP_NUDGE`` disables it."""
|
||||
env = os.environ.get("HERMES_KANBAN_STOP_NUDGE")
|
||||
if env is not None and env.strip().lower() in {"0", "false", "no", "off"}:
|
||||
return False
|
||||
task = (os.environ.get("HERMES_KANBAN_TASK") or "").strip()
|
||||
return bool(task)
|
||||
return bool((os.environ.get("HERMES_KANBAN_TASK") or "").strip())
|
||||
|
||||
|
||||
def _tool_call_name(tc: Any) -> str:
|
||||
@@ -56,13 +46,10 @@ def session_called_kanban_terminal(messages: Iterable[dict] | None) -> bool:
|
||||
continue
|
||||
role = msg.get("role")
|
||||
if role == "assistant":
|
||||
for tc in msg.get("tool_calls") or []:
|
||||
if _tool_call_name(tc) in _TERMINAL_KANBAN_TOOLS:
|
||||
return True
|
||||
elif role == "tool":
|
||||
name = str(msg.get("name") or "")
|
||||
if name in _TERMINAL_KANBAN_TOOLS:
|
||||
if any(_tool_call_name(tc) in _TERMINAL_KANBAN_TOOLS for tc in msg.get("tool_calls") or []):
|
||||
return True
|
||||
elif role == "tool" and str(msg.get("name") or "") in _TERMINAL_KANBAN_TOOLS:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@@ -73,16 +60,16 @@ def build_kanban_stop_nudge(
|
||||
max_attempts: int = _DEFAULT_MAX_ATTEMPTS,
|
||||
task_id: Optional[str] = None,
|
||||
) -> Optional[str]:
|
||||
"""Return a synthetic follow-up when a kanban worker exits without a terminal tool.
|
||||
"""Synthetic follow-up when a kanban worker exits without a terminal tool.
|
||||
|
||||
Returns ``None`` when the guard should not fire (not a kanban worker,
|
||||
already completed/blocked, or nudge budget exhausted).
|
||||
``None`` when the guard should not fire (not a kanban worker, already
|
||||
completed/blocked, or nudge budget exhausted).
|
||||
"""
|
||||
if not kanban_stop_nudge_enabled():
|
||||
return None
|
||||
if attempts >= max_attempts:
|
||||
return None
|
||||
if session_called_kanban_terminal(messages):
|
||||
if (
|
||||
not kanban_stop_nudge_enabled()
|
||||
or attempts >= max_attempts
|
||||
or session_called_kanban_terminal(messages)
|
||||
):
|
||||
return None
|
||||
|
||||
tid = (task_id or os.environ.get("HERMES_KANBAN_TASK") or "").strip() or "this task"
|
||||
|
||||
@@ -1,17 +1,10 @@
|
||||
"""Hermes gateway monitoring.
|
||||
"""Hermes gateway monitoring: service health + redacted diagnostics over OTLP.
|
||||
|
||||
Service health monitoring plus redacted operational diagnostics for the
|
||||
gateway daemon, exported over OTLP to an operator-configured endpoint.
|
||||
|
||||
``emitter`` is the in-process event bus: producers (gateway status hooks,
|
||||
the diagnostic log handler) hand typed events to a fire-and-forget queue,
|
||||
and subscribers (the OTLP streamers) consume them off the hot path. The
|
||||
emitter never blocks or raises into gateway code (the hot-path invariant),
|
||||
and nothing is persisted locally — monitoring is an egress path, not a store.
|
||||
|
||||
Deliberately out of scope here: run/model/tool trajectory capture, usage
|
||||
analytics, and any content-bearing signal. Those planes are served by the
|
||||
NeMo Relay integration and its Hermes-owned subscribers.
|
||||
``emitter`` is the in-process event bus: producers hand typed events to a
|
||||
fire-and-forget queue that never blocks or raises into gateway code, and OTLP
|
||||
subscribers consume them off the hot path. Nothing is persisted locally.
|
||||
Out of scope: trajectory capture, usage analytics, any content-bearing signal
|
||||
(those belong to the NeMo Relay integration).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -2,15 +2,18 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
from agent.monitoring.events import CronExecutionEvent
|
||||
from agent.monitoring.gateway_health import GatewayHealthSnapshot, GatewayMetric
|
||||
from agent.monitoring.gateway_health import (
|
||||
GatewayMetric,
|
||||
_contains_any,
|
||||
_safe_instance_id,
|
||||
)
|
||||
from cron.jobs import (
|
||||
_compute_grace_seconds,
|
||||
get_catch_up_occurrence_count,
|
||||
@@ -19,7 +22,7 @@ from cron.jobs import (
|
||||
load_jobs,
|
||||
)
|
||||
from cron.scheduler import get_running_job_ids
|
||||
from hermes_time import now as _hermes_now
|
||||
from hermes_time import now as _now
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
_KNOWN_STATUSES = {"claimed", "running", "completed", "failed", "unknown"}
|
||||
@@ -27,6 +30,7 @@ _KNOWN_SOURCES = {"builtin", "direct", "external"}
|
||||
_KNOWN_DELIVERY_OUTCOMES = {
|
||||
"delivered", "failed", "suppressed", "suppressed_acked", "not_configured",
|
||||
}
|
||||
_TERMINAL_STATUSES = {"completed", "failed", "unknown"}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -35,39 +39,32 @@ class CronHealthSnapshot:
|
||||
events: list[CronExecutionEvent]
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return _hermes_now()
|
||||
# Opaque job key: same sha256:<24 hex> shape as service.instance.id — never the raw id.
|
||||
_job_key = _safe_instance_id
|
||||
|
||||
_AUTH_RE = re.compile(
|
||||
r"\b(?:authentication|authenticated|authenticate|authorization|authorized|authorize"
|
||||
r"|unauthorized|forbidden|bearer|401|403)\b|\b(?:access|api|refresh) token\b"
|
||||
)
|
||||
|
||||
|
||||
def _job_key(raw: Any) -> str:
|
||||
value = str(raw or "unknown").encode("utf-8", errors="replace")
|
||||
return f"sha256:{hashlib.sha256(value).hexdigest()[:24]}"
|
||||
# Ordered (predicate, class) rules; first match wins. Auth uses word boundaries so
|
||||
# "oauth"/"tokenizer"/"HTTP 4015" do not false-positive.
|
||||
_CRON_ERROR_RULES: tuple[tuple[Callable[[str], bool], str], ...] = (
|
||||
(lambda s: _AUTH_RE.search(s) is not None, "auth_failed"),
|
||||
(_contains_any("rate limit", "429", "quota"), "rate_limited"),
|
||||
(_contains_any("timeout", "timed out"), "timeout"),
|
||||
(_contains_any("network", "connection", "dns", "socket", "unreachable"), "network_error"),
|
||||
(_contains_any("dispatch", "executor"), "dispatch_failed"),
|
||||
(_contains_any("interrupt", "owner exited", "restarted"), "interrupted"),
|
||||
(_contains_any("empty response"), "empty_response"),
|
||||
(_contains_any("config", "missing", "invalid"), "invalid_config"),
|
||||
)
|
||||
|
||||
|
||||
def classify_cron_error(raw: Any) -> str:
|
||||
text = str(raw or "").lower()
|
||||
if (
|
||||
re.search(r"\b(?:authentication|authenticated|authenticate|authorization|authorized|authorize|unauthorized|forbidden)\b", text)
|
||||
or re.search(r"\bbearer\b", text)
|
||||
or re.search(r"\b(?:access|api|refresh) token\b", text)
|
||||
or re.search(r"\b(?:401|403)\b", text)
|
||||
):
|
||||
return "auth_failed"
|
||||
if "rate limit" in text or "429" in text or "quota" in text:
|
||||
return "rate_limited"
|
||||
if "timeout" in text or "timed out" in text:
|
||||
return "timeout"
|
||||
if any(value in text for value in ("network", "connection", "dns", "socket", "unreachable")):
|
||||
return "network_error"
|
||||
if "dispatch" in text or "executor" in text:
|
||||
return "dispatch_failed"
|
||||
if "interrupt" in text or "owner exited" in text or "restarted" in text:
|
||||
return "interrupted"
|
||||
if "empty response" in text:
|
||||
return "empty_response"
|
||||
if any(value in text for value in ("config", "missing", "invalid")):
|
||||
return "invalid_config"
|
||||
return "unknown"
|
||||
return next((label for match, label in _CRON_ERROR_RULES if match(text)), "unknown")
|
||||
|
||||
|
||||
def _parse_time(raw: Any) -> Optional[datetime]:
|
||||
@@ -94,13 +91,12 @@ def project_execution_event(
|
||||
) -> CronExecutionEvent:
|
||||
status = str(record.get("status") or "unknown").lower()
|
||||
source = str(record.get("source") or "unknown").lower()
|
||||
if source not in _KNOWN_SOURCES and source != "unknown":
|
||||
source = "external"
|
||||
outcome = str(delivery_outcome).lower() if delivery_outcome is not None else None
|
||||
return CronExecutionEvent(
|
||||
status=status if status in _KNOWN_STATUSES else "unknown",
|
||||
job_key=_job_key(record.get("job_id")),
|
||||
source=source if source in _KNOWN_SOURCES else "unknown",
|
||||
# Unknown non-empty sources are bucketed as "external" (not dropped to unknown).
|
||||
source=source if source in _KNOWN_SOURCES or source == "unknown" else "external",
|
||||
duration_ms=_duration_ms(record),
|
||||
delivery_outcome=(
|
||||
outcome if outcome in _KNOWN_DELIVERY_OUTCOMES else None
|
||||
@@ -125,7 +121,7 @@ def emit_execution_state(
|
||||
event = project_execution_event(record, delivery_outcome=delivery_outcome)
|
||||
target = emitter.get_emitter()
|
||||
target.emit(event)
|
||||
if event.status in {"completed", "failed", "unknown"}:
|
||||
if event.status in _TERMINAL_STATUSES:
|
||||
target.flush(timeout=1.0)
|
||||
except Exception:
|
||||
logger.debug("cron execution telemetry emit failed", exc_info=True)
|
||||
@@ -147,50 +143,50 @@ def _is_overdue(job: dict[str, Any], now: datetime) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _job_metrics(metrics: list[GatewayMetric]) -> None:
|
||||
enabled = [job for job in load_jobs() if job.get("enabled", True)]
|
||||
metrics.append(GatewayMetric("hermes.cron.jobs.enabled", len(enabled), {}))
|
||||
metrics.append(GatewayMetric(
|
||||
"hermes.cron.jobs.overdue",
|
||||
sum(1 for job in enabled if _is_overdue(job, _now())),
|
||||
{},
|
||||
))
|
||||
|
||||
|
||||
def _freshness_metric(name: str, reader: Callable[[], Optional[float]]) -> Callable[[list[GatewayMetric]], None]:
|
||||
def build(metrics: list[GatewayMetric]) -> None:
|
||||
value = reader()
|
||||
if value is not None:
|
||||
metrics.append(GatewayMetric(name, max(0.0, float(value)), {}))
|
||||
return build
|
||||
|
||||
|
||||
def _single_metric(name: str, reader: Callable[[], Any]) -> Callable[[list[GatewayMetric]], None]:
|
||||
return lambda metrics: metrics.append(GatewayMetric(name, reader(), {}))
|
||||
|
||||
|
||||
# Each group is independently fail-open so one unavailable source never hides the rest.
|
||||
# Readers are wrapped in lambdas so monkeypatching this module's names still takes effect.
|
||||
_METRIC_GROUPS: tuple[tuple[Callable[[list[GatewayMetric]], None], str], ...] = (
|
||||
(_freshness_metric("hermes.cron.scheduler.heartbeat_age_seconds", lambda: get_ticker_heartbeat_age()),
|
||||
"cron freshness metric unavailable"),
|
||||
(_freshness_metric("hermes.cron.scheduler.last_success_age_seconds", lambda: get_ticker_success_age()),
|
||||
"cron freshness metric unavailable"),
|
||||
(_single_metric("hermes.cron.scheduler.catch_up_occurrences", lambda: get_catch_up_occurrence_count()),
|
||||
"cron catch-up metric unavailable"),
|
||||
(_job_metrics, "cron job metrics unavailable"),
|
||||
(_single_metric("hermes.cron.jobs.running", lambda: len(get_running_job_ids())),
|
||||
"cron running-job metric unavailable"),
|
||||
)
|
||||
|
||||
|
||||
def build_cron_health_snapshot() -> CronHealthSnapshot:
|
||||
metrics: list[GatewayMetric] = []
|
||||
for name, reader in (
|
||||
("hermes.cron.scheduler.heartbeat_age_seconds", get_ticker_heartbeat_age),
|
||||
("hermes.cron.scheduler.last_success_age_seconds", get_ticker_success_age),
|
||||
):
|
||||
for build, failure_msg in _METRIC_GROUPS:
|
||||
try:
|
||||
value = reader()
|
||||
if value is not None:
|
||||
metrics.append(GatewayMetric(name, max(0.0, float(value)), {}))
|
||||
build(metrics)
|
||||
except Exception:
|
||||
logger.debug("cron freshness metric unavailable", exc_info=True)
|
||||
|
||||
try:
|
||||
metrics.append(
|
||||
GatewayMetric(
|
||||
"hermes.cron.scheduler.catch_up_occurrences",
|
||||
get_catch_up_occurrence_count(),
|
||||
{},
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("cron catch-up metric unavailable", exc_info=True)
|
||||
|
||||
try:
|
||||
jobs = load_jobs()
|
||||
enabled = [job for job in jobs if job.get("enabled", True)]
|
||||
metrics.append(GatewayMetric("hermes.cron.jobs.enabled", len(enabled), {}))
|
||||
metrics.append(
|
||||
GatewayMetric(
|
||||
"hermes.cron.jobs.overdue",
|
||||
sum(1 for job in enabled if _is_overdue(job, _now())),
|
||||
{},
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("cron job metrics unavailable", exc_info=True)
|
||||
|
||||
try:
|
||||
metrics.append(
|
||||
GatewayMetric("hermes.cron.jobs.running", len(get_running_job_ids()), {})
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("cron running-job metric unavailable", exc_info=True)
|
||||
logger.debug(failure_msg, exc_info=True)
|
||||
return CronHealthSnapshot(metrics=metrics, events=[])
|
||||
|
||||
|
||||
|
||||
+10
-31
@@ -1,22 +1,11 @@
|
||||
"""Monitoring emitter: fire-and-forget queue + background dispatcher.
|
||||
|
||||
The emitter is the single seam between producers (gateway status hooks, the
|
||||
diagnostic log handler) and consumers (the OTLP streamers). Its contract is
|
||||
the hot-path invariant:
|
||||
|
||||
``emit()`` MUST return in O(microseconds), MUST NOT block on disk/network,
|
||||
and MUST NEVER raise into the caller. A monitoring failure is logged
|
||||
locally and dropped — it can never affect the gateway or a session.
|
||||
|
||||
Mechanism:
|
||||
* ``emit(event)`` does a non-blocking ``queue.put_nowait`` wrapped in a bare
|
||||
except. On a full queue it drops the *oldest* event and counts the drop.
|
||||
* A daemon thread drains the queue and fans each batch out to subscribers
|
||||
(the OTLP metric/span/log streamers). Each subscriber is fail-isolated —
|
||||
a slow or raising subscriber never affects the hot path or its peers.
|
||||
|
||||
Nothing is persisted here. Monitoring is an egress path, not a local store;
|
||||
if no subscriber is attached, events simply age out of the ring buffer.
|
||||
The single seam between producers (gateway status hooks, diagnostic log handler)
|
||||
and consumers (OTLP streamers). Hot-path invariant: ``emit()`` MUST return in
|
||||
O(microseconds), MUST NOT block on disk/network, and MUST NEVER raise into the
|
||||
caller — a monitoring failure is logged locally and dropped. On a full queue the
|
||||
*oldest* event is dropped. A daemon thread fans batches out to fail-isolated
|
||||
subscribers. Nothing is persisted: monitoring is an egress path, not a store.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -45,16 +34,12 @@ class MonitoringEmitter:
|
||||
self._started = False
|
||||
self._lock = threading.Lock()
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
# Live subscribers (the OTLP streamers). Called from the dispatcher
|
||||
# thread, fully fail-isolated. Each subscriber is callable(batch: list[dict]).
|
||||
# Subscribers are callable(batch: list[dict]), invoked on the dispatcher thread.
|
||||
self._subscribers: list = []
|
||||
|
||||
# ── public API (hot path) ───────────────────────────────────────────────
|
||||
def emit(self, event: Any) -> None:
|
||||
"""Enqueue an event. Never blocks, never raises.
|
||||
|
||||
``event`` may be a dataclass with ``to_dict()`` or a plain dict.
|
||||
"""
|
||||
"""Enqueue a dataclass with ``to_dict()`` or a plain dict. Never blocks, never raises."""
|
||||
if not self._enabled:
|
||||
return
|
||||
try:
|
||||
@@ -107,7 +92,6 @@ class MonitoringEmitter:
|
||||
self._q.task_done()
|
||||
|
||||
def _dispatch(self, batch) -> None:
|
||||
# Fan-out to subscribers (OTLP streamers) — fully fail-isolated.
|
||||
for sub in list(self._subscribers):
|
||||
try:
|
||||
sub(batch)
|
||||
@@ -116,7 +100,7 @@ class MonitoringEmitter:
|
||||
self._dispatched += len(batch)
|
||||
|
||||
def subscribe(self, callback) -> None:
|
||||
"""Register a live batch subscriber (callable(batch: list[dict]))."""
|
||||
"""Register a live batch subscriber; the first subscriber enables collection."""
|
||||
if callback not in self._subscribers:
|
||||
self._subscribers.append(callback)
|
||||
self._enabled = True
|
||||
@@ -176,8 +160,7 @@ def get_emitter() -> MonitoringEmitter:
|
||||
return _EMITTER
|
||||
with _EMITTER_LOCK:
|
||||
if _EMITTER is None:
|
||||
# Collection is opt-in. A plane exporter enables the singleton by
|
||||
# attaching its first subscriber; until then producers are no-ops.
|
||||
# Collection is opt-in: disabled until a plane exporter attaches its first subscriber.
|
||||
_EMITTER = MonitoringEmitter(enabled=False)
|
||||
return _EMITTER
|
||||
|
||||
@@ -199,12 +182,8 @@ def reset_emitter_for_tests(emitter: Optional[MonitoringEmitter] = None) -> None
|
||||
_EMITTER = emitter
|
||||
|
||||
|
||||
# Back-compat alias for the salvaged class name used in emozilla's tests.
|
||||
TelemetryEmitter = MonitoringEmitter
|
||||
|
||||
__all__ = [
|
||||
"MonitoringEmitter",
|
||||
"TelemetryEmitter",
|
||||
"get_emitter",
|
||||
"emit",
|
||||
"reset_emitter_for_tests",
|
||||
|
||||
+22
-20
@@ -1,25 +1,32 @@
|
||||
"""Typed gateway monitoring events.
|
||||
|
||||
Content-free service-health and redacted diagnostic events for the gateway
|
||||
daemon. These are the only event shapes the monitoring plane emits: no
|
||||
prompts, messages, tool args/results, session history, or usage analytics.
|
||||
daemon — the only shapes the monitoring plane emits: no prompts, messages,
|
||||
tool args/results, session history, or usage analytics. Field order is wire
|
||||
order (``asdict``); never reorder.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from dataclasses import dataclass, field, asdict
|
||||
from typing import Any, Dict, Optional
|
||||
from typing import Any, ClassVar, Dict, Optional
|
||||
|
||||
|
||||
def _now_ns() -> int:
|
||||
return time.time_ns()
|
||||
class _MonitoringEvent:
|
||||
__slots__ = ()
|
||||
EVENT: ClassVar[str]
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {"event": self.EVENT, **asdict(self)}
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class GatewayHealthEvent:
|
||||
class GatewayHealthEvent(_MonitoringEvent):
|
||||
"""Content-free gateway health snapshot or lifecycle event."""
|
||||
|
||||
EVENT: ClassVar[str] = "gateway_health"
|
||||
|
||||
name: str
|
||||
gateway_state: Optional[str] = None
|
||||
old_state: Optional[str] = None
|
||||
@@ -36,16 +43,15 @@ class GatewayHealthEvent:
|
||||
version: Optional[str] = None
|
||||
supervision_mode: Optional[str] = None
|
||||
pid: Optional[int] = None
|
||||
ts_ns: int = field(default_factory=_now_ns)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {"event": "gateway_health", **asdict(self)}
|
||||
ts_ns: int = field(default_factory=time.time_ns)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class GatewayDiagnosticEvent:
|
||||
class GatewayDiagnosticEvent(_MonitoringEvent):
|
||||
"""Redacted gateway diagnostic event for operator-owned observability."""
|
||||
|
||||
EVENT: ClassVar[str] = "gateway_diagnostic"
|
||||
|
||||
name: str
|
||||
subsystem: str
|
||||
error_class: str = "unknown"
|
||||
@@ -56,27 +62,23 @@ class GatewayDiagnosticEvent:
|
||||
profile: Optional[str] = None
|
||||
version: Optional[str] = None
|
||||
severity: str = "warning"
|
||||
ts_ns: int = field(default_factory=_now_ns)
|
||||
ts_ns: int = field(default_factory=time.time_ns)
|
||||
source_logger: Optional[str] = None
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {"event": "gateway_diagnostic", **asdict(self)}
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CronExecutionEvent:
|
||||
class CronExecutionEvent(_MonitoringEvent):
|
||||
"""Content-free durable cron execution lifecycle projection."""
|
||||
|
||||
EVENT: ClassVar[str] = "cron_execution"
|
||||
|
||||
status: str
|
||||
job_key: str
|
||||
source: str = "unknown"
|
||||
duration_ms: Optional[int] = None
|
||||
delivery_outcome: Optional[str] = None
|
||||
error_class: Optional[str] = None
|
||||
ts_ns: int = field(default_factory=_now_ns)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {"event": "cron_execution", **asdict(self)}
|
||||
ts_ns: int = field(default_factory=time.time_ns)
|
||||
|
||||
|
||||
__all__ = [
|
||||
|
||||
+137
-201
@@ -1,9 +1,8 @@
|
||||
"""Gateway health and diagnostics signal producer.
|
||||
|
||||
This module keeps the plane narrow: service health monitoring plus
|
||||
redacted operational diagnostics. It reuses the existing gateway runtime-status
|
||||
contract and emits content-free metrics/events. No prompts, messages, tool args,
|
||||
session history, audit records, or product analytics belong here.
|
||||
Keeps the plane narrow: service health plus redacted operational diagnostics,
|
||||
derived from the existing gateway runtime-status contract. No prompts,
|
||||
messages, tool args, session history, audit records, or product analytics.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,9 +11,13 @@ import hashlib
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
from agent.monitoring import emitter
|
||||
from agent.monitoring.events import GatewayDiagnosticEvent, GatewayHealthEvent
|
||||
from agent.monitoring.redaction import redact_bounded
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -42,61 +45,34 @@ _SUPERVISION_MODES = {"systemd", "s6", "container", "launchd", "manual", "unknow
|
||||
_SOURCE_LOGGER_RE = re.compile(r"^gateway(?:\.[A-Za-z_][A-Za-z0-9_]*)*$")
|
||||
|
||||
|
||||
def _allowed_logger(name: str) -> bool:
|
||||
return name == "gateway" or name.startswith("gateway.")
|
||||
|
||||
|
||||
def source_logger_for_export(name: Any) -> Optional[str]:
|
||||
"""Return a bounded source-controlled gateway logger name for OTLP scope."""
|
||||
value = str(name or "")
|
||||
return value if len(value) <= 128 and _SOURCE_LOGGER_RE.fullmatch(value) else None
|
||||
|
||||
|
||||
def redact_gateway_message(message: Any) -> str:
|
||||
"""Redact gateway diagnostic free text for operator-owned export.
|
||||
def _contains_any(*needles: str) -> Callable[[str], bool]:
|
||||
return lambda text: any(needle in text for needle in needles)
|
||||
|
||||
Single scrub path: everything goes through
|
||||
``agent.monitoring.redaction.redact_for_export`` (unconditional
|
||||
secrets + PII), then is length-bounded.
|
||||
"""
|
||||
try:
|
||||
from agent.monitoring.redaction import redact_for_export
|
||||
redacted = redact_for_export(str(message or "")) or ""
|
||||
except Exception:
|
||||
redacted = "[redaction-unavailable]"
|
||||
return redacted[:500]
|
||||
|
||||
# Ordered (predicate, class) rules; first match wins, so auth outranks rate-limit etc.
|
||||
_GATEWAY_ERROR_RULES: tuple[tuple[Callable[[str], bool], str], ...] = (
|
||||
(_contains_any("auth", "token", "unauthorized", "forbidden", "401", "403"), "auth_failed"),
|
||||
(lambda s: "rate" in s and "limit" in s, "rate_limited"),
|
||||
(_contains_any("timeout", "timed out"), "timeout"),
|
||||
(_contains_any(
|
||||
"network", "connection", "dns", "socket", "connect call failed",
|
||||
"failed to connect", "cannot connect", "unreachable", "name resolution",
|
||||
), "network_error"),
|
||||
(_contains_any("config", "missing", "invalid"), "invalid_config"),
|
||||
(_contains_any("startup"), "startup_failed"),
|
||||
(_contains_any("fatal"), "platform_fatal"),
|
||||
)
|
||||
|
||||
|
||||
def classify_gateway_error(raw: Any) -> str:
|
||||
s = str(raw or "").lower()
|
||||
if any(k in s for k in ("auth", "token", "unauthorized", "forbidden", "401", "403")):
|
||||
return "auth_failed"
|
||||
if "rate" in s and "limit" in s:
|
||||
return "rate_limited"
|
||||
if "timeout" in s or "timed out" in s:
|
||||
return "timeout"
|
||||
if any(
|
||||
k in s
|
||||
for k in (
|
||||
"network",
|
||||
"connection",
|
||||
"dns",
|
||||
"socket",
|
||||
"connect call failed",
|
||||
"failed to connect",
|
||||
"cannot connect",
|
||||
"unreachable",
|
||||
"name resolution",
|
||||
)
|
||||
):
|
||||
return "network_error"
|
||||
if any(k in s for k in ("config", "missing", "invalid")):
|
||||
return "invalid_config"
|
||||
if "startup" in s:
|
||||
return "startup_failed"
|
||||
if "fatal" in s:
|
||||
return "platform_fatal"
|
||||
return "unknown"
|
||||
return next((label for match, label in _GATEWAY_ERROR_RULES if match(s)), "unknown")
|
||||
|
||||
|
||||
def classify_exit_reason(
|
||||
@@ -124,13 +100,13 @@ def _bounded_state(raw: Any, *, allowed: set[str]) -> str:
|
||||
return state if state in allowed else "unknown"
|
||||
|
||||
|
||||
def _optional_state(raw: Any, *, allowed: set[str]) -> Optional[str]:
|
||||
"""``_bounded_state`` that preserves "absent" (None) instead of coercing to unknown."""
|
||||
return None if raw is None else _bounded_state(raw, allowed=allowed)
|
||||
|
||||
|
||||
def _safe_metric_value(raw: Any, *, limit: int = 128) -> str:
|
||||
try:
|
||||
from agent.monitoring.redaction import redact_for_export
|
||||
value = redact_for_export(str(raw or "")) or "unknown"
|
||||
except Exception:
|
||||
return "unknown"
|
||||
return value[:limit]
|
||||
return redact_bounded(raw, limit=limit, empty="unknown", unavailable="unknown")
|
||||
|
||||
|
||||
def _safe_instance_id(raw: Any) -> str:
|
||||
@@ -140,23 +116,16 @@ def _safe_instance_id(raw: Any) -> str:
|
||||
|
||||
|
||||
def subsystem_for_logger(logger_name: str) -> str:
|
||||
if logger_name == "gateway.relay" or logger_name.startswith("gateway.relay."):
|
||||
parts = logger_name.split(".")
|
||||
if parts[:2] == ["gateway", "relay"]:
|
||||
return "platform.relay"
|
||||
if logger_name.startswith("gateway.platforms."):
|
||||
parts = logger_name.split(".")
|
||||
if len(parts) >= 3 and parts[2]:
|
||||
return f"platform.{parts[2]}"
|
||||
if logger_name.startswith("gateway.platforms"):
|
||||
return "platform"
|
||||
if logger_name.startswith("gateway"):
|
||||
return "gateway"
|
||||
return "gateway"
|
||||
if parts[:2] == ["gateway", "platforms"] and len(parts) >= 3 and parts[2]:
|
||||
return f"platform.{parts[2]}"
|
||||
return "platform" if logger_name.startswith("gateway.platforms") else "gateway"
|
||||
|
||||
|
||||
def platform_for_subsystem(subsystem: str) -> Optional[str]:
|
||||
if subsystem.startswith("platform."):
|
||||
return subsystem.split(".", 1)[1] or None
|
||||
return None
|
||||
return (subsystem.split(".", 1)[1] or None) if subsystem.startswith("platform.") else None
|
||||
|
||||
|
||||
def _parse_active_agents(raw: Any) -> int:
|
||||
@@ -174,9 +143,7 @@ def _derive_busy(gateway_running: bool, gateway_state: Any, active_agents: Any)
|
||||
try:
|
||||
from gateway.status import derive_gateway_busy
|
||||
return derive_gateway_busy(
|
||||
gateway_running=gateway_running,
|
||||
gateway_state=gateway_state,
|
||||
active_agents=active_agents,
|
||||
gateway_running=gateway_running, gateway_state=gateway_state, active_agents=active_agents
|
||||
)
|
||||
except Exception:
|
||||
return bool(gateway_running and gateway_state == "running" and _parse_active_agents(active_agents) > 0)
|
||||
@@ -190,7 +157,7 @@ def _derive_drainable(gateway_running: bool, gateway_state: Any) -> bool:
|
||||
return bool(gateway_running and gateway_state == "running")
|
||||
|
||||
|
||||
def _base_attrs(*, profile: str, install_id: str, version: str, supervision_mode: str) -> Dict[str, str]:
|
||||
def _base_attrs(*, install_id: str, version: str, supervision_mode: str) -> Dict[str, str]:
|
||||
mode = str(supervision_mode or "unknown").lower()
|
||||
return {
|
||||
"service.instance.id": _safe_instance_id(install_id),
|
||||
@@ -207,6 +174,11 @@ def _metric(name: str, value: int | float, attrs: Dict[str, str], **extra: str)
|
||||
return GatewayMetric(name=name, value=value, attributes=out)
|
||||
|
||||
|
||||
def _platforms_of(runtime: Optional[dict[str, Any]]) -> dict[str, Any]:
|
||||
raw = (runtime or {}).get("platforms")
|
||||
return raw if isinstance(raw, dict) else {}
|
||||
|
||||
|
||||
def build_gateway_health_snapshot(
|
||||
runtime: Optional[dict[str, Any]],
|
||||
*,
|
||||
@@ -218,14 +190,12 @@ def build_gateway_health_snapshot(
|
||||
) -> GatewayHealthSnapshot:
|
||||
"""Convert gateway_state.json-compatible runtime state into P0 signals."""
|
||||
runtime = runtime or {}
|
||||
gateway_state = _bounded_state(
|
||||
runtime.get("gateway_state"), allowed=_KNOWN_GATEWAY_STATES
|
||||
)
|
||||
gateway_state = _bounded_state(runtime.get("gateway_state"), allowed=_KNOWN_GATEWAY_STATES)
|
||||
active_agents = _parse_active_agents(runtime.get("active_agents", 0))
|
||||
busy = _derive_busy(gateway_running, gateway_state, active_agents)
|
||||
drainable = _derive_drainable(gateway_running, gateway_state)
|
||||
platforms = runtime.get("platforms") if isinstance(runtime.get("platforms"), dict) else {}
|
||||
base = _base_attrs(profile=profile, install_id=install_id, version=version, supervision_mode=supervision_mode)
|
||||
platforms = _platforms_of(runtime)
|
||||
base = _base_attrs(install_id=install_id, version=version, supervision_mode=supervision_mode)
|
||||
|
||||
metrics: list[GatewayMetric] = [
|
||||
_metric("hermes.gateway.up", 1 if gateway_running else 0, base),
|
||||
@@ -233,34 +203,23 @@ def build_gateway_health_snapshot(
|
||||
_metric("hermes.gateway.busy", 1 if busy else 0, base),
|
||||
_metric("hermes.gateway.drainable", 1 if drainable else 0, base),
|
||||
_metric("hermes.gateway.restart_requested", 1 if runtime.get("restart_requested") else 0, base),
|
||||
_metric("hermes.gateway.state", 1, base, **{"hermes.gateway.state": gateway_state}),
|
||||
]
|
||||
if gateway_state:
|
||||
metrics.append(_metric("hermes.gateway.state", 1, base, **{"hermes.gateway.state": str(gateway_state)}))
|
||||
|
||||
fatal_count = 0
|
||||
events: list[GatewayHealthEvent | GatewayDiagnosticEvent] = []
|
||||
for platform, pdata in platforms.items():
|
||||
pdata = pdata if isinstance(pdata, dict) else {}
|
||||
state = _bounded_state(
|
||||
pdata.get("state"), allowed=_KNOWN_PLATFORM_STATES
|
||||
)
|
||||
raw_error = pdata.get("error_code") or pdata.get("error_message")
|
||||
error_code = classify_gateway_error(raw_error)
|
||||
is_up = state in _RUNNING_PLATFORM_STATES
|
||||
state = _bounded_state(pdata.get("state"), allowed=_KNOWN_PLATFORM_STATES)
|
||||
# classify_* is idempotent on its own labels, so error_class == error_code here.
|
||||
error_code = classify_gateway_error(pdata.get("error_code") or pdata.get("error_message"))
|
||||
is_degraded = state in _FATAL_PLATFORM_STATES
|
||||
if is_degraded:
|
||||
fatal_count += 1
|
||||
pattrs = {"hermes.platform": str(platform), "hermes.platform.state": state}
|
||||
metrics.append(_metric("hermes.platform.up", 1 if state in _RUNNING_PLATFORM_STATES else 0, base, **pattrs))
|
||||
metrics.append(_metric(
|
||||
"hermes.platform.up",
|
||||
1 if is_up else 0,
|
||||
base,
|
||||
**{"hermes.platform": str(platform), "hermes.platform.state": state},
|
||||
))
|
||||
metrics.append(_metric(
|
||||
"hermes.platform.degraded",
|
||||
1 if is_degraded else 0,
|
||||
base,
|
||||
**{"hermes.platform": str(platform), "hermes.platform.state": state, "hermes.error_code": error_code},
|
||||
"hermes.platform.degraded", 1 if is_degraded else 0, base, **pattrs, **{"hermes.error_code": error_code}
|
||||
))
|
||||
if is_degraded:
|
||||
events.append(GatewayDiagnosticEvent(
|
||||
@@ -268,7 +227,7 @@ def build_gateway_health_snapshot(
|
||||
subsystem=f"platform.{platform}",
|
||||
platform=str(platform),
|
||||
error_code=error_code,
|
||||
error_class=classify_gateway_error(error_code or pdata.get("error_message")),
|
||||
error_class=error_code,
|
||||
profile=profile,
|
||||
version=version,
|
||||
severity="error" if state == "fatal" else "warning",
|
||||
@@ -276,7 +235,7 @@ def build_gateway_health_snapshot(
|
||||
|
||||
events.insert(0, GatewayHealthEvent(
|
||||
name="gateway.health_snapshot",
|
||||
gateway_state=str(gateway_state) if gateway_state is not None else None,
|
||||
gateway_state=gateway_state,
|
||||
active_agents=active_agents,
|
||||
gateway_busy=busy,
|
||||
gateway_drainable=drainable,
|
||||
@@ -307,6 +266,81 @@ def _safe_version() -> str:
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _lifecycle_events(
|
||||
previous: Optional[dict[str, Any]], current: dict[str, Any], *, profile: str, version: str
|
||||
) -> list[GatewayHealthEvent | GatewayDiagnosticEvent]:
|
||||
"""Gateway-level transition events: lifecycle, startup_failed diagnostic, exit."""
|
||||
old_state = _optional_state((previous or {}).get("gateway_state"), allowed=_KNOWN_GATEWAY_STATES)
|
||||
new_state = _optional_state(current.get("gateway_state"), allowed=_KNOWN_GATEWAY_STATES)
|
||||
if old_state == new_state or not new_state:
|
||||
return []
|
||||
restart_requested = bool(current.get("restart_requested"))
|
||||
|
||||
def health(name: str) -> GatewayHealthEvent:
|
||||
return GatewayHealthEvent(
|
||||
name=name,
|
||||
gateway_state=new_state,
|
||||
old_state=old_state,
|
||||
new_state=new_state,
|
||||
exit_reason=classify_exit_reason(
|
||||
current.get("exit_reason"), state=new_state, restart_requested=restart_requested
|
||||
),
|
||||
restart_requested=restart_requested,
|
||||
active_agents=_parse_active_agents(current.get("active_agents", 0)),
|
||||
profile=profile,
|
||||
version=version,
|
||||
pid=_coerce_pid(current.get("pid")),
|
||||
)
|
||||
|
||||
out: list[GatewayHealthEvent | GatewayDiagnosticEvent] = [health("gateway.lifecycle")]
|
||||
if new_state == "startup_failed":
|
||||
error_class = classify_gateway_error(current.get("exit_reason") or "startup_failed")
|
||||
out.append(GatewayDiagnosticEvent(
|
||||
name="gateway.startup_failed",
|
||||
subsystem="gateway",
|
||||
error_class=error_class,
|
||||
error_code=error_class,
|
||||
profile=profile,
|
||||
version=version,
|
||||
severity="error",
|
||||
))
|
||||
if new_state == "stopped":
|
||||
out.append(health("gateway.exit"))
|
||||
return out
|
||||
|
||||
|
||||
def _platform_events(
|
||||
previous: Optional[dict[str, Any]], current: dict[str, Any], *, profile: str, version: str
|
||||
) -> list[GatewayDiagnosticEvent]:
|
||||
"""Per-platform state_change diagnostics, plus platform.fatal when the new state is fatal."""
|
||||
old_platforms = _platforms_of(previous)
|
||||
out: list[GatewayDiagnosticEvent] = []
|
||||
for platform, pdata in _platforms_of(current).items():
|
||||
pdata = pdata if isinstance(pdata, dict) else {}
|
||||
prev_raw = old_platforms.get(platform, {})
|
||||
prev = prev_raw if isinstance(prev_raw, dict) else {}
|
||||
old_state = _optional_state(prev.get("state"), allowed=_KNOWN_PLATFORM_STATES)
|
||||
new_state = _optional_state(pdata.get("state"), allowed=_KNOWN_PLATFORM_STATES)
|
||||
if old_state == new_state or not new_state:
|
||||
continue
|
||||
error_code = classify_gateway_error(pdata.get("error_code") or pdata.get("error_message"))
|
||||
common: dict[str, Any] = dict(
|
||||
subsystem=f"platform.{platform}",
|
||||
platform=str(platform),
|
||||
error_code=error_code,
|
||||
error_class=error_code,
|
||||
profile=profile,
|
||||
version=version,
|
||||
severity="error" if new_state in {"fatal", "failed", "error"} else "warning",
|
||||
)
|
||||
out.append(GatewayDiagnosticEvent(
|
||||
name="platform.state_change", old_state=old_state, new_state=new_state, **common
|
||||
))
|
||||
if new_state in _FATAL_PLATFORM_STATES:
|
||||
out.append(GatewayDiagnosticEvent(name="platform.fatal", **common))
|
||||
return out
|
||||
|
||||
|
||||
def emit_runtime_status_transition(previous: Optional[dict[str, Any]], current: dict[str, Any]) -> None:
|
||||
"""Emit immediate content-free gateway events for runtime status changes.
|
||||
|
||||
@@ -314,106 +348,11 @@ def emit_runtime_status_transition(previous: Optional[dict[str, Any]], current:
|
||||
Fully fail-open: failures never affect gateway status writes.
|
||||
"""
|
||||
try:
|
||||
from agent.monitoring import emitter
|
||||
out: list[GatewayHealthEvent | GatewayDiagnosticEvent] = []
|
||||
profile = _safe_profile()
|
||||
version = _safe_version()
|
||||
old_gateway_state = _bounded_state(
|
||||
(previous or {}).get("gateway_state"), allowed=_KNOWN_GATEWAY_STATES
|
||||
) if (previous or {}).get("gateway_state") is not None else None
|
||||
new_gateway_state = _bounded_state(
|
||||
current.get("gateway_state"), allowed=_KNOWN_GATEWAY_STATES
|
||||
) if current.get("gateway_state") is not None else None
|
||||
if old_gateway_state != new_gateway_state and new_gateway_state:
|
||||
out.append(GatewayHealthEvent(
|
||||
name="gateway.lifecycle",
|
||||
gateway_state=new_gateway_state,
|
||||
old_state=old_gateway_state,
|
||||
new_state=new_gateway_state,
|
||||
exit_reason=classify_exit_reason(
|
||||
current.get("exit_reason"),
|
||||
state=new_gateway_state,
|
||||
restart_requested=bool(current.get("restart_requested")),
|
||||
),
|
||||
restart_requested=bool(current.get("restart_requested")),
|
||||
active_agents=_parse_active_agents(current.get("active_agents", 0)),
|
||||
profile=profile,
|
||||
version=version,
|
||||
pid=_coerce_pid(current.get("pid")),
|
||||
))
|
||||
if new_gateway_state == "startup_failed":
|
||||
out.append(GatewayDiagnosticEvent(
|
||||
name="gateway.startup_failed",
|
||||
subsystem="gateway",
|
||||
error_class=classify_gateway_error(current.get("exit_reason") or "startup_failed"),
|
||||
error_code=classify_gateway_error(current.get("exit_reason") or "startup_failed"),
|
||||
profile=profile,
|
||||
version=version,
|
||||
severity="error",
|
||||
))
|
||||
if new_gateway_state == "stopped":
|
||||
out.append(GatewayHealthEvent(
|
||||
name="gateway.exit",
|
||||
gateway_state=new_gateway_state,
|
||||
old_state=old_gateway_state,
|
||||
new_state=new_gateway_state,
|
||||
exit_reason=classify_exit_reason(
|
||||
current.get("exit_reason"),
|
||||
state=new_gateway_state,
|
||||
restart_requested=bool(current.get("restart_requested")),
|
||||
),
|
||||
restart_requested=bool(current.get("restart_requested")),
|
||||
active_agents=_parse_active_agents(current.get("active_agents", 0)),
|
||||
profile=profile,
|
||||
version=version,
|
||||
pid=_coerce_pid(current.get("pid")),
|
||||
))
|
||||
|
||||
old_platforms_raw = (previous or {}).get("platforms")
|
||||
new_platforms_raw = current.get("platforms")
|
||||
old_platforms = old_platforms_raw if isinstance(old_platforms_raw, dict) else {}
|
||||
new_platforms = new_platforms_raw if isinstance(new_platforms_raw, dict) else {}
|
||||
for platform, pdata in new_platforms.items():
|
||||
pdata = pdata if isinstance(pdata, dict) else {}
|
||||
prev_raw = old_platforms.get(platform, {})
|
||||
prev = prev_raw if isinstance(prev_raw, dict) else {}
|
||||
old_state = _bounded_state(
|
||||
prev.get("state"), allowed=_KNOWN_PLATFORM_STATES
|
||||
) if prev.get("state") is not None else None
|
||||
new_state = _bounded_state(
|
||||
pdata.get("state"), allowed=_KNOWN_PLATFORM_STATES
|
||||
) if pdata.get("state") is not None else None
|
||||
if old_state == new_state or not new_state:
|
||||
continue
|
||||
error_code = classify_gateway_error(pdata.get("error_code") or pdata.get("error_message"))
|
||||
severity = "error" if new_state.lower() in {"fatal", "failed", "error"} else "warning"
|
||||
out.append(GatewayDiagnosticEvent(
|
||||
name="platform.state_change",
|
||||
subsystem=f"platform.{platform}",
|
||||
platform=str(platform),
|
||||
old_state=old_state,
|
||||
new_state=new_state,
|
||||
error_code=error_code,
|
||||
error_class=error_code,
|
||||
profile=profile,
|
||||
version=version,
|
||||
severity=severity,
|
||||
))
|
||||
if new_state.lower() in _FATAL_PLATFORM_STATES:
|
||||
out.append(GatewayDiagnosticEvent(
|
||||
name="platform.fatal",
|
||||
subsystem=f"platform.{platform}",
|
||||
platform=str(platform),
|
||||
error_code=error_code,
|
||||
error_class=error_code,
|
||||
profile=profile,
|
||||
version=version,
|
||||
severity=severity,
|
||||
))
|
||||
for ev in out:
|
||||
ctx = dict(profile=_safe_profile(), version=_safe_version())
|
||||
for ev in _lifecycle_events(previous, current, **ctx) + _platform_events(previous, current, **ctx):
|
||||
emitter.emit(ev)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).debug("gateway runtime status transition emit failed", exc_info=True)
|
||||
logger.debug("gateway runtime status transition emit failed", exc_info=True)
|
||||
|
||||
|
||||
def _coerce_pid(raw: Any) -> Optional[int]:
|
||||
@@ -436,11 +375,10 @@ class GatewayDiagnosticLogHandler(logging.Handler):
|
||||
try:
|
||||
if record.levelno < logging.WARNING:
|
||||
return
|
||||
if not _allowed_logger(record.name):
|
||||
if not (record.name == "gateway" or record.name.startswith("gateway.")):
|
||||
return
|
||||
subsystem = subsystem_for_logger(record.name)
|
||||
message = record.getMessage()
|
||||
error_class = classify_gateway_error(message)
|
||||
error_class = classify_gateway_error(record.getMessage())
|
||||
event = GatewayDiagnosticEvent(
|
||||
name=f"gateway.log.{record.levelname.lower()}",
|
||||
subsystem=subsystem,
|
||||
@@ -452,10 +390,9 @@ class GatewayDiagnosticLogHandler(logging.Handler):
|
||||
version=self.version,
|
||||
severity=record.levelname.lower(),
|
||||
)
|
||||
from agent.monitoring import emitter
|
||||
emitter.get_emitter().emit(event)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).debug("gateway diagnostic emit failed", exc_info=True)
|
||||
logger.debug("gateway diagnostic emit failed", exc_info=True)
|
||||
|
||||
|
||||
__all__ = [
|
||||
@@ -465,5 +402,4 @@ __all__ = [
|
||||
"build_gateway_health_snapshot",
|
||||
"classify_gateway_error",
|
||||
"source_logger_for_export",
|
||||
"redact_gateway_message",
|
||||
]
|
||||
|
||||
@@ -1,101 +1,74 @@
|
||||
"""Gateway Health & Diagnostics OTLP export runtime.
|
||||
|
||||
This exporter emits operator-owned gateway service-health metrics plus
|
||||
narrow redacted diagnostic events. It is deliberately in-process and fail-open so
|
||||
it works under systemd, launchd, s6, containers, tmux, nohup, or a simple shell
|
||||
without a sidecar/watchdog dependency.
|
||||
Emits operator-owned gateway service-health metrics plus narrow redacted
|
||||
diagnostic events. Deliberately in-process and fail-open so it works under
|
||||
systemd, launchd, s6, containers, tmux, nohup, or a plain shell without a
|
||||
sidecar/watchdog dependency.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Dict, Optional
|
||||
from typing import Any, Callable, Dict, Optional
|
||||
|
||||
from agent.monitoring import emitter, otlp_exporter
|
||||
from agent.monitoring.gateway_health import (
|
||||
GatewayDiagnosticLogHandler,
|
||||
GatewayMetric,
|
||||
_safe_profile as _profile,
|
||||
_safe_version as _version,
|
||||
build_gateway_health_snapshot,
|
||||
source_logger_for_export,
|
||||
)
|
||||
from agent.monitoring.otlp_exporter import (
|
||||
EmitterStreamer,
|
||||
_allowlisted_attrs,
|
||||
_install_id,
|
||||
_monitoring_section,
|
||||
_otlp_config,
|
||||
_resolve_headers,
|
||||
_runtime_resource_attributes,
|
||||
_safe_resource_attributes, # noqa: F401 — re-exported for tests
|
||||
_signal_endpoint,
|
||||
)
|
||||
from agent.monitoring.redaction import redact_bounded
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_DEFAULT_DIAGNOSTIC_SCOPE = "hermes.gateway.diagnostics"
|
||||
|
||||
_RESOURCE_ATTRIBUTE_KEYS = frozenset({
|
||||
"service.name",
|
||||
"service.namespace",
|
||||
"service.version",
|
||||
"service.instance.id",
|
||||
"deployment.environment.name",
|
||||
"cloud.provider",
|
||||
"cloud.platform",
|
||||
"cloud.region",
|
||||
"telemetry.scope",
|
||||
})
|
||||
_DIAGNOSTIC_ATTRIBUTE_KEYS = frozenset({
|
||||
"name",
|
||||
"subsystem",
|
||||
"error_class",
|
||||
"error_code",
|
||||
"platform",
|
||||
"old_state",
|
||||
"new_state",
|
||||
"version",
|
||||
"severity",
|
||||
})
|
||||
_SAFE_RESOURCE_VALUE = re.compile(r"^[A-Za-z0-9._:/-]{1,128}$")
|
||||
|
||||
|
||||
def _redact_string(raw: Any, *, limit: int = 500) -> str:
|
||||
try:
|
||||
from agent.monitoring.redaction import redact_for_export
|
||||
return (redact_for_export(str(raw or "")) or "[redacted]")[:limit]
|
||||
except Exception:
|
||||
return "[redaction-unavailable]"
|
||||
|
||||
|
||||
def _safe_resource_attributes(raw: Any) -> Dict[str, str]:
|
||||
"""Allowlist bounded resource labels and reject values changed by redaction."""
|
||||
attrs: Dict[str, str] = {}
|
||||
if not isinstance(raw, dict):
|
||||
return attrs
|
||||
for key, value in raw.items():
|
||||
key = str(key)
|
||||
if key not in _RESOURCE_ATTRIBUTE_KEYS or value is None:
|
||||
continue
|
||||
if key == "service.instance.id":
|
||||
from agent.monitoring.gateway_health import _safe_instance_id
|
||||
attrs[key] = _safe_instance_id(value)
|
||||
continue
|
||||
text = str(value)
|
||||
if not _SAFE_RESOURCE_VALUE.fullmatch(text):
|
||||
continue
|
||||
if _redact_string(text, limit=128) != text:
|
||||
continue
|
||||
attrs[key] = text
|
||||
return attrs
|
||||
|
||||
|
||||
def _runtime_resource_attributes(
|
||||
config: Dict[str, Any], *, telemetry_scope: str
|
||||
) -> Dict[str, str]:
|
||||
"""Build the safe OTLP resource shared by metrics and diagnostic logs."""
|
||||
gh = _gateway_health_config(config)
|
||||
attrs = _safe_resource_attributes(gh.get("resource_attributes"))
|
||||
from agent.monitoring.gateway_health import _safe_instance_id
|
||||
|
||||
attrs["service.name"] = "hermes-gateway"
|
||||
attrs["service.instance.id"] = _safe_instance_id(_install_id(config))
|
||||
attrs["telemetry.scope"] = telemetry_scope
|
||||
return attrs
|
||||
_METRICS_SDK = (
|
||||
"OTLPLogExporter", "OTLPMetricExporter", "Observation", "LogRecord", "LoggerProvider",
|
||||
"INVALID_SPAN_ID", "INVALID_TRACE_ID", "TraceFlags", "SeverityNumber",
|
||||
"BatchLogRecordProcessor", "MeterProvider", "PeriodicExportingMetricReader", "Resource",
|
||||
)
|
||||
# Every gauge the runtime snapshot can emit MUST be listed here or it is silently dropped.
|
||||
_OBSERVABLE_METRIC_NAMES = (
|
||||
"hermes.gateway.up",
|
||||
"hermes.gateway.state",
|
||||
"hermes.gateway.active_agents",
|
||||
"hermes.gateway.busy",
|
||||
"hermes.gateway.drainable",
|
||||
"hermes.gateway.restart_requested",
|
||||
"hermes.gateway.background_work",
|
||||
"hermes.gateway.background_delegations",
|
||||
"hermes.platform.up",
|
||||
"hermes.platform.degraded",
|
||||
"hermes.cron.scheduler.heartbeat_age_seconds",
|
||||
"hermes.cron.scheduler.last_success_age_seconds",
|
||||
"hermes.cron.scheduler.catch_up_occurrences",
|
||||
"hermes.cron.jobs.enabled",
|
||||
"hermes.cron.jobs.running",
|
||||
"hermes.cron.jobs.overdue",
|
||||
)
|
||||
|
||||
|
||||
def _diagnostic_log_attributes(event: Dict[str, Any]) -> Dict[str, Any]:
|
||||
attrs: Dict[str, Any] = {}
|
||||
for key in _DIAGNOSTIC_ATTRIBUTE_KEYS:
|
||||
value = event.get(key)
|
||||
if value is None:
|
||||
continue
|
||||
attrs[f"hermes.{key}"] = _redact_string(value) if isinstance(value, str) else value
|
||||
return attrs
|
||||
# Same allowlist as the span mapping: profile/install_id/ts never egress as attributes.
|
||||
return _allowlisted_attrs(event, otlp_exporter._KEEP_BY_KIND["gateway_diagnostic"])
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@@ -120,26 +93,20 @@ class GatewayHealthExportRuntime:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# All producers above are now stopped. Drain queued and in-flight
|
||||
# events before detaching subscribers so the terminal lifecycle event
|
||||
# cannot race exporter shutdown. The barrier is bounded and fail-open.
|
||||
# Producers are stopped; drain queued/in-flight events BEFORE detaching subscribers
|
||||
# so the terminal lifecycle event cannot race exporter shutdown. Bounded, fail-open.
|
||||
subscribers = [item for item in (self.streamer, self.log_streamer) if item is not None]
|
||||
try:
|
||||
from agent.monitoring.emitter import get_emitter
|
||||
emitter = get_emitter()
|
||||
emitter.flush(timeout=1.0)
|
||||
if self.streamer is not None:
|
||||
emitter.unsubscribe(self.streamer)
|
||||
if self.log_streamer is not None:
|
||||
emitter.unsubscribe(self.log_streamer)
|
||||
bus = emitter.get_emitter()
|
||||
bus.flush(timeout=1.0)
|
||||
for sub in subscribers:
|
||||
bus.unsubscribe(sub)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Network flush/close runs under one bounded daemon-thread deadline and
|
||||
# can never delay gateway teardown indefinitely.
|
||||
closeables = [
|
||||
item for item in (self.streamer, self.log_streamer, self.metric_provider)
|
||||
if item is not None
|
||||
]
|
||||
# Network flush/close runs under one bounded daemon-thread deadline so it can
|
||||
# never delay gateway teardown indefinitely.
|
||||
closeables = subscribers + ([self.metric_provider] if self.metric_provider is not None else [])
|
||||
|
||||
def _close() -> None:
|
||||
for item in closeables:
|
||||
@@ -150,136 +117,55 @@ class GatewayHealthExportRuntime:
|
||||
|
||||
if closeables:
|
||||
worker = threading.Thread(
|
||||
target=_close,
|
||||
name="hermes-gateway-health-export-shutdown",
|
||||
daemon=True,
|
||||
target=_close, name="hermes-gateway-health-export-shutdown", daemon=True
|
||||
)
|
||||
worker.start()
|
||||
worker.join(timeout=2.0)
|
||||
|
||||
self.streamer = None
|
||||
self.log_streamer = None
|
||||
self.metric_provider = None
|
||||
self.thread = None
|
||||
self.stop_event = None
|
||||
self.streamer = self.log_streamer = self.metric_provider = self.thread = self.stop_event = None
|
||||
|
||||
|
||||
def _gateway_health_config(config: Dict[str, Any]) -> Dict[str, Any]:
|
||||
mon = (config or {}).get("monitoring") or {}
|
||||
return mon.get("gateway_health_export") or {}
|
||||
|
||||
|
||||
def _otlp_config(config: Dict[str, Any]) -> Dict[str, Any]:
|
||||
mon = (config or {}).get("monitoring") or {}
|
||||
export = mon.get("export") or {}
|
||||
return export.get("otlp") or {}
|
||||
return _monitoring_section(config, "gateway_health_export")
|
||||
|
||||
|
||||
def _enabled(config: Dict[str, Any]) -> bool:
|
||||
gh = _gateway_health_config(config)
|
||||
otlp = _otlp_config(config)
|
||||
return bool(gh.get("enabled") and otlp.get("enabled") and otlp.get("endpoint"))
|
||||
return bool(_gateway_health_config(config).get("enabled") and otlp_exporter.is_enabled(config))
|
||||
|
||||
|
||||
def _require_metrics_sdk(*, auto_install: bool = True, prompt: bool = False) -> Dict[str, Any]:
|
||||
if auto_install:
|
||||
try:
|
||||
from tools.lazy_deps import ensure as _lazy_ensure
|
||||
_lazy_ensure("export.otlp", prompt=prompt)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.metrics import Observation
|
||||
from opentelemetry.trace import INVALID_SPAN_ID, INVALID_TRACE_ID, TraceFlags
|
||||
from opentelemetry._logs import LogRecord
|
||||
from opentelemetry._logs.severity import SeverityNumber
|
||||
from opentelemetry.sdk._logs import LoggerProvider
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
return {
|
||||
"OTLPLogExporter": OTLPLogExporter,
|
||||
"OTLPMetricExporter": OTLPMetricExporter,
|
||||
"Observation": Observation,
|
||||
"LogRecord": LogRecord,
|
||||
"LoggerProvider": LoggerProvider,
|
||||
"INVALID_SPAN_ID": INVALID_SPAN_ID,
|
||||
"INVALID_TRACE_ID": INVALID_TRACE_ID,
|
||||
"TraceFlags": TraceFlags,
|
||||
"SeverityNumber": SeverityNumber,
|
||||
"BatchLogRecordProcessor": BatchLogRecordProcessor,
|
||||
"MeterProvider": MeterProvider,
|
||||
"PeriodicExportingMetricReader": PeriodicExportingMetricReader,
|
||||
"Resource": Resource,
|
||||
}
|
||||
return otlp_exporter._require_sdk(_METRICS_SDK, auto_install=auto_install, prompt=prompt)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"OTLP metrics SDK unavailable: {exc}") from exc
|
||||
|
||||
|
||||
def _resolve_headers(headers_env: Optional[Dict[str, str]]) -> Dict[str, str]:
|
||||
resolved: Dict[str, str] = {}
|
||||
for header_name, env_name in (headers_env or {}).items():
|
||||
val = os.environ.get(str(env_name))
|
||||
if val:
|
||||
resolved[str(header_name)] = val
|
||||
return resolved
|
||||
def _exporter_kwargs(config: Dict[str, Any], signal: str) -> Dict[str, Any]:
|
||||
otlp = _otlp_config(config)
|
||||
return {
|
||||
"endpoint": _signal_endpoint(str(otlp.get("endpoint")), signal),
|
||||
"headers": _resolve_headers(otlp.get("headers_env")) or None,
|
||||
}
|
||||
|
||||
|
||||
def _metric_endpoint(endpoint: str) -> str:
|
||||
if endpoint.endswith("/v1/traces"):
|
||||
return endpoint[: -len("/v1/traces")] + "/v1/metrics"
|
||||
return endpoint
|
||||
def _resource(config: Dict[str, Any], sdk: Dict[str, Any], telemetry_scope: str) -> Any:
|
||||
return sdk["Resource"].create(_runtime_resource_attributes(config, telemetry_scope=telemetry_scope))
|
||||
|
||||
|
||||
def _logs_endpoint(endpoint: str) -> str:
|
||||
if endpoint.endswith("/v1/traces"):
|
||||
return endpoint[: -len("/v1/traces")] + "/v1/logs"
|
||||
if endpoint.endswith("/v1/metrics"):
|
||||
return endpoint[: -len("/v1/metrics")] + "/v1/logs"
|
||||
return endpoint
|
||||
|
||||
|
||||
def _version() -> str:
|
||||
try:
|
||||
from hermes_cli import __version__
|
||||
return str(__version__)
|
||||
except Exception:
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _profile() -> str:
|
||||
try:
|
||||
from hermes_cli.profiles import get_active_profile_name
|
||||
return str(get_active_profile_name() or "default")
|
||||
except Exception:
|
||||
return "default"
|
||||
|
||||
|
||||
def _install_id(config: Dict[str, Any]) -> str:
|
||||
try:
|
||||
from agent.monitoring.policy import ensure_install_id
|
||||
return str(ensure_install_id(config))
|
||||
except Exception:
|
||||
return "unknown"
|
||||
# Ordered detection: systemd > s6 > container > launchd > manual (first match wins).
|
||||
_SUPERVISION_DETECTORS: tuple[tuple[str, Callable[[], Any]], ...] = (
|
||||
("systemd", lambda: os.environ.get("INVOCATION_ID")),
|
||||
("s6", lambda: os.environ.get("S6_CMD_ARG0") or os.environ.get("S6_VERSION")),
|
||||
("container", lambda: os.environ.get("container") or os.path.exists("/.dockerenv")),
|
||||
("launchd", lambda: os.environ.get("LAUNCHD_SOCKET")),
|
||||
)
|
||||
|
||||
|
||||
def _supervision_mode() -> str:
|
||||
if os.environ.get("INVOCATION_ID"):
|
||||
return "systemd"
|
||||
if os.environ.get("S6_CMD_ARG0") or os.environ.get("S6_VERSION"):
|
||||
return "s6"
|
||||
if os.environ.get("container") or os.path.exists("/.dockerenv"):
|
||||
return "container"
|
||||
if os.environ.get("LAUNCHD_SOCKET"):
|
||||
return "launchd"
|
||||
return "manual"
|
||||
return next((mode for mode, detect in _SUPERVISION_DETECTORS if detect()), "manual")
|
||||
|
||||
|
||||
def _read_gateway_snapshot(config: Dict[str, Any]):
|
||||
from agent.monitoring.gateway_health import build_gateway_health_snapshot
|
||||
try:
|
||||
from gateway.status import read_runtime_status
|
||||
runtime = read_runtime_status() or {}
|
||||
@@ -301,83 +187,51 @@ def _read_cron_snapshot():
|
||||
return build_cron_health_snapshot()
|
||||
|
||||
|
||||
def _count(failure_msg: str, module: str, read: Callable[[Any], Any]) -> int:
|
||||
"""Best-effort non-negative count read from a lazily imported module; 0 when it can't be imported/read."""
|
||||
try:
|
||||
return max(0, int(read(importlib.import_module(module))))
|
||||
except Exception:
|
||||
logger.debug(failure_msg, exc_info=True)
|
||||
return 0
|
||||
|
||||
|
||||
def _read_background_work_count() -> int:
|
||||
"""Count live background/subagent work that ``active_agents`` does NOT include.
|
||||
"""Live background/subagent work that ``active_agents`` deliberately does NOT include.
|
||||
|
||||
``hermes.gateway.active_agents`` counts foreground turns + in-flight cron
|
||||
jobs + API runs, but deliberately excludes backgrounded ``delegate_task``
|
||||
subagents, ``terminal(background=true)`` processes, kanban workers, and the
|
||||
runner's own background tasks (they are tracked only for the scale-to-zero
|
||||
suspend guard, ``_scale_to_zero_has_live_background_work``). Without this
|
||||
metric a peer churning through delegated subagents shows ``active_agents=0``
|
||||
on the fleet dashboard. Best-effort and content-free: a single integer,
|
||||
no job/task identity. Returns 0 if a source can't be imported.
|
||||
|
||||
Delegation is counted TASK-granular (``active_task_count``): a fan-out batch
|
||||
of N subagents contributes N, not 1, so the metric reflects real concurrent
|
||||
subagent load rather than dispatch-unit/pool-slot count. This intentionally
|
||||
differs from the async pool's capacity accounting (one batch = one slot).
|
||||
``active_agents`` counts foreground turns + in-flight cron + API runs; backgrounded
|
||||
``delegate_task`` subagents, ``terminal(background=true)`` processes and kanban workers
|
||||
are tracked only by the scale-to-zero guard, so without this a peer churning through
|
||||
subagents shows ``active_agents=0``. TASK-granular: a fan-out batch of N contributes N
|
||||
(real concurrent load), unlike the pool's one-slot-per-batch accounting. Content-free.
|
||||
"""
|
||||
total = 0
|
||||
try:
|
||||
from tools.async_delegation import active_task_count
|
||||
|
||||
total += max(0, int(active_task_count()))
|
||||
except Exception:
|
||||
logger.debug("background-work async-delegation count failed", exc_info=True)
|
||||
try:
|
||||
from tools.process_registry import process_registry
|
||||
|
||||
total += max(0, int(process_registry.count_running()))
|
||||
except Exception:
|
||||
logger.debug("background-work process-registry count failed", exc_info=True)
|
||||
return total
|
||||
return (
|
||||
_count("background-work async-delegation count failed", "tools.async_delegation",
|
||||
lambda m: m.active_task_count())
|
||||
+ _count("background-work process-registry count failed", "tools.process_registry",
|
||||
lambda m: m.process_registry.count_running())
|
||||
)
|
||||
|
||||
|
||||
def _read_background_delegations_count() -> int:
|
||||
"""Count live async delegation UNITS (dispatch/pool slots).
|
||||
|
||||
Complements ``_read_background_work_count`` (which is task-granular): this
|
||||
counts each ``delegate_task`` dispatch as ONE regardless of fan-out width,
|
||||
matching the async pool's capacity accounting (a batch = one slot). Together
|
||||
the two metrics let an operator see both slot pressure
|
||||
(``background_delegations``, alert vs ``max_concurrent_children``) and real
|
||||
concurrent subagent load (``background_work``). Delegations only — it does
|
||||
not include ``terminal(background)`` / kanban work, which are already folded
|
||||
into ``background_work``. Best-effort; 0 if the source can't be imported.
|
||||
"""
|
||||
try:
|
||||
from tools.async_delegation import active_count
|
||||
|
||||
return max(0, int(active_count()))
|
||||
except Exception:
|
||||
logger.debug("background-delegations count failed", exc_info=True)
|
||||
return 0
|
||||
"""Live async delegation UNITS (dispatch/pool slots): a batch counts ONE regardless of
|
||||
fan-out width, matching the pool's capacity accounting — so operators can see slot
|
||||
pressure (alert vs ``max_concurrent_children``) alongside ``background_work``'s real load.
|
||||
Delegations only; terminal/kanban work is already folded into ``background_work``."""
|
||||
return _count("background-delegations count failed", "tools.async_delegation", lambda m: m.active_count())
|
||||
|
||||
|
||||
def _read_runtime_snapshot(config: Dict[str, Any]):
|
||||
gateway_snapshot = _read_gateway_snapshot(config)
|
||||
# Background/subagent work — a distinct metric from active_agents (which
|
||||
# never counts it). Appended to the gateway snapshot so it rides the same
|
||||
# base resource attributes (service.instance.id etc.).
|
||||
# Background/subagent work is appended to the gateway snapshot so it rides the same base
|
||||
# resource attributes (service.instance.id etc.).
|
||||
try:
|
||||
from agent.monitoring.gateway_health import GatewayMetric
|
||||
|
||||
base = dict(gateway_snapshot.metrics[0].attributes) if gateway_snapshot.metrics else {}
|
||||
gateway_snapshot.metrics.append(
|
||||
GatewayMetric(
|
||||
name="hermes.gateway.background_work",
|
||||
value=_read_background_work_count(),
|
||||
attributes=base,
|
||||
)
|
||||
)
|
||||
gateway_snapshot.metrics.append(
|
||||
GatewayMetric(
|
||||
name="hermes.gateway.background_delegations",
|
||||
value=_read_background_delegations_count(),
|
||||
attributes=base,
|
||||
)
|
||||
)
|
||||
for name, read in (
|
||||
("hermes.gateway.background_work", _read_background_work_count),
|
||||
("hermes.gateway.background_delegations", _read_background_delegations_count),
|
||||
):
|
||||
gateway_snapshot.metrics.append(GatewayMetric(name=name, value=read(), attributes=base))
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"background-work snapshot unavailable; metric not exported (error_type=%s)",
|
||||
@@ -387,10 +241,8 @@ def _read_runtime_snapshot(config: Dict[str, Any]):
|
||||
try:
|
||||
cron_snapshot = _read_cron_snapshot()
|
||||
except Exception as exc:
|
||||
# Content-free visibility: cron telemetry silently dropping out is a
|
||||
# release-relevant regression, so surface it at WARNING with only the
|
||||
# exception *type* name (never the message, which could carry paths or
|
||||
# other environment detail). exc_info stays on the DEBUG record.
|
||||
# Cron telemetry silently dropping out is a release-relevant regression: WARN with only
|
||||
# the exception *type* (the message could carry paths); exc_info stays on DEBUG.
|
||||
logger.warning(
|
||||
"cron health snapshot unavailable; cron telemetry not exported (error_type=%s)",
|
||||
type(exc).__name__,
|
||||
@@ -402,13 +254,10 @@ def _read_runtime_snapshot(config: Dict[str, Any]):
|
||||
|
||||
|
||||
def _emit_snapshot_events(config: Dict[str, Any]) -> None:
|
||||
gh = _gateway_health_config(config)
|
||||
if not gh.get("diagnostic_events_enabled", True):
|
||||
if not _gateway_health_config(config).get("diagnostic_events_enabled", True):
|
||||
return
|
||||
try:
|
||||
from agent.monitoring import emitter
|
||||
snapshot = _read_runtime_snapshot(config)
|
||||
for event in snapshot.events:
|
||||
for event in _read_runtime_snapshot(config).events:
|
||||
emitter.emit(event)
|
||||
except Exception:
|
||||
logger.debug("gateway health snapshot emit failed", exc_info=True)
|
||||
@@ -416,43 +265,15 @@ def _emit_snapshot_events(config: Dict[str, Any]) -> None:
|
||||
|
||||
def _start_metric_provider(config: Dict[str, Any], sdk: Dict[str, Any]) -> Any:
|
||||
gh = _gateway_health_config(config)
|
||||
if not gh.get("metrics_enabled", True):
|
||||
return None
|
||||
otlp = _otlp_config(config)
|
||||
endpoint = _metric_endpoint(str(otlp.get("endpoint")))
|
||||
headers = _resolve_headers(otlp.get("headers_env"))
|
||||
exporter = sdk["OTLPMetricExporter"](endpoint=endpoint, headers=headers or None)
|
||||
exporter = sdk["OTLPMetricExporter"](**_exporter_kwargs(config, "metrics"))
|
||||
interval_ms = max(5, int(gh.get("export_interval_seconds", 60))) * 1000
|
||||
reader = sdk["PeriodicExportingMetricReader"](exporter, export_interval_millis=interval_ms)
|
||||
resource_attrs = _runtime_resource_attributes(
|
||||
config, telemetry_scope="gateway_health"
|
||||
)
|
||||
provider = sdk["MeterProvider"](
|
||||
metric_readers=[reader],
|
||||
resource=sdk["Resource"].create(resource_attrs),
|
||||
metric_readers=[reader], resource=_resource(config, sdk, "gateway_health")
|
||||
)
|
||||
meter = provider.get_meter("hermes.gateway.health")
|
||||
Observation = sdk["Observation"]
|
||||
|
||||
metric_names = [
|
||||
"hermes.gateway.up",
|
||||
"hermes.gateway.state",
|
||||
"hermes.gateway.active_agents",
|
||||
"hermes.gateway.busy",
|
||||
"hermes.gateway.drainable",
|
||||
"hermes.gateway.restart_requested",
|
||||
"hermes.gateway.background_work",
|
||||
"hermes.gateway.background_delegations",
|
||||
"hermes.platform.up",
|
||||
"hermes.platform.degraded",
|
||||
"hermes.cron.scheduler.heartbeat_age_seconds",
|
||||
"hermes.cron.scheduler.last_success_age_seconds",
|
||||
"hermes.cron.scheduler.catch_up_occurrences",
|
||||
"hermes.cron.jobs.enabled",
|
||||
"hermes.cron.jobs.running",
|
||||
"hermes.cron.jobs.overdue",
|
||||
]
|
||||
|
||||
def callback(name: str):
|
||||
def _cb(_options=None):
|
||||
try:
|
||||
@@ -463,98 +284,61 @@ def _start_metric_provider(config: Dict[str, Any], sdk: Dict[str, Any]) -> Any:
|
||||
return []
|
||||
return _cb
|
||||
|
||||
for metric_name in metric_names:
|
||||
for metric_name in _OBSERVABLE_METRIC_NAMES:
|
||||
meter.create_observable_gauge(metric_name, callbacks=[callback(metric_name)])
|
||||
return provider
|
||||
|
||||
|
||||
_SEVERITY_NAMES = {
|
||||
"critical": "FATAL",
|
||||
"fatal": "FATAL",
|
||||
"error": "ERROR",
|
||||
"info": "INFO",
|
||||
"information": "INFO",
|
||||
"debug": "DEBUG",
|
||||
}
|
||||
|
||||
|
||||
def _severity_number(sdk: Dict[str, Any], severity: Any) -> Any:
|
||||
SeverityNumber = sdk["SeverityNumber"]
|
||||
sev = str(severity or "warning").lower()
|
||||
if sev in {"critical", "fatal"}:
|
||||
return SeverityNumber.FATAL
|
||||
if sev == "error":
|
||||
return SeverityNumber.ERROR
|
||||
if sev in {"info", "information"}:
|
||||
return SeverityNumber.INFO
|
||||
if sev == "debug":
|
||||
return SeverityNumber.DEBUG
|
||||
return SeverityNumber.WARN
|
||||
return getattr(sdk["SeverityNumber"], _SEVERITY_NAMES.get(sev, "WARN"))
|
||||
|
||||
|
||||
class GatewayDiagnosticLogStreamer:
|
||||
class GatewayDiagnosticLogStreamer(EmitterStreamer):
|
||||
"""Emitter subscriber that sends gateway diagnostic events as OTLP logs."""
|
||||
|
||||
def __init__(self, config: Dict[str, Any], sdk: Dict[str, Any]):
|
||||
otlp = _otlp_config(config)
|
||||
headers = _resolve_headers(otlp.get("headers_env"))
|
||||
endpoint = _logs_endpoint(str(otlp.get("endpoint")))
|
||||
resource_attrs = _runtime_resource_attributes(
|
||||
config, telemetry_scope="gateway_diagnostics"
|
||||
)
|
||||
self._provider = sdk["LoggerProvider"](resource=sdk["Resource"].create(resource_attrs))
|
||||
self._provider = sdk["LoggerProvider"](resource=_resource(config, sdk, "gateway_diagnostics"))
|
||||
self._processor = sdk["BatchLogRecordProcessor"](
|
||||
sdk["OTLPLogExporter"](endpoint=endpoint, headers=headers or None)
|
||||
sdk["OTLPLogExporter"](**_exporter_kwargs(config, "logs"))
|
||||
)
|
||||
self._provider.add_log_record_processor(self._processor)
|
||||
self._logger = self._provider.get_logger(_DEFAULT_DIAGNOSTIC_SCOPE)
|
||||
self._LogRecord = sdk["LogRecord"]
|
||||
self._sdk = sdk
|
||||
self.exported = 0
|
||||
|
||||
def __call__(self, batch: list[Dict[str, Any]]) -> None:
|
||||
from agent.monitoring.gateway_health import source_logger_for_export
|
||||
|
||||
sdk = self._sdk
|
||||
for ev in batch:
|
||||
if ev.get("event") != "gateway_diagnostic":
|
||||
continue
|
||||
attrs = _diagnostic_log_attributes(ev)
|
||||
# Preserve the source-controlled Python logger as the OTel
|
||||
# instrumentation scope. This adds precise code attribution without
|
||||
# turning a fluid module layout into a maintained subsystem enum.
|
||||
# Rendered messages stay out because they may contain arbitrary IDs,
|
||||
# names, paths, or configured strings. A future, separately gated
|
||||
# ``diagnostic_detail: redacted_message`` mode may add best-effort
|
||||
# free text when an observability plane defines that privacy policy.
|
||||
# The source-controlled Python logger becomes the OTel instrumentation scope:
|
||||
# precise code attribution without maintaining a subsystem enum. Rendered
|
||||
# messages stay out (they may carry IDs, names, paths, configured strings).
|
||||
source_logger = source_logger_for_export(ev.get("source_logger"))
|
||||
otel_logger = (
|
||||
self._provider.get_logger(source_logger)
|
||||
if source_logger is not None
|
||||
else self._logger
|
||||
)
|
||||
body = "gateway diagnostic"
|
||||
record = self._LogRecord(
|
||||
otel_logger = self._provider.get_logger(source_logger) if source_logger is not None else self._logger
|
||||
otel_logger.emit(sdk["LogRecord"](
|
||||
timestamp=ev.get("ts_ns"),
|
||||
trace_id=self._sdk["INVALID_TRACE_ID"],
|
||||
span_id=self._sdk["INVALID_SPAN_ID"],
|
||||
trace_flags=self._sdk["TraceFlags"].DEFAULT,
|
||||
trace_id=sdk["INVALID_TRACE_ID"],
|
||||
span_id=sdk["INVALID_SPAN_ID"],
|
||||
trace_flags=sdk["TraceFlags"].DEFAULT,
|
||||
severity_text=str(ev.get("severity") or "warning").upper(),
|
||||
severity_number=_severity_number(self._sdk, ev.get("severity")),
|
||||
body=_redact_string(body),
|
||||
attributes=attrs,
|
||||
)
|
||||
otel_logger.emit(record)
|
||||
severity_number=_severity_number(sdk, ev.get("severity")),
|
||||
body=redact_bounded("gateway diagnostic"),
|
||||
attributes=_diagnostic_log_attributes(ev),
|
||||
))
|
||||
self.exported += 1
|
||||
|
||||
def shutdown(self) -> None:
|
||||
try:
|
||||
from agent.monitoring.emitter import get_emitter
|
||||
get_emitter().unsubscribe(self)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self._processor.force_flush()
|
||||
self._provider.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _start_diagnostic_log_streamer(config: Dict[str, Any], sdk: Dict[str, Any]) -> GatewayDiagnosticLogStreamer:
|
||||
from agent.monitoring.emitter import get_emitter
|
||||
streamer = GatewayDiagnosticLogStreamer(config, sdk)
|
||||
get_emitter().subscribe(streamer)
|
||||
return streamer
|
||||
|
||||
|
||||
def _start_snapshot_thread(config: Dict[str, Any], stop_event: threading.Event) -> threading.Thread:
|
||||
interval = max(5, int(_gateway_health_config(config).get("logs_export_interval_seconds", 5)))
|
||||
@@ -572,7 +356,6 @@ def _attach_log_handler(config: Dict[str, Any]) -> Any:
|
||||
gh = _gateway_health_config(config)
|
||||
if not gh.get("diagnostic_events_enabled", True) or not gh.get("warning_error_events_enabled", True):
|
||||
return None
|
||||
from agent.monitoring.gateway_health import GatewayDiagnosticLogHandler
|
||||
handler = GatewayDiagnosticLogHandler(profile=_profile(), version=_version())
|
||||
root = logging.getLogger()
|
||||
if handler not in root.handlers:
|
||||
@@ -589,10 +372,12 @@ def start_gateway_health_export(config: Dict[str, Any]) -> GatewayHealthExportRu
|
||||
if not _enabled(config):
|
||||
return GatewayHealthExportRuntime(enabled=False, reason="disabled")
|
||||
gh = _gateway_health_config(config)
|
||||
metrics_on = gh.get("metrics_enabled", True)
|
||||
diagnostics_on = gh.get("diagnostic_events_enabled", True)
|
||||
runtime = GatewayHealthExportRuntime(enabled=True, reason="enabled")
|
||||
sdk: Optional[Dict[str, Any]] = None
|
||||
|
||||
if gh.get("metrics_enabled", True) or gh.get("diagnostic_events_enabled", True):
|
||||
if metrics_on or diagnostics_on:
|
||||
try:
|
||||
sdk = _require_metrics_sdk(prompt=False)
|
||||
except Exception:
|
||||
@@ -603,7 +388,7 @@ def start_gateway_health_export(config: Dict[str, Any]) -> GatewayHealthExportRu
|
||||
)
|
||||
return GatewayHealthExportRuntime(enabled=False, reason="otlp_unavailable")
|
||||
|
||||
if gh.get("metrics_enabled", True) and sdk is not None:
|
||||
if metrics_on and sdk is not None:
|
||||
try:
|
||||
runtime.metric_provider = _start_metric_provider(config, sdk)
|
||||
except Exception:
|
||||
@@ -611,13 +396,14 @@ def start_gateway_health_export(config: Dict[str, Any]) -> GatewayHealthExportRu
|
||||
runtime.shutdown()
|
||||
return GatewayHealthExportRuntime(enabled=False, reason="metrics_start_failed")
|
||||
|
||||
if gh.get("diagnostic_events_enabled", True) and sdk is not None:
|
||||
if diagnostics_on and sdk is not None:
|
||||
try:
|
||||
from agent.monitoring import otlp_exporter
|
||||
runtime.streamer = otlp_exporter.start_streaming(config, event_filter=_gateway_health_event)
|
||||
if runtime.streamer is None:
|
||||
raise RuntimeError("gateway health span streamer did not start")
|
||||
runtime.log_streamer = _start_diagnostic_log_streamer(config, sdk)
|
||||
log_streamer = GatewayDiagnosticLogStreamer(config, sdk)
|
||||
emitter.get_emitter().subscribe(log_streamer)
|
||||
runtime.log_streamer = log_streamer
|
||||
except Exception:
|
||||
logger.debug("gateway diagnostic OTLP export failed to start", exc_info=True)
|
||||
runtime.shutdown()
|
||||
@@ -627,7 +413,7 @@ def start_gateway_health_export(config: Dict[str, Any]) -> GatewayHealthExportRu
|
||||
runtime.log_handler = _attach_log_handler(config)
|
||||
except Exception:
|
||||
logger.debug("gateway diagnostic log handler failed to attach", exc_info=True)
|
||||
if gh.get("diagnostic_events_enabled", True):
|
||||
if diagnostics_on:
|
||||
try:
|
||||
_emit_snapshot_events(config)
|
||||
runtime.stop_event = threading.Event()
|
||||
|
||||
+177
-108
@@ -1,31 +1,30 @@
|
||||
"""Export monitoring events to an OpenTelemetry Collector over OTLP/HTTP.
|
||||
|
||||
Maps gateway monitoring events to OTel spans and sends them to the endpoint
|
||||
configured under ``monitoring.export.otlp``. Lets an operator stream Hermes
|
||||
gateway health into their own observability stack (OTEL Collector, DataDog,
|
||||
and similar).
|
||||
Maps gateway monitoring events to OTel spans and sends them to the operator
|
||||
configured ``monitoring.export.otlp`` endpoint (no default destination ships).
|
||||
Also hosts the OTLP plumbing shared with ``gateway_health_export`` (SDK loading,
|
||||
header resolution, resource attributes, endpoint mapping).
|
||||
|
||||
Notes:
|
||||
* The destination is operator-configured; this module only sends to that
|
||||
endpoint. No default destination ships.
|
||||
* ``opentelemetry-sdk`` + ``opentelemetry-exporter-otlp-proto-http`` are an
|
||||
optional extra (``pip install hermes-agent[otlp]``), imported lazily so the
|
||||
dependency is only required when OTLP export is actually used.
|
||||
* ``headers_env`` maps a header name to an environment variable name; values
|
||||
are read from the environment at export time and never logged or stored.
|
||||
* The continuous subscriber runs in the emitter's dispatcher thread and is
|
||||
fail-isolated, so an export error cannot affect the gateway.
|
||||
|
||||
Only monitoring events (gateway_health / gateway_diagnostic) exist on this
|
||||
plane; the ``event_filter`` seam is kept so future planes sharing the emitter
|
||||
cannot silently ride along on this exporter.
|
||||
* The OTel SDK is an optional extra (``pip install hermes-agent[otlp]``),
|
||||
imported lazily so it is only required when export is actually used.
|
||||
* ``headers_env`` maps a header name to an environment variable name; values
|
||||
are read from the environment at export time and never logged or stored.
|
||||
* The continuous subscriber runs in the emitter's dispatcher thread and is
|
||||
fail-isolated, so an export error cannot affect the gateway. The
|
||||
``event_filter`` seam keeps future planes sharing the emitter from silently
|
||||
riding along on this exporter.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import logging
|
||||
import os
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
import re
|
||||
from typing import Any, Callable, Dict, Iterable, List, Optional
|
||||
|
||||
from agent.monitoring.gateway_health import _safe_instance_id
|
||||
from agent.monitoring.redaction import redact_bounded
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -34,43 +33,49 @@ class OTLPUnavailable(RuntimeError):
|
||||
"""Raised when the optional OpenTelemetry SDK isn't installed."""
|
||||
|
||||
|
||||
def _require_sdk(*, auto_install: bool = True, prompt: bool = True):
|
||||
"""Import the OTel SDK, lazily installing it on first use if needed.
|
||||
# ── SDK loading ──────────────────────────────────────────────────────────────
|
||||
_SDK_SYMBOLS: Dict[str, str] = {
|
||||
"TracerProvider": "opentelemetry.sdk.trace",
|
||||
"BatchSpanProcessor": "opentelemetry.sdk.trace.export",
|
||||
"Resource": "opentelemetry.sdk.resources",
|
||||
"OTLPSpanExporter": "opentelemetry.exporter.otlp.proto.http.trace_exporter",
|
||||
"SpanKind": "opentelemetry.trace",
|
||||
"OTLPLogExporter": "opentelemetry.exporter.otlp.proto.http._log_exporter",
|
||||
"OTLPMetricExporter": "opentelemetry.exporter.otlp.proto.http.metric_exporter",
|
||||
"Observation": "opentelemetry.metrics",
|
||||
"INVALID_SPAN_ID": "opentelemetry.trace",
|
||||
"INVALID_TRACE_ID": "opentelemetry.trace",
|
||||
"TraceFlags": "opentelemetry.trace",
|
||||
"LogRecord": "opentelemetry._logs",
|
||||
"SeverityNumber": "opentelemetry._logs.severity",
|
||||
"LoggerProvider": "opentelemetry.sdk._logs",
|
||||
"BatchLogRecordProcessor": "opentelemetry.sdk._logs.export",
|
||||
"MeterProvider": "opentelemetry.sdk.metrics",
|
||||
"PeriodicExportingMetricReader": "opentelemetry.sdk.metrics.export",
|
||||
}
|
||||
_SPAN_SDK = ("TracerProvider", "BatchSpanProcessor", "Resource", "OTLPSpanExporter", "SpanKind")
|
||||
|
||||
Routes through tools.lazy_deps (feature 'export.otlp') so a missing SDK
|
||||
triggers the standard venv install flow — same as every other optional
|
||||
backend — gated by security.allow_lazy_installs and TTY-prompted. Falls back
|
||||
to OTLPUnavailable (with a manual install hint) when the SDK can't be made
|
||||
importable (lazy installs disabled, install failed, or auto_install=False).
|
||||
|
||||
``auto_install``: attempt the lazy install when missing (default True).
|
||||
``prompt``: ask before installing when interactive (default True); pass
|
||||
False from non-interactive contexts like the continuous streamer.
|
||||
def _require_sdk(
|
||||
names: Iterable[str] = _SPAN_SDK, *, auto_install: bool = True, prompt: bool = True
|
||||
) -> Dict[str, Any]:
|
||||
"""Import the named OTel SDK symbols, lazily installing the extra on first use.
|
||||
|
||||
Routes through tools.lazy_deps (feature 'export.otlp') — gated by
|
||||
security.allow_lazy_installs and TTY-prompted (``prompt=False`` from
|
||||
non-interactive contexts). Any lazy-install failure falls through to the
|
||||
import attempt, which raises OTLPUnavailable with a manual install hint.
|
||||
"""
|
||||
if auto_install:
|
||||
try:
|
||||
from tools.lazy_deps import ensure as _lazy_ensure
|
||||
_lazy_ensure("export.otlp", prompt=prompt)
|
||||
except ImportError:
|
||||
pass # lazy_deps unavailable — fall through to the import attempt
|
||||
except Exception:
|
||||
# FeatureUnavailable (lazy installs disabled / declined / failed) —
|
||||
# fall through; the import below raises OTLPUnavailable with the hint.
|
||||
pass
|
||||
try:
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
|
||||
OTLPSpanExporter,
|
||||
)
|
||||
from opentelemetry.trace import SpanKind
|
||||
return {
|
||||
"TracerProvider": TracerProvider,
|
||||
"BatchSpanProcessor": BatchSpanProcessor,
|
||||
"Resource": Resource,
|
||||
"OTLPSpanExporter": OTLPSpanExporter,
|
||||
"SpanKind": SpanKind,
|
||||
name: getattr(importlib.import_module(_SDK_SYMBOLS[name]), name)
|
||||
for name in names
|
||||
}
|
||||
except Exception as e: # ImportError or partial install
|
||||
raise OTLPUnavailable(
|
||||
@@ -80,28 +85,89 @@ def _require_sdk(*, auto_install: bool = True, prompt: bool = True):
|
||||
)
|
||||
|
||||
|
||||
def _resolve_headers(headers_env: Optional[Dict[str, str]]) -> Dict[str, str]:
|
||||
"""Resolve {header_name: ENV_VAR_NAME} -> {header_name: value} from env.
|
||||
# ── config + connection plumbing ─────────────────────────────────────────────
|
||||
def _monitoring_section(config: Dict[str, Any], *path: str) -> Dict[str, Any]:
|
||||
node: Any = (config or {}).get("monitoring") or {}
|
||||
for key in path:
|
||||
node = node.get(key) or {}
|
||||
return node
|
||||
|
||||
The config stores environment variable names, not secret values; values are
|
||||
read from the environment here. Missing variables are skipped (and noted at
|
||||
debug level without the value).
|
||||
"""
|
||||
|
||||
def _otlp_config(config: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return _monitoring_section(config, "export", "otlp")
|
||||
|
||||
|
||||
def _resolve_headers(headers_env: Optional[Dict[str, str]]) -> Dict[str, str]:
|
||||
"""Resolve {header_name: ENV_VAR_NAME} -> {header_name: value}; missing vars skipped."""
|
||||
resolved: Dict[str, str] = {}
|
||||
for header_name, env_name in (headers_env or {}).items():
|
||||
val = os.environ.get(str(env_name))
|
||||
if val:
|
||||
resolved[str(header_name)] = val
|
||||
else:
|
||||
logger.debug("OTLP header %s: env var %s not set; skipping",
|
||||
header_name, env_name)
|
||||
logger.debug("OTLP header %s: env var %s not set; skipping", header_name, env_name)
|
||||
return resolved
|
||||
|
||||
|
||||
def _otlp_config(config: Dict[str, Any]) -> Dict[str, Any]:
|
||||
mon = (config or {}).get("monitoring") or {}
|
||||
export = mon.get("export") or {}
|
||||
return export.get("otlp") or {}
|
||||
_SIGNAL_SUFFIXES = ("/v1/traces", "/v1/metrics")
|
||||
|
||||
|
||||
def _signal_endpoint(endpoint: str, signal: str) -> str:
|
||||
"""Rewrite a traces/metrics OTLP path to ``/v1/<signal>``; other paths pass through."""
|
||||
target = f"/v1/{signal}"
|
||||
for suffix in _SIGNAL_SUFFIXES:
|
||||
if suffix != target and endpoint.endswith(suffix):
|
||||
return endpoint[: -len(suffix)] + target
|
||||
return endpoint
|
||||
|
||||
|
||||
_RESOURCE_ATTRIBUTE_KEYS = frozenset({
|
||||
"service.name",
|
||||
"service.namespace",
|
||||
"service.version",
|
||||
"service.instance.id",
|
||||
"deployment.environment.name",
|
||||
"cloud.provider",
|
||||
"cloud.platform",
|
||||
"cloud.region",
|
||||
"telemetry.scope",
|
||||
})
|
||||
_SAFE_RESOURCE_VALUE = re.compile(r"^[A-Za-z0-9._:/-]{1,128}$")
|
||||
|
||||
|
||||
def _install_id(config: Dict[str, Any]) -> str:
|
||||
try:
|
||||
from agent.monitoring.policy import ensure_install_id
|
||||
return str(ensure_install_id(config))
|
||||
except Exception:
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _safe_resource_attributes(raw: Any) -> Dict[str, str]:
|
||||
"""Allowlist bounded resource labels and reject values changed by redaction."""
|
||||
attrs: Dict[str, str] = {}
|
||||
for key, value in (raw.items() if isinstance(raw, dict) else ()):
|
||||
key = str(key)
|
||||
if key not in _RESOURCE_ATTRIBUTE_KEYS or value is None:
|
||||
continue
|
||||
text = str(value)
|
||||
if key == "service.instance.id":
|
||||
attrs[key] = _safe_instance_id(value)
|
||||
elif _SAFE_RESOURCE_VALUE.fullmatch(text) and redact_bounded(text, limit=128) == text:
|
||||
attrs[key] = text
|
||||
return attrs
|
||||
|
||||
|
||||
def _runtime_resource_attributes(
|
||||
config: Dict[str, Any], *, telemetry_scope: str
|
||||
) -> Dict[str, str]:
|
||||
"""Build the safe OTLP resource shared by spans, metrics and diagnostic logs."""
|
||||
gh = _monitoring_section(config, "gateway_health_export")
|
||||
attrs = _safe_resource_attributes(gh.get("resource_attributes"))
|
||||
attrs["service.name"] = "hermes-gateway"
|
||||
attrs["service.instance.id"] = _safe_instance_id(_install_id(config))
|
||||
attrs["telemetry.scope"] = telemetry_scope
|
||||
return attrs
|
||||
|
||||
|
||||
def build_exporter(config: Dict[str, Any]):
|
||||
@@ -116,11 +182,6 @@ def build_exporter(config: Dict[str, Any]):
|
||||
|
||||
|
||||
def _resource_attributes(config: Dict[str, Any]) -> Dict[str, str]:
|
||||
# Lazy import: gateway_health_export imports this module back (for
|
||||
# start_streaming), so the dependency must resolve at call time, not
|
||||
# at module load, to avoid a circular import.
|
||||
from agent.monitoring.gateway_health_export import _runtime_resource_attributes
|
||||
|
||||
return _runtime_resource_attributes(config, telemetry_scope="gateway_monitoring")
|
||||
|
||||
|
||||
@@ -134,32 +195,36 @@ def _make_provider(config: Dict[str, Any]):
|
||||
|
||||
|
||||
# ── event -> span attribute mapping ──────────────────────────────────────────
|
||||
# Per-kind attribute allowlists: everything else (profile, install_id, ...) never egresses.
|
||||
_KEEP_BY_KIND: Dict[str, tuple[str, ...]] = {
|
||||
"gateway_health": ("name", "gateway_state", "old_state", "new_state",
|
||||
"exit_reason", "restart_requested", "active_agents",
|
||||
"gateway_busy", "gateway_drainable", "platform_count",
|
||||
"fatal_platform_count", "version",
|
||||
"supervision_mode", "pid"),
|
||||
"gateway_diagnostic": ("name", "subsystem", "error_class", "error_code",
|
||||
"platform", "old_state", "new_state",
|
||||
"version", "severity"),
|
||||
"cron_execution": ("status", "job_key", "source", "duration_ms",
|
||||
"delivery_outcome", "error_class"),
|
||||
}
|
||||
|
||||
|
||||
def _allowlisted_attrs(ev: Dict[str, Any], keys: Iterable[str]) -> Dict[str, Any]:
|
||||
"""``hermes.<key>`` attributes for present keys; string values are redacted and bounded."""
|
||||
attrs: Dict[str, Any] = {}
|
||||
for col in keys:
|
||||
v = ev.get(col)
|
||||
if v is not None:
|
||||
attrs[f"hermes.{col}"] = redact_bounded(v) if isinstance(v, str) else v
|
||||
return attrs
|
||||
|
||||
|
||||
def _span_attrs(ev: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Span attributes for a monitoring event (content-free by construction)."""
|
||||
kind = ev.get("event")
|
||||
attrs: Dict[str, Any] = {"hermes.event": kind or "unknown"}
|
||||
keep_by_kind = {
|
||||
"gateway_health": ("name", "gateway_state", "old_state", "new_state",
|
||||
"exit_reason", "restart_requested", "active_agents",
|
||||
"gateway_busy", "gateway_drainable", "platform_count",
|
||||
"fatal_platform_count", "version",
|
||||
"supervision_mode", "pid"),
|
||||
"gateway_diagnostic": ("name", "subsystem", "error_class", "error_code",
|
||||
"platform", "old_state", "new_state",
|
||||
"version", "severity"),
|
||||
"cron_execution": ("status", "job_key", "source", "duration_ms",
|
||||
"delivery_outcome", "error_class"),
|
||||
}
|
||||
for col in keep_by_kind.get(kind, ()): # type: ignore[arg-type]
|
||||
v = ev.get(col)
|
||||
if v is not None:
|
||||
if isinstance(v, str):
|
||||
try:
|
||||
from agent.monitoring.redaction import redact_for_export
|
||||
v = (redact_for_export(v) or "[redacted]")[:500]
|
||||
except Exception:
|
||||
v = "[redaction-unavailable]"
|
||||
attrs[f"hermes.{col}"] = v
|
||||
attrs.update(_allowlisted_attrs(ev, _KEEP_BY_KIND.get(kind, ()))) # type: ignore[arg-type]
|
||||
return attrs
|
||||
|
||||
|
||||
@@ -178,13 +243,33 @@ def export_batch(provider, batch: List[Dict[str, Any]]) -> int:
|
||||
return n
|
||||
|
||||
|
||||
# ── continuous streaming subscriber ─────────────────────────────────────────
|
||||
class OTLPStreamer:
|
||||
"""A live subscriber that pushes each emitter batch to OTLP as it lands.
|
||||
# ── continuous streaming subscribers ─────────────────────────────────────────
|
||||
class EmitterStreamer:
|
||||
"""Base for emitter subscribers owning an OTel provider + batch processor.
|
||||
|
||||
Register with ``emitter.subscribe(streamer)``. Fail-isolated by the emitter.
|
||||
"""
|
||||
|
||||
_provider: Any
|
||||
_processor: Any
|
||||
exported: int = 0
|
||||
|
||||
def shutdown(self) -> None:
|
||||
try:
|
||||
from agent.monitoring.emitter import get_emitter
|
||||
get_emitter().unsubscribe(self)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self._processor.force_flush()
|
||||
self._provider.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class OTLPStreamer(EmitterStreamer):
|
||||
"""A live subscriber that pushes each emitter batch to OTLP as spans."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: Dict[str, Any],
|
||||
@@ -202,22 +287,9 @@ class OTLPStreamer:
|
||||
return
|
||||
self.exported += export_batch(self._provider, batch)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
try:
|
||||
from agent.monitoring.emitter import get_emitter
|
||||
get_emitter().unsubscribe(self)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self._processor.force_flush()
|
||||
self._provider.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def is_available() -> bool:
|
||||
"""True when the OTel SDK is already importable. Does NOT auto-install —
|
||||
this is a pure check (e.g. for status display)."""
|
||||
"""True when the OTel SDK is already importable (pure check, no auto-install)."""
|
||||
try:
|
||||
_require_sdk(auto_install=False)
|
||||
return True
|
||||
@@ -237,13 +309,10 @@ def start_streaming(
|
||||
) -> Optional[OTLPStreamer]:
|
||||
"""If OTLP is enabled, attach a streamer to the singleton emitter.
|
||||
|
||||
``event_filter`` scopes the exporter to its plane, e.g. gateway-health
|
||||
export, so enabling one plane cannot silently export unrelated events.
|
||||
|
||||
Non-interactive context (startup): attempts a lazy install with prompt=False
|
||||
so a configured-but-missing SDK is installed once (gated by
|
||||
security.allow_lazy_installs), then streams. If it still can't load, logs and
|
||||
no-ops — never blocks or raises into startup.
|
||||
``event_filter`` scopes the exporter to its plane. Startup is non-interactive:
|
||||
a configured-but-missing SDK is lazily installed once (prompt=False, gated by
|
||||
security.allow_lazy_installs); if it still can't load, log and no-op — never
|
||||
raise into startup.
|
||||
"""
|
||||
if not is_enabled(config):
|
||||
return None
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
"""Install identity for gateway monitoring.
|
||||
|
||||
The install id is a stable, resettable pseudonymous identifier attached to
|
||||
exported health signals so an operator can tell instances apart in their
|
||||
collector. It carries no account identity and can be rotated by clearing
|
||||
``monitoring.install_id`` in config.
|
||||
A stable, resettable pseudonymous id attached to exported health signals so an
|
||||
operator can tell instances apart. Carries no account identity; rotate by
|
||||
clearing ``monitoring.install_id`` in config.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,14 +17,9 @@ logger = logging.getLogger(__name__)
|
||||
def ensure_install_id(config: Dict[str, Any]) -> str:
|
||||
"""Return a stable install id, minting and persisting one when empty.
|
||||
|
||||
The id must survive gateway restarts (it becomes ``service.instance.id``
|
||||
on exported signals), so a freshly minted UUID is written back to
|
||||
config.yaml immediately. The write is fail-open: if persisting fails
|
||||
(read-only home, managed scope), the ephemeral id is still returned and
|
||||
a new one is minted next start.
|
||||
|
||||
Clearing ``monitoring.install_id`` (e.g. ``hermes config set
|
||||
monitoring.install_id ""``) rotates the id on the next gateway start.
|
||||
The id becomes ``service.instance.id`` and must survive restarts, so a fresh
|
||||
UUID is written to config.yaml immediately. Fail-open: if persisting fails
|
||||
(read-only home, managed scope) the ephemeral id is still returned.
|
||||
"""
|
||||
mon = config.get("monitoring") if isinstance(config, dict) else None
|
||||
existing = (mon or {}).get("install_id") if isinstance(mon, dict) else None
|
||||
|
||||
@@ -1,24 +1,17 @@
|
||||
"""Redaction applied to monitoring data before egress.
|
||||
|
||||
One unconditional scrub, no modes, no knobs. Every string that leaves the
|
||||
process passes through ``redact_for_export``:
|
||||
|
||||
* Secrets first — wraps ``agent/redact.py::redact_sensitive_text(force=True)``
|
||||
plus bearer/token-shape patterns, and fails CLOSED: if the redactor cannot
|
||||
run, the raw string is never emitted.
|
||||
* PII second — e-mail addresses, phone numbers, and UUID-shaped identifiers
|
||||
are rewritten to ``[email]`` / ``[phone]`` / ``[id]``.
|
||||
|
||||
There is deliberately no setting to weaken this. The monitoring plane is
|
||||
content-free by design: rendered log messages are not exported, and bounded
|
||||
structured strings are still scrubbed as defense-in-depth. This redactor also
|
||||
remains available for a future, explicitly gated redacted-message detail mode.
|
||||
process passes through ``redact_for_export``: secrets first (wraps
|
||||
``agent/redact.py::redact_sensitive_text(force=True)`` plus bearer/token
|
||||
shapes, failing CLOSED so a broken redactor never emits the raw string), then
|
||||
PII (e-mail, phone, UUID-shaped ids -> ``[email]`` / ``[phone]`` / ``[id]``).
|
||||
There is deliberately no setting to weaken this.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Optional
|
||||
from typing import Any, Optional
|
||||
|
||||
# ── secret shapes (belt-and-suspenders on top of agent/redact.py) ───────────
|
||||
_BEARER_RE = re.compile(r"\bBearer\s+[A-Za-z0-9._~+\-/]+=*", re.IGNORECASE)
|
||||
@@ -34,11 +27,12 @@ _EMAIL_RE = re.compile(r"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}")
|
||||
_PHONE_RE = re.compile(
|
||||
r"(?<!\w)(?:\+?\d{1,3}[\s.\-]?)?(?:\(\d{2,4}\)[\s.\-]?)?\d{3}[\s.\-]?\d{3,4}(?:[\s.\-]?\d{2,4})?(?!\w)"
|
||||
)
|
||||
# Long opaque hex/uuid-ish user identifiers.
|
||||
_UUID_RE = re.compile(
|
||||
r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b"
|
||||
)
|
||||
|
||||
UNAVAILABLE = "[redaction-unavailable]"
|
||||
|
||||
|
||||
def _secret_redact(text: str) -> str:
|
||||
"""Always-on secret redaction. force=True so user config can't disable it."""
|
||||
@@ -47,11 +41,9 @@ def _secret_redact(text: str) -> str:
|
||||
out = redact_sensitive_text(text, force=True)
|
||||
except Exception:
|
||||
# Fail CLOSED: if the redactor can't run, do not emit the raw string.
|
||||
return "[redaction-unavailable]"
|
||||
out = _BEARER_RE.sub("[redacted]", out)
|
||||
out = _TOKEN_RE.sub("[redacted]", out)
|
||||
out = _SECRET_LITERAL_RE.sub("[redacted]", out)
|
||||
out = _BEARER_RESIDUE_RE.sub("[redacted]", out)
|
||||
return UNAVAILABLE
|
||||
for pattern in (_BEARER_RE, _TOKEN_RE, _SECRET_LITERAL_RE, _BEARER_RESIDUE_RE):
|
||||
out = pattern.sub("[redacted]", out)
|
||||
return out
|
||||
|
||||
|
||||
@@ -66,6 +58,22 @@ def redact_for_export(text: Optional[str]) -> Optional[str]:
|
||||
return out
|
||||
|
||||
|
||||
def redact_bounded(
|
||||
raw: Any,
|
||||
*,
|
||||
limit: int = 500,
|
||||
empty: str = "[redacted]",
|
||||
unavailable: str = UNAVAILABLE,
|
||||
) -> str:
|
||||
"""Redact ``str(raw or "")`` and length-bound it; ``empty`` replaces an empty
|
||||
result, ``unavailable`` is returned if redaction itself raises."""
|
||||
try:
|
||||
return (redact_for_export(str(raw or "")) or empty)[:limit]
|
||||
except Exception:
|
||||
return unavailable
|
||||
|
||||
|
||||
__all__ = [
|
||||
"redact_for_export",
|
||||
"redact_bounded",
|
||||
]
|
||||
|
||||
+15
-37
@@ -1,24 +1,12 @@
|
||||
"""Shared one-off LLM requests for non-conversational helpers.
|
||||
|
||||
A "one-shot" is a single, stateless model call that runs *outside* any
|
||||
conversation: it never touches a session's history, never breaks prompt
|
||||
caching, and returns plain text. UI surfaces use it for small generative
|
||||
chores — a commit message from a diff, a rename suggestion, a summary —
|
||||
where spinning up an agent turn would be wrong (it would pollute the thread)
|
||||
and hand-rolling an LLM call at every call site would be worse.
|
||||
|
||||
Two ways to call it:
|
||||
|
||||
* ``run_oneshot(instructions=..., user_input=...)`` — caller supplies the
|
||||
full prompt.
|
||||
* ``run_oneshot(template="commit_message", variables={...})`` — caller
|
||||
names a registered template and passes its variables; the template owns
|
||||
the prompt engineering so it stays consistent across CLI/TUI/desktop.
|
||||
|
||||
Model selection rides the same auxiliary plumbing as title generation
|
||||
(:func:`agent.auxiliary_client.call_llm`): pass ``main_runtime`` to inherit
|
||||
the live session's provider/model, otherwise the configured ``task`` (default
|
||||
``title_generation``) resolves a cheap/fast backend.
|
||||
A "one-shot" is a single stateless model call outside any conversation: it
|
||||
never touches session history or prompt caching and returns plain text (commit
|
||||
messages, rename suggestions, summaries). Call with explicit
|
||||
``instructions``/``user_input`` or a registered ``template`` + ``variables`` so
|
||||
prompt engineering stays consistent across CLI/TUI/desktop. Model selection
|
||||
rides :func:`agent.auxiliary_client.call_llm`: ``main_runtime`` inherits the
|
||||
live session's provider/model, else ``task`` resolves a cheap backend.
|
||||
"""
|
||||
|
||||
import logging
|
||||
@@ -28,7 +16,6 @@ from agent.auxiliary_client import call_llm, extract_content_or_reasoning
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# A template turns a variables dict into a (instructions, user_input) pair.
|
||||
# Templates are plain callables (not str.format) so diff/code payloads with
|
||||
# literal "{" / "}" pass through untouched.
|
||||
PromptTemplate = Callable[[Dict[str, Any]], Tuple[str, str]]
|
||||
@@ -69,9 +56,9 @@ def _commit_message_template(variables: Dict[str, Any]) -> Tuple[str, str]:
|
||||
)
|
||||
parts.append("Diff to describe:\n" + (diff or "(no textual diff available)"))
|
||||
|
||||
# "Regenerate" must yield something new even on models that decode greedily
|
||||
# / pin temperature server-side. A trailing nonce isn't enough, so we hand
|
||||
# back the previous message and require a genuinely different one.
|
||||
# "Regenerate" must yield something new even on greedy/server-pinned
|
||||
# temperature models; a nonce isn't enough, so hand back the previous
|
||||
# message and require a genuinely different one.
|
||||
avoid = _truncate(str(variables.get("avoid") or "").strip(), 1000)
|
||||
if avoid:
|
||||
parts.append(
|
||||
@@ -84,19 +71,14 @@ def _commit_message_template(variables: Dict[str, Any]) -> Tuple[str, str]:
|
||||
return _COMMIT_INSTRUCTIONS, "\n\n".join(parts)
|
||||
|
||||
|
||||
# Registry of named templates. Add an entry here to give a new surface a
|
||||
# consistent, reusable prompt without teaching every caller the prompt text.
|
||||
# Registry of named templates; add an entry to give a new surface a reusable prompt.
|
||||
PROMPT_TEMPLATES: Dict[str, PromptTemplate] = {
|
||||
"commit_message": _commit_message_template,
|
||||
}
|
||||
|
||||
|
||||
def render_template(name: str, variables: Optional[Dict[str, Any]] = None) -> Tuple[str, str]:
|
||||
"""Resolve a registered template into (instructions, user_input).
|
||||
|
||||
Raises KeyError if the template name is unknown so callers fail loudly
|
||||
instead of silently sending an empty prompt.
|
||||
"""
|
||||
"""Resolve a registered template into (instructions, user_input); KeyError if unknown."""
|
||||
template = PROMPT_TEMPLATES.get(name)
|
||||
if template is None:
|
||||
raise KeyError(f"unknown one-shot template: {name}")
|
||||
@@ -115,14 +97,10 @@ def run_oneshot(
|
||||
timeout: float = 60.0,
|
||||
main_runtime: Optional[Dict[str, Any]] = None,
|
||||
) -> str:
|
||||
"""Run a single stateless LLM request and return its text.
|
||||
"""Run a single stateless LLM request and return its text (fence-stripped).
|
||||
|
||||
Provide either a registered ``template`` (+ ``variables``) or an explicit
|
||||
``instructions`` / ``user_input`` pair. Returns the model's text answer,
|
||||
stripped of surrounding whitespace and any wrapping code fence.
|
||||
|
||||
Raises RuntimeError when no LLM provider is configured (surfaced from
|
||||
:func:`call_llm`) and KeyError for an unknown template name.
|
||||
Raises RuntimeError when no provider is configured (from :func:`call_llm`),
|
||||
KeyError for an unknown template, ValueError when the prompt is empty.
|
||||
"""
|
||||
if template:
|
||||
instructions, user_input = render_template(template, variables)
|
||||
|
||||
+80
-224
@@ -1,67 +1,31 @@
|
||||
"""
|
||||
Outbound webhook notifications.
|
||||
"""Outbound webhook notifications.
|
||||
|
||||
Reads the ``hooks.outbound:`` list from ``config.yaml`` and registers
|
||||
notify-only callbacks on the existing plugin hook manager, so every
|
||||
``invoke_hook()`` site can push lifecycle events to external HTTP
|
||||
endpoints — CI systems, dashboards, other agents — with zero changes to
|
||||
call sites and zero polling on the receiving end.
|
||||
Reads ``hooks.outbound:`` from config.yaml and registers notify-only callbacks on
|
||||
the plugin hook manager, so every ``invoke_hook()`` site can push lifecycle events
|
||||
to external HTTP endpoints. Outbound mirror of ``gateway/platforms/webhook.py``.
|
||||
|
||||
This is the outbound mirror of the inbound webhook platform
|
||||
(``gateway/platforms/webhook.py``): inbound wakes Hermes when the world
|
||||
changes; outbound tells the world when Hermes does something.
|
||||
* Delivery is fire-and-forget through a bounded queue and one daemon worker
|
||||
thread; callbacks serialize, enqueue, and return ``None`` immediately, so a
|
||||
target can never block a tool call or influence agent flow.
|
||||
* Payloads are HMAC-SHA256 signed (``X-Hermes-Signature-256: sha256=<hex>`` over
|
||||
the raw body) when a secret is configured.
|
||||
* No consent prompt (no code runs on this machine); ``HERMES_SAFE_MODE=1`` still
|
||||
skips registration. Registration is idempotent.
|
||||
|
||||
Design notes
|
||||
------------
|
||||
* Delivery is fire-and-forget through a bounded in-process queue and a
|
||||
single daemon worker thread. ``invoke_hook()`` runs inside the agent
|
||||
loop, so callbacks must never block on network I/O — they serialize,
|
||||
enqueue, and return ``None`` immediately. Outbound targets can never
|
||||
block a tool call, inject context, or otherwise influence agent flow.
|
||||
* Payloads are signed with HMAC-SHA256 (GitHub-style
|
||||
``X-Hermes-Signature-256: sha256=<hexdigest>`` over the raw body) when
|
||||
a secret is configured. Receivers verify exactly like they verify
|
||||
GitHub webhooks.
|
||||
* No consent prompt: unlike shell hooks, an outbound target executes no
|
||||
code on this machine — it POSTs JSON to a URL the user themselves put
|
||||
in config. ``HERMES_SAFE_MODE=1`` still skips registration, matching
|
||||
plugins / MCP / shell hooks.
|
||||
* Registration is idempotent — safe to invoke from both the CLI entry
|
||||
point and the gateway entry point.
|
||||
|
||||
Config schema (``~/.hermes/config.yaml``)::
|
||||
Config::
|
||||
|
||||
hooks:
|
||||
outbound:
|
||||
- url: https://ci.example.com/hermes-events
|
||||
events: [on_session_end, subagent_stop]
|
||||
# secret literal (discouraged) or env var name (preferred):
|
||||
secret_env: HERMES_OUTBOUND_WEBHOOK_SECRET
|
||||
# optional regex, honored for pre/post_tool_call only:
|
||||
matcher: "terminal|delegate_task"
|
||||
timeout: 10 # per-attempt seconds, clamped to [1, 60]
|
||||
name: ci-notify # optional label for logs / `hermes hooks list`
|
||||
secret_env: HERMES_OUTBOUND_WEBHOOK_SECRET # or inline ``secret``
|
||||
matcher: "terminal|delegate_task" # pre/post_tool_call only
|
||||
timeout: 10 # seconds, clamped to [1, 60]
|
||||
name: ci-notify
|
||||
|
||||
Wire format (POST body)::
|
||||
|
||||
{
|
||||
"hook_event_name": "on_session_end",
|
||||
"tool_name": null,
|
||||
"tool_input": null,
|
||||
"session_id": "sess_abc123",
|
||||
"cwd": "/home/user/project",
|
||||
"extra": {...}, # event-specific kwargs
|
||||
"delivery_id": "3f2c...", # uuid4, unique per POST
|
||||
"timestamp": "2026-07-22T14:00:00Z"
|
||||
}
|
||||
|
||||
Headers::
|
||||
|
||||
Content-Type: application/json
|
||||
User-Agent: Hermes-Agent-Outbound-Webhook
|
||||
X-Hermes-Event: <hook event name>
|
||||
X-Hermes-Delivery: <delivery_id>
|
||||
X-Hermes-Signature-256: sha256=<hmac hexdigest> # only when secret set
|
||||
POST body: ``{hook_event_name, profile, tool_name, tool_input, session_id, cwd,
|
||||
extra, delivery_id, timestamp}``. Headers: ``Content-Type``, ``User-Agent``,
|
||||
``X-Hermes-Event``, ``X-Hermes-Delivery``, ``X-Hermes-Signature-256`` (if secret).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -78,12 +42,19 @@ import threading
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional, Set, Tuple
|
||||
from urllib import error as urlerror
|
||||
from urllib import request as urlrequest
|
||||
|
||||
from agent.shell_hooks import (
|
||||
_TOOL_EVENTS as _TOOL_SCOPED_EVENTS,
|
||||
_ToolMatcherMixin,
|
||||
_forget_home_registrations,
|
||||
_home_key,
|
||||
_payload_fields,
|
||||
_utc_now_iso,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_TIMEOUT_SECONDS = 10
|
||||
@@ -92,17 +63,8 @@ MAX_DELIVERY_ATTEMPTS = 2
|
||||
RETRY_BACKOFF_SECONDS = 1.0
|
||||
QUEUE_MAX_SIZE = 256
|
||||
|
||||
# Events whose ``matcher`` field is honored (mirrors shell hooks).
|
||||
_TOOL_SCOPED_EVENTS = {"pre_tool_call", "post_tool_call"}
|
||||
|
||||
# kwargs promoted to top-level payload keys (mirrors shell hooks wire).
|
||||
_TOP_LEVEL_PAYLOAD_KEYS = {"tool_name", "args", "session_id", "parent_session_id"}
|
||||
|
||||
# (home, event, url) triples already wired to the plugin manager in this
|
||||
# process. Home is part of the key so a multiplexed gateway's secondary
|
||||
# profiles — each with their own plugin manager (see
|
||||
# hermes_cli.plugins.get_plugin_manager) — can register identical webhook
|
||||
# targets without the first profile's registration shadowing the rest.
|
||||
# (home, event, url) triples already wired in this process. Home is part of the key so a
|
||||
# multiplexed gateway's secondary profiles (own plugin managers) can register identical targets.
|
||||
_registered: Set[Tuple[str, str, str]] = set()
|
||||
_registered_lock = threading.Lock()
|
||||
|
||||
@@ -114,9 +76,11 @@ _worker: Optional[threading.Thread] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class WebhookTarget:
|
||||
class WebhookTarget(_ToolMatcherMixin):
|
||||
"""Parsed and validated representation of one ``hooks.outbound`` entry."""
|
||||
|
||||
_MATCHER_KIND = "outbound webhook"
|
||||
|
||||
url: str
|
||||
events: List[str]
|
||||
name: str = ""
|
||||
@@ -125,47 +89,18 @@ class WebhookTarget:
|
||||
timeout: int = DEFAULT_TIMEOUT_SECONDS
|
||||
compiled_matcher: Optional[re.Pattern] = field(default=None, repr=False)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if isinstance(self.matcher, str):
|
||||
stripped = self.matcher.strip()
|
||||
self.matcher = stripped if stripped else None
|
||||
if self.matcher:
|
||||
try:
|
||||
self.compiled_matcher = re.compile(self.matcher)
|
||||
except re.error as exc:
|
||||
logger.warning(
|
||||
"outbound webhook matcher %r is invalid (%s) — treating "
|
||||
"as literal equality", self.matcher, exc,
|
||||
)
|
||||
self.compiled_matcher = None
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
return self.name or self.url
|
||||
|
||||
def matches_tool(self, tool_name: Optional[str]) -> bool:
|
||||
if not self.matcher:
|
||||
return True
|
||||
if tool_name is None:
|
||||
return False
|
||||
if self.compiled_matcher is not None:
|
||||
return self.compiled_matcher.fullmatch(tool_name) is not None
|
||||
return tool_name == self.matcher
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public API
|
||||
# ---------------------------------------------------------------------------
|
||||
# --- Public API -----------------------------------------------------------------
|
||||
|
||||
def register_from_config(cfg: Optional[Dict[str, Any]]) -> List[WebhookTarget]:
|
||||
"""Register every configured outbound webhook on the plugin manager.
|
||||
|
||||
``cfg`` is the full parsed config dict. Missing, empty, or malformed
|
||||
``hooks.outbound`` is treated as zero targets — config parsing never
|
||||
raises, because a broken webhook entry must not crash the agent.
|
||||
|
||||
Returns the targets that ended up wired (deduplicated across repeat
|
||||
calls, so the CLI and gateway can both invoke this safely).
|
||||
Malformed ``hooks.outbound`` means zero targets — never raises. Returns the
|
||||
targets that ended up wired (deduplicated across repeat calls).
|
||||
"""
|
||||
if not isinstance(cfg, dict):
|
||||
return []
|
||||
@@ -176,18 +111,14 @@ def register_from_config(cfg: Optional[Dict[str, Any]]) -> List[WebhookTarget]:
|
||||
logger.info("HERMES_SAFE_MODE=1 — outbound webhook registration skipped")
|
||||
return []
|
||||
|
||||
hooks_cfg = cfg.get("hooks")
|
||||
targets = _parse_outbound_block(
|
||||
hooks_cfg.get("outbound") if isinstance(hooks_cfg, dict) else None
|
||||
)
|
||||
targets = iter_configured_targets(cfg)
|
||||
if not targets:
|
||||
return []
|
||||
|
||||
from hermes_cli.plugins import get_plugin_manager
|
||||
from hermes_constants import get_hermes_home
|
||||
|
||||
manager = get_plugin_manager()
|
||||
home_key = str(get_hermes_home().expanduser().resolve())
|
||||
home_key = _home_key()
|
||||
|
||||
registered: List[WebhookTarget] = []
|
||||
with _registered_lock:
|
||||
@@ -214,8 +145,7 @@ def register_from_config(cfg: Optional[Dict[str, Any]]) -> List[WebhookTarget]:
|
||||
|
||||
|
||||
def iter_configured_targets(cfg: Optional[Dict[str, Any]]) -> List[WebhookTarget]:
|
||||
"""Parse ``hooks.outbound`` without registering anything.
|
||||
Used by ``hermes hooks list``."""
|
||||
"""Parse ``hooks.outbound`` without registering anything (``hermes hooks list``)."""
|
||||
if not isinstance(cfg, dict):
|
||||
return []
|
||||
hooks_cfg = cfg.get("hooks")
|
||||
@@ -225,8 +155,7 @@ def iter_configured_targets(cfg: Optional[Dict[str, Any]]) -> List[WebhookTarget
|
||||
|
||||
|
||||
def flush(timeout: float = 5.0) -> bool:
|
||||
"""Block until all queued deliveries are done (or *timeout* elapses).
|
||||
Returns ``True`` when the queue fully drained. Test/shutdown helper."""
|
||||
"""Block until all queued deliveries are done (or *timeout* elapses); True if drained."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
with _delivery_queue.all_tasks_done:
|
||||
@@ -238,25 +167,14 @@ def flush(timeout: float = 5.0) -> bool:
|
||||
|
||||
|
||||
def re_register_config_hooks() -> None:
|
||||
"""Re-register outbound webhooks from config after a plugin force-reload.
|
||||
"""Re-register outbound webhooks after a plugin force-reload cleared ``_hooks``.
|
||||
|
||||
Mirrors ``agent.shell_hooks.re_register_config_hooks``: config-owned
|
||||
outbound-webhook callbacks live in the same ``_hooks`` dict that
|
||||
``PluginManager.discover_and_load(force=True)`` clears via ``unload()``,
|
||||
so without this the force-reloaded profile's outbound webhooks go
|
||||
silently inert (#92682 review). Only the current home's idempotence
|
||||
keys are cleared so a force-reload in one profile cannot invalidate
|
||||
another profile's still-live registration.
|
||||
Only the current home's idempotence keys are cleared so a force-reload in one
|
||||
profile cannot invalidate another profile's still-live registration.
|
||||
"""
|
||||
from hermes_cli.config import load_config
|
||||
from hermes_constants import get_hermes_home
|
||||
|
||||
home_key = str(get_hermes_home().expanduser().resolve())
|
||||
with _registered_lock:
|
||||
_registered.difference_update(
|
||||
{key for key in _registered if key[0] == home_key}
|
||||
)
|
||||
|
||||
_forget_home_registrations(_registered, _registered_lock)
|
||||
register_from_config(load_config())
|
||||
|
||||
|
||||
@@ -272,9 +190,7 @@ def reset_for_tests() -> None:
|
||||
pass
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Config parsing
|
||||
# ---------------------------------------------------------------------------
|
||||
# --- Config parsing -------------------------------------------------------------
|
||||
|
||||
def _parse_outbound_block(raw: Any) -> List[WebhookTarget]:
|
||||
if raw is None:
|
||||
@@ -285,100 +201,68 @@ def _parse_outbound_block(raw: Any) -> List[WebhookTarget]:
|
||||
type(raw).__name__,
|
||||
)
|
||||
return []
|
||||
|
||||
targets: List[WebhookTarget] = []
|
||||
for i, entry in enumerate(raw):
|
||||
target = _parse_single_target(i, entry)
|
||||
if target is not None:
|
||||
targets.append(target)
|
||||
return targets
|
||||
targets = (_parse_single_target(i, entry) for i, entry in enumerate(raw))
|
||||
return [t for t in targets if t is not None]
|
||||
|
||||
|
||||
def _parse_single_target(index: int, raw: Any) -> Optional[WebhookTarget]:
|
||||
from hermes_cli.plugins import VALID_HOOKS
|
||||
|
||||
def warn(msg: str, *args: Any) -> None:
|
||||
logger.warning("hooks.outbound[%d]" + msg, index, *args)
|
||||
|
||||
if not isinstance(raw, dict):
|
||||
logger.warning(
|
||||
"hooks.outbound[%d] must be a mapping with 'url' and 'events' "
|
||||
"keys; got %s", index, type(raw).__name__,
|
||||
)
|
||||
warn(" must be a mapping with 'url' and 'events' keys; got %s", type(raw).__name__)
|
||||
return None
|
||||
|
||||
url = raw.get("url")
|
||||
if not isinstance(url, str) or not url.strip():
|
||||
logger.warning("hooks.outbound[%d] is missing a non-empty 'url'", index)
|
||||
warn(" is missing a non-empty 'url'")
|
||||
return None
|
||||
url = url.strip()
|
||||
if not url.lower().startswith(("http://", "https://")):
|
||||
logger.warning(
|
||||
"hooks.outbound[%d].url must be http(s); got %r — skipped",
|
||||
index, url,
|
||||
)
|
||||
warn(".url must be http(s); got %r — skipped", url)
|
||||
return None
|
||||
if url.lower().startswith("http://"):
|
||||
logger.warning(
|
||||
"hooks.outbound[%d].url uses plain http:// — payloads (including "
|
||||
"tool inputs) travel unencrypted. Prefer https.", index,
|
||||
)
|
||||
warn(".url uses plain http:// — payloads (including tool inputs) travel unencrypted. Prefer https.")
|
||||
|
||||
events_raw = raw.get("events")
|
||||
valid_list = ", ".join(sorted(VALID_HOOKS))
|
||||
if not isinstance(events_raw, list) or not events_raw:
|
||||
logger.warning(
|
||||
"hooks.outbound[%d] needs a non-empty 'events' list (valid: %s)",
|
||||
index, ", ".join(sorted(VALID_HOOKS)),
|
||||
)
|
||||
warn(" needs a non-empty 'events' list (valid: %s)", valid_list)
|
||||
return None
|
||||
events: List[str] = []
|
||||
for ev in events_raw:
|
||||
if ev in VALID_HOOKS:
|
||||
events.append(ev)
|
||||
else:
|
||||
logger.warning(
|
||||
"hooks.outbound[%d]: unknown event %r ignored (valid: %s)",
|
||||
index, ev, ", ".join(sorted(VALID_HOOKS)),
|
||||
)
|
||||
warn(": unknown event %r ignored (valid: %s)", ev, valid_list)
|
||||
if not events:
|
||||
logger.warning(
|
||||
"hooks.outbound[%d] has no valid events — skipped", index,
|
||||
)
|
||||
warn(" has no valid events — skipped")
|
||||
return None
|
||||
|
||||
matcher = raw.get("matcher")
|
||||
if matcher is not None and not isinstance(matcher, str):
|
||||
logger.warning(
|
||||
"hooks.outbound[%d].matcher must be a string regex; ignoring",
|
||||
index,
|
||||
)
|
||||
warn(".matcher must be a string regex; ignoring")
|
||||
matcher = None
|
||||
if matcher is not None and not any(e in _TOOL_SCOPED_EVENTS for e in events):
|
||||
logger.warning(
|
||||
"hooks.outbound[%d].matcher=%r will be ignored — matcher is only "
|
||||
"honored for pre_tool_call / post_tool_call.", index, matcher,
|
||||
)
|
||||
warn(".matcher=%r will be ignored — matcher is only honored for pre_tool_call / post_tool_call.", matcher)
|
||||
matcher = None
|
||||
|
||||
timeout_raw = raw.get("timeout", DEFAULT_TIMEOUT_SECONDS)
|
||||
try:
|
||||
timeout = int(timeout_raw)
|
||||
except (TypeError, ValueError):
|
||||
logger.warning(
|
||||
"hooks.outbound[%d].timeout must be an int (got %r); using "
|
||||
"default %ds", index, timeout_raw, DEFAULT_TIMEOUT_SECONDS,
|
||||
)
|
||||
warn(".timeout must be an int (got %r); using default %ds", timeout_raw, DEFAULT_TIMEOUT_SECONDS)
|
||||
timeout = DEFAULT_TIMEOUT_SECONDS
|
||||
timeout = max(1, min(timeout, MAX_TIMEOUT_SECONDS))
|
||||
|
||||
secret = _resolve_secret(index, raw)
|
||||
|
||||
name = raw.get("name")
|
||||
if not isinstance(name, str):
|
||||
name = ""
|
||||
|
||||
return WebhookTarget(
|
||||
url=url,
|
||||
events=events,
|
||||
name=name.strip(),
|
||||
secret=secret,
|
||||
name=name.strip() if isinstance(name, str) else "",
|
||||
secret=_resolve_secret(index, raw),
|
||||
matcher=matcher,
|
||||
timeout=timeout,
|
||||
)
|
||||
@@ -397,26 +281,21 @@ def _resolve_secret(index: int, raw: Dict[str, Any]) -> Optional[str]:
|
||||
)
|
||||
return None
|
||||
secret = raw.get("secret")
|
||||
if isinstance(secret, str) and secret:
|
||||
return secret
|
||||
return None
|
||||
return secret if isinstance(secret, str) and secret else None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Callback + delivery
|
||||
# ---------------------------------------------------------------------------
|
||||
# --- Callback + delivery --------------------------------------------------------
|
||||
|
||||
def _make_callback(event: str, target: WebhookTarget):
|
||||
"""Build the notify-only closure ``invoke_hook()`` calls per firing."""
|
||||
|
||||
def _callback(**kwargs: Any) -> None:
|
||||
if event in _TOOL_SCOPED_EVENTS:
|
||||
if not target.matches_tool(kwargs.get("tool_name")):
|
||||
return None
|
||||
if event in _TOOL_SCOPED_EVENTS and not target.matches_tool(kwargs.get("tool_name")):
|
||||
return None
|
||||
delivery_id = uuid.uuid4().hex
|
||||
try:
|
||||
body = _serialize_payload(event, kwargs, delivery_id)
|
||||
except Exception: # defensive — a bad payload must not hurt the loop
|
||||
except Exception: # a bad payload must not hurt the loop
|
||||
logger.warning(
|
||||
"outbound webhook payload serialization failed (event=%s "
|
||||
"target=%s)", event, target.label, exc_info=True,
|
||||
@@ -433,34 +312,20 @@ def _make_callback(event: str, target: WebhookTarget):
|
||||
def _serialize_payload(
|
||||
event: str, kwargs: Dict[str, Any], delivery_id: str,
|
||||
) -> bytes:
|
||||
"""Render the POST body. Same top-level shape as shell hooks' stdin
|
||||
(documented in :mod:`agent.shell_hooks`), plus delivery metadata.
|
||||
"""Render the POST body: shell-hooks stdin shape plus delivery metadata.
|
||||
|
||||
``delivery_id`` is shared with the ``X-Hermes-Delivery`` header so
|
||||
receivers can dedupe on either — and since it (plus ``timestamp``)
|
||||
lives inside the HMAC-signed body, it doubles as replay protection.
|
||||
``delivery_id`` (also the ``X-Hermes-Delivery`` header) and ``timestamp`` live
|
||||
inside the HMAC-signed body, so they double as replay protection.
|
||||
"""
|
||||
extras = {k: v for k, v in kwargs.items() if k not in _TOP_LEVEL_PAYLOAD_KEYS}
|
||||
try:
|
||||
cwd = str(Path.cwd())
|
||||
except OSError:
|
||||
cwd = ""
|
||||
# Resolved at fire time from the bound home so a multiplexed gateway's
|
||||
# receivers can tell which profile emitted the event (#92674).
|
||||
# Profile resolved at fire time so a multiplexed gateway's receivers can tell which profile emitted.
|
||||
from hermes_cli.profiles import get_active_profile_name
|
||||
|
||||
payload = {
|
||||
"hook_event_name": event,
|
||||
"profile": get_active_profile_name(),
|
||||
"tool_name": kwargs.get("tool_name"),
|
||||
"tool_input": kwargs.get("args") if isinstance(kwargs.get("args"), dict) else None,
|
||||
"session_id": kwargs.get("session_id") or kwargs.get("parent_session_id") or "",
|
||||
"cwd": cwd,
|
||||
"extra": extras,
|
||||
**_payload_fields(kwargs),
|
||||
"delivery_id": delivery_id,
|
||||
"timestamp": datetime.now(tz=timezone.utc)
|
||||
.isoformat()
|
||||
.replace("+00:00", "Z"),
|
||||
"timestamp": _utc_now_iso(),
|
||||
}
|
||||
return json.dumps(payload, ensure_ascii=False, default=str).encode("utf-8")
|
||||
|
||||
@@ -511,11 +376,9 @@ def _ensure_worker() -> None:
|
||||
target=_worker_loop, name="outbound-webhooks", daemon=True,
|
||||
)
|
||||
_worker.start()
|
||||
# The worker is a daemon thread, so a short-lived process (a `-q`
|
||||
# CLI run, a cron session) can exit right after enqueuing the
|
||||
# final events — silently dropping on_session_end, the headline
|
||||
# use case. Drain the queue at interpreter shutdown, bounded so
|
||||
# a dead endpoint can only delay exit, never hang it.
|
||||
# Daemon worker: a short-lived process could exit right after enqueuing
|
||||
# on_session_end. Drain at interpreter shutdown, bounded so a dead
|
||||
# endpoint can only delay exit, never hang it.
|
||||
atexit.register(flush, timeout=5.0)
|
||||
|
||||
|
||||
@@ -536,13 +399,8 @@ def _worker_loop() -> None:
|
||||
|
||||
|
||||
class _NoRedirectHandler(urlrequest.HTTPRedirectHandler):
|
||||
"""Refuse to follow redirects.
|
||||
|
||||
urllib's default handler converts a redirected POST into a body-less
|
||||
GET — the signed payload would be silently dropped and the headers
|
||||
re-sent to a location the user never configured. Treat any 3xx as a
|
||||
delivery failure instead (surfaced as HTTPError by returning None).
|
||||
"""
|
||||
"""Refuse redirects: urllib would turn a redirected POST into a body-less GET,
|
||||
silently dropping the signed payload. Any 3xx surfaces as HTTPError instead."""
|
||||
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D102
|
||||
return None
|
||||
@@ -552,9 +410,7 @@ _opener = urlrequest.build_opener(_NoRedirectHandler)
|
||||
|
||||
|
||||
def _deliver(delivery: Dict[str, Any]) -> None:
|
||||
"""POST with bounded retries. Retries on connection errors and 5xx;
|
||||
4xx is the receiver telling us the request itself is wrong — no retry.
|
||||
3xx redirects are never followed (misconfiguration — fix the URL)."""
|
||||
"""POST with bounded retries: retry on connection errors and 5xx; 4xx and 3xx are final."""
|
||||
last_error = ""
|
||||
for attempt in range(1, MAX_DELIVERY_ATTEMPTS + 1):
|
||||
req = urlrequest.Request(
|
||||
|
||||
@@ -140,8 +140,7 @@ STATE_ALIASES: dict[str, tuple[str, ...]] = {
|
||||
def state_aliases_for(state: "PetState | str") -> tuple[str, ...]:
|
||||
"""Return accepted row-name aliases for *state* (always non-empty)."""
|
||||
value = state.value if isinstance(state, PetState) else str(state)
|
||||
aliases = STATE_ALIASES.get(value)
|
||||
return aliases if aliases else (value,)
|
||||
return STATE_ALIASES.get(value) or (value,)
|
||||
|
||||
|
||||
def state_rows_for_grid(row_count: int | None) -> list[str]:
|
||||
@@ -150,10 +149,7 @@ def state_rows_for_grid(row_count: int | None) -> list[str]:
|
||||
rows = int(row_count or 0)
|
||||
except (TypeError, ValueError):
|
||||
rows = 0
|
||||
|
||||
if rows >= len(CODEX_STATE_ROWS):
|
||||
return CODEX_STATE_ROWS
|
||||
return LEGACY_STATE_ROWS
|
||||
return CODEX_STATE_ROWS if rows >= len(CODEX_STATE_ROWS) else LEGACY_STATE_ROWS
|
||||
|
||||
|
||||
def state_row_index(state: "PetState | str", row_count: int | None = None) -> int:
|
||||
|
||||
+329
-603
File diff suppressed because it is too large
Load Diff
@@ -37,17 +37,6 @@ _PROVIDER_LABELS: dict[str, str] = {
|
||||
}
|
||||
|
||||
|
||||
def _forced_provider_from_env() -> str | None:
|
||||
"""Optional QA override to force a pet-gen backend.
|
||||
|
||||
`HERMES_PET_IMAGE_PROVIDER=<name>` (e.g. `openrouter`) bypasses the normal
|
||||
active/default provider resolution for pet generation only. Unknown values are
|
||||
ignored so existing users are unaffected.
|
||||
"""
|
||||
forced = os.environ.get("HERMES_PET_IMAGE_PROVIDER", "").strip().lower()
|
||||
return forced if forced in _REF_CAPABLE else None
|
||||
|
||||
|
||||
class GenerationError(RuntimeError):
|
||||
"""Raised on any image-generation failure (no provider, API error, IO)."""
|
||||
|
||||
@@ -70,6 +59,14 @@ def _discover() -> None:
|
||||
logger.debug("image-gen plugin discovery failed: %s", exc)
|
||||
|
||||
|
||||
def _available(name: str):
|
||||
"""The registered provider *name* if it exists and has credentials, else ``None``."""
|
||||
from agent.image_gen_registry import get_provider
|
||||
|
||||
provider = get_provider(name)
|
||||
return provider if provider is not None and provider.is_available() else None
|
||||
|
||||
|
||||
def resolve_provider(*, require_references: bool = True, prefer: str | None = None) -> SpriteProvider:
|
||||
"""Pick the image provider to use for sprite work.
|
||||
|
||||
@@ -80,25 +77,17 @@ def resolve_provider(*, require_references: bool = True, prefer: str | None = No
|
||||
prompt-only base drafts).
|
||||
"""
|
||||
_discover()
|
||||
from agent.image_gen_registry import get_active_provider, get_provider
|
||||
from agent.image_gen_registry import get_active_provider
|
||||
|
||||
# QA override: force one provider for pet-gen iteration regardless of the
|
||||
# globally active image_gen backend.
|
||||
forced = _forced_provider_from_env()
|
||||
if forced:
|
||||
chosen = get_provider(forced)
|
||||
if chosen is not None and chosen.is_available():
|
||||
return SpriteProvider(name=forced, provider=chosen, supports_references=True)
|
||||
|
||||
# An explicit user pick wins when it's reference-capable and has credentials;
|
||||
# otherwise we ignore it and fall through to the normal resolution.
|
||||
if prefer:
|
||||
chosen = get_provider(prefer)
|
||||
if prefer in _REF_CAPABLE and chosen is not None and chosen.is_available():
|
||||
return SpriteProvider(name=prefer, provider=chosen, supports_references=True)
|
||||
# QA override: ``HERMES_PET_IMAGE_PROVIDER=<name>`` forces one ref-capable backend
|
||||
# for pet-gen only (unknown values ignored). Then an explicit user pick (desktop
|
||||
# picker) wins when ref-capable and configured; otherwise fall through.
|
||||
forced = os.environ.get("HERMES_PET_IMAGE_PROVIDER", "").strip().lower()
|
||||
for name in (forced, prefer):
|
||||
if name in _REF_CAPABLE and (chosen := _available(name)) is not None:
|
||||
return SpriteProvider(name=name, provider=chosen, supports_references=True)
|
||||
|
||||
# Configured / active provider first.
|
||||
active = None
|
||||
try:
|
||||
active = get_active_provider()
|
||||
except Exception: # noqa: BLE001
|
||||
@@ -110,8 +99,8 @@ def resolve_provider(*, require_references: bool = True, prefer: str | None = No
|
||||
|
||||
# Any available reference-capable provider.
|
||||
for name in _REF_CAPABLE:
|
||||
provider = get_provider(name)
|
||||
if provider is not None and provider.is_available():
|
||||
provider = _available(name)
|
||||
if provider is not None:
|
||||
return SpriteProvider(name=name, provider=provider, supports_references=True)
|
||||
|
||||
if not require_references and active is not None and active.is_available():
|
||||
@@ -136,26 +125,15 @@ def list_sprite_providers() -> list[dict]:
|
||||
yield an empty list.
|
||||
"""
|
||||
_discover()
|
||||
from agent.image_gen_registry import get_provider
|
||||
|
||||
try:
|
||||
default_name = resolve_provider(require_references=True).name
|
||||
except GenerationError:
|
||||
default_name = ""
|
||||
|
||||
out: list[dict] = []
|
||||
for name in _REF_CAPABLE:
|
||||
provider = get_provider(name)
|
||||
if provider is None or not provider.is_available():
|
||||
continue
|
||||
out.append(
|
||||
{
|
||||
"name": name,
|
||||
"label": _PROVIDER_LABELS.get(name, name),
|
||||
"default": name == default_name,
|
||||
}
|
||||
)
|
||||
return out
|
||||
return [
|
||||
{"name": name, "label": _PROVIDER_LABELS.get(name, name), "default": name == default_name}
|
||||
for name in _REF_CAPABLE
|
||||
if _available(name) is not None
|
||||
]
|
||||
|
||||
|
||||
def _save_local(image_ref: str, *, prefix: str) -> Path:
|
||||
|
||||
+120
-165
@@ -1,16 +1,12 @@
|
||||
"""Pet generation orchestration — the base-draft → hatch flow.
|
||||
|
||||
Two steps, mirroring the UX across every surface:
|
||||
1. :func:`generate_base_drafts` — a few cheap prompt-only "what should this pet
|
||||
look like" variants; the user picks one (or retries).
|
||||
2. :func:`hatch_pet` — grounds one row strip per Hermes state on the chosen base,
|
||||
slices frames, composes + validates the atlas, and writes it to the store.
|
||||
|
||||
1. :func:`generate_base_drafts` — a handful of prompt-only "what should this pet
|
||||
look like" variants. Cheap; the user picks one (or retries for a fresh set).
|
||||
2. :func:`hatch_pet` — takes the chosen base and generates one grounded row
|
||||
strip per Hermes state, slices each into frames, composes the atlas, validates
|
||||
it, and writes the pet into the store.
|
||||
|
||||
Splitting it this way bounds cost (4 cheap base calls per round; the ~6 row
|
||||
calls happen once, on the pet you actually keep) and gives each UI a natural
|
||||
preview/loading point.
|
||||
Splitting bounds cost (4 cheap base calls per round; the ~8 row calls happen
|
||||
once, on the pet you keep) and gives each UI a natural preview/loading point.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,7 +16,7 @@ import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
from typing import Callable, Iterator
|
||||
|
||||
from agent.pet.generate import atlas, imagegen, prompts
|
||||
from agent.pet.generate.imagegen import GenerationError, SpriteProvider
|
||||
@@ -30,18 +26,30 @@ logger = logging.getLogger(__name__)
|
||||
# (event, detail) — e.g. ("row", "idle"), ("compose", ""), ("save", "<slug>").
|
||||
ProgressFn = Callable[[str, str], None]
|
||||
|
||||
# Image generations are independent network calls, so we fan them out instead of
|
||||
# blocking on each in turn — a hatch is ~8 row calls that would otherwise run
|
||||
# back-to-back and routinely blow past the client's RPC timeout. Capped so we
|
||||
# don't hammer the provider's rate limit (one cold call can still be slow).
|
||||
# Generations are independent network calls, fanned out so a hatch (~8 rows)
|
||||
# doesn't blow the client's RPC timeout; capped to respect provider rate limits.
|
||||
_MAX_PARALLEL_GENERATIONS = 4
|
||||
# How many times to (re)generate a single row before accepting a best-effort
|
||||
# slice. Early attempts demand clean per-pose gutters; the last is lenient so a
|
||||
# stubborn row still yields frames instead of dropping out entirely.
|
||||
# Row (re)generation attempts: early ones demand clean per-pose gutters, the
|
||||
# last is lenient so a stubborn row still yields frames instead of dropping out.
|
||||
_ROW_GEN_ATTEMPTS = 3
|
||||
_MIN_FILLED_STATES = 6
|
||||
_REQUIRED_STATES = frozenset({"idle", "running-right", "waving"})
|
||||
|
||||
# (substrings, friendly message), first match wins. Moderation is the big one:
|
||||
# image models refuse trademarked characters / real people as an opaque 400.
|
||||
_IMAGE_ERROR_HINTS: tuple[tuple[tuple[str, ...], str], ...] = (
|
||||
(
|
||||
("moderation_blocked", "safety system", "content policy", "content_policy"),
|
||||
"The image provider blocked this prompt — its safety filter rejects "
|
||||
"trademarked characters and real people. Try an original description.",
|
||||
),
|
||||
(
|
||||
("api key", "unauthorized", "401", "auth"),
|
||||
"The image provider rejected the request — check your API key in Settings → Providers.",
|
||||
),
|
||||
(("rate limit", "429"), "The image provider is rate-limiting — wait a moment and try again."),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HatchResult:
|
||||
@@ -54,47 +62,60 @@ class HatchResult:
|
||||
validation: dict
|
||||
|
||||
|
||||
def _unlink_quietly(path: Path) -> None:
|
||||
try:
|
||||
path.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _harden_transparency(path: Path) -> Path:
|
||||
"""Key out any solid backdrop the provider painted; save as an RGBA PNG.
|
||||
|
||||
``background=transparent`` is requested on every call, but image models honor
|
||||
it inconsistently — some still paint a flat (often near-white) backdrop. We
|
||||
run the same chroma-key pass the row extractor uses so every base draft the
|
||||
user picks between (and the reference the rows are grounded on) is a clean
|
||||
cutout. Best-effort: a decode failure leaves the original untouched.
|
||||
``background=transparent`` is requested but honored inconsistently, so run the
|
||||
row extractor's chroma-key pass on every base draft. Best-effort: a decode
|
||||
failure leaves the original untouched.
|
||||
"""
|
||||
from PIL import Image
|
||||
|
||||
try:
|
||||
with Image.open(path) as opened:
|
||||
keyed = atlas.remove_background(opened.convert("RGBA"))
|
||||
# Zero the RGB of any leftover semi-transparent edge pixels so a keyed
|
||||
# draft has no colored halo when composited on the dark UI.
|
||||
keyed = atlas._clear_transparent_rgb(keyed)
|
||||
# PNG inputs are hardened in place, including mixed-case suffixes like
|
||||
# .PNG. with_suffix(".png") would name a different Path string that still
|
||||
# resolves to the same file on case-insensitive filesystems (macOS APFS,
|
||||
# Windows), and unlinking path after save would delete the hardened output.
|
||||
if path.suffix.lower() == ".png":
|
||||
out = path
|
||||
else:
|
||||
out = path.with_suffix(".png")
|
||||
keyed = atlas._clear_transparent_rgb(keyed) # no colored halo on the dark UI
|
||||
# PNGs (any case) are hardened in place: with_suffix(".png") on ".PNG" would
|
||||
# name the same file on case-insensitive filesystems and the unlink below
|
||||
# would delete the hardened output.
|
||||
out = path if path.suffix.lower() == ".png" else path.with_suffix(".png")
|
||||
keyed.save(out, format="PNG")
|
||||
if out != path:
|
||||
# The hardened PNG stands in for the draft. When the provider handed
|
||||
# back a non-PNG file (webp, jpg, gif), out is a different path, so
|
||||
# remove the original instead of leaving it behind in cache/images
|
||||
# (nothing prunes that directory outside the gateway loop).
|
||||
try:
|
||||
path.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
# Nothing prunes cache/images outside the gateway loop: drop the
|
||||
# non-PNG original the hardened PNG replaces.
|
||||
_unlink_quietly(path)
|
||||
return out
|
||||
except Exception as exc: # noqa: BLE001 - cosmetic; fall back to the raw image
|
||||
logger.debug("base draft transparency hardening failed for %s: %s", path, exc)
|
||||
return path
|
||||
|
||||
|
||||
def _run_parallel(fn, items, *, cancelled, on_cancel_log: str) -> Iterator:
|
||||
"""Fan *fn* over *items* in a pool, yielding results in completion order.
|
||||
|
||||
``as_completed`` runs on the caller's (request) thread, so callbacks fired
|
||||
from the results inherit the request's bound transport, unlike the workers.
|
||||
Once *cancelled* trips, queued work is cancelled and in-flight results dropped.
|
||||
"""
|
||||
workers = max(1, min(len(items), _MAX_PARALLEL_GENERATIONS))
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
futures = [pool.submit(fn, item) for item in items]
|
||||
for fut in as_completed(futures):
|
||||
if cancelled():
|
||||
logger.info(on_cancel_log)
|
||||
for pending in futures:
|
||||
pending.cancel()
|
||||
break
|
||||
yield fut.result()
|
||||
|
||||
|
||||
def generate_base_drafts(
|
||||
concept: str,
|
||||
*,
|
||||
@@ -107,31 +128,23 @@ def generate_base_drafts(
|
||||
) -> list[Path]:
|
||||
"""Generate *n* candidate base looks for *concept*; returns image paths.
|
||||
|
||||
Each draft is hardened to a transparent cutout (see :func:`_harden_transparency`).
|
||||
Drafts are generated concurrently and *on_draft(index, path)* fires as each
|
||||
one finishes (not at the end) so callers can stream previews to the UI
|
||||
instead of leaving it blank until the whole batch is done.
|
||||
|
||||
*is_cancelled*, when supplied, is polled cooperatively: a draft that hasn't
|
||||
started yet is skipped, and once it trips we stop staging/streaming further
|
||||
drafts and cancel any queued work (already-in-flight provider calls can't be
|
||||
hard-killed, but their results are dropped).
|
||||
Drafts run concurrently and are hardened to transparent cutouts;
|
||||
*on_draft(index, path)* fires as each finishes so UIs can stream previews.
|
||||
*is_cancelled* is polled cooperatively (unstarted drafts skipped, queued work
|
||||
cancelled, in-flight results dropped).
|
||||
"""
|
||||
# A user reference image (e.g. their own pet) grounds every draft, so it
|
||||
# needs a reference-capable provider — same requirement as the row passes.
|
||||
# A user reference image grounds every draft, so it needs a reference-capable provider.
|
||||
refs = reference_images or None
|
||||
sprite = provider or imagegen.resolve_provider(require_references=bool(refs))
|
||||
cancelled = is_cancelled or (lambda: False)
|
||||
|
||||
# Each draft is its own one-shot generation, run concurrently so the user
|
||||
# waits for one image, not N. A single draft failing must not sink the set.
|
||||
# Each gets a distinct variation nudge so the options aren't near-duplicates.
|
||||
logger.info("pet generate: drafting %d base looks for %r (style=%s)", n, concept, style)
|
||||
|
||||
def _one(index: int) -> tuple[int, Path | None, str | None]:
|
||||
if cancelled():
|
||||
return index, None, None
|
||||
t0 = time.monotonic()
|
||||
# Distinct variation nudge per draft so the options aren't near-duplicates.
|
||||
variation = prompts.BASE_VARIATIONS[index % len(prompts.BASE_VARIATIONS)]
|
||||
prompt = prompts.build_base_prompt(concept, style=style, variation=variation)
|
||||
try:
|
||||
@@ -145,68 +158,40 @@ def generate_base_drafts(
|
||||
logger.info("pet generate: draft %d ready in %.1fs", index, time.monotonic() - t0)
|
||||
return index, _harden_transparency(out[0]), None
|
||||
|
||||
workers = max(1, min(n, _MAX_PARALLEL_GENERATIONS))
|
||||
results: dict[int, Path] = {}
|
||||
errors: list[str] = []
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
futures = [pool.submit(_one, i) for i in range(n)]
|
||||
# as_completed runs in *this* (the caller's) thread, so on_draft — and any
|
||||
# gateway event it emits — inherits the request's bound transport, unlike
|
||||
# the worker threads above.
|
||||
for fut in as_completed(futures):
|
||||
if cancelled():
|
||||
logger.info("pet generate: cancelled — dropping remaining drafts")
|
||||
for pending in futures:
|
||||
pending.cancel()
|
||||
break
|
||||
index, path, err = fut.result()
|
||||
if path is None:
|
||||
if err:
|
||||
errors.append(err)
|
||||
continue
|
||||
results[index] = path
|
||||
if on_draft is not None:
|
||||
try:
|
||||
on_draft(index, path)
|
||||
except Exception as exc: # noqa: BLE001 - progress is best-effort
|
||||
logger.debug("on_draft callback failed: %s", exc)
|
||||
for index, path, err in _run_parallel(
|
||||
_one, range(n), cancelled=cancelled, on_cancel_log="pet generate: cancelled — dropping remaining drafts"
|
||||
):
|
||||
if path is None:
|
||||
if err:
|
||||
errors.append(err)
|
||||
continue
|
||||
results[index] = path
|
||||
if on_draft is not None:
|
||||
try:
|
||||
on_draft(index, path)
|
||||
except Exception as exc: # noqa: BLE001 - progress is best-effort
|
||||
logger.debug("on_draft callback failed: %s", exc)
|
||||
|
||||
drafts = [results[i] for i in sorted(results)]
|
||||
if not drafts and not cancelled():
|
||||
# Surface *why* — every draft failed for a reason (a content-policy refusal
|
||||
# on a name like "minion", a provider/auth error, …); the most common one
|
||||
# is the representative cause. Far more useful than "no usable drafts".
|
||||
raise GenerationError(_drafts_failed_reason(errors))
|
||||
# Surface *why*: the most common failure reason is the representative cause.
|
||||
if not errors:
|
||||
raise GenerationError("image generation produced no usable drafts")
|
||||
from collections import Counter
|
||||
|
||||
raise GenerationError(_humanize_image_error(Counter(errors).most_common(1)[0][0]))
|
||||
return drafts
|
||||
|
||||
|
||||
def _drafts_failed_reason(errors: list[str]) -> str:
|
||||
"""The representative reason a draft round produced nothing, humanized."""
|
||||
if not errors:
|
||||
return "image generation produced no usable drafts"
|
||||
from collections import Counter
|
||||
|
||||
return _humanize_image_error(Counter(errors).most_common(1)[0][0])
|
||||
|
||||
|
||||
def _humanize_image_error(error: str) -> str:
|
||||
"""Turn a raw provider error into a friendly, actionable sentence.
|
||||
|
||||
The big one is moderation: image models refuse trademarked characters and
|
||||
real people (e.g. "minion"), which reads as an opaque 400 otherwise.
|
||||
"""
|
||||
"""Turn a raw provider error into a friendly, actionable sentence."""
|
||||
low = error.lower()
|
||||
if any(s in low for s in ("moderation_blocked", "safety system", "content policy", "content_policy")):
|
||||
return (
|
||||
"The image provider blocked this prompt — its safety filter rejects "
|
||||
"trademarked characters and real people. Try an original description."
|
||||
)
|
||||
if any(s in low for s in ("api key", "unauthorized", "401", "auth")):
|
||||
return "The image provider rejected the request — check your API key in Settings → Providers."
|
||||
if "rate limit" in low or "429" in low:
|
||||
return "The image provider is rate-limiting — wait a moment and try again."
|
||||
# Otherwise the first line, trimmed of the noisy provider envelope.
|
||||
return error.splitlines()[0].strip()[:200]
|
||||
for needles, message in _IMAGE_ERROR_HINTS:
|
||||
if any(s in low for s in needles):
|
||||
return message
|
||||
return error.splitlines()[0].strip()[:200] # first line, sans provider envelope
|
||||
|
||||
|
||||
def hatch_pet(
|
||||
@@ -223,14 +208,10 @@ def hatch_pet(
|
||||
) -> HatchResult:
|
||||
"""Turn an approved base image into a full, installed Hermes pet.
|
||||
|
||||
Generates a grounded row strip per state, extracts frames, composes +
|
||||
validates the atlas, and registers it. The idle row falls back to the base
|
||||
look so the pet always renders. Raises :class:`GenerationError` on failure.
|
||||
|
||||
*is_cancelled*, when supplied, is polled cooperatively: rows that haven't
|
||||
started are skipped, queued rows are cancelled, and once every row is done we
|
||||
abort (raising :class:`GenerationError`) before composing/saving so a stopped
|
||||
hatch never writes a half-built pet.
|
||||
Idle falls back to the base look so the pet always renders. Raises
|
||||
:class:`GenerationError` on failure. *is_cancelled* is polled cooperatively
|
||||
and, once tripped, aborts before composing/saving so a stopped hatch never
|
||||
writes a half-built pet.
|
||||
"""
|
||||
base = Path(base_image)
|
||||
if not base.is_file():
|
||||
@@ -245,19 +226,15 @@ def hatch_pet(
|
||||
total_rows = len(atlas.ROW_SPECS)
|
||||
logger.info("pet hatch %r: generating %d animation rows", slug, total_rows)
|
||||
|
||||
# Generate every state's row strip concurrently — they're independent
|
||||
# grounded calls, so the hatch waits for the slowest row, not their sum. A
|
||||
# single row failing is tolerated (idle is guaranteed below).
|
||||
def _gen_row(spec: tuple[str, int, int]) -> tuple[str, list | None]:
|
||||
state, _row, count = spec
|
||||
if cancelled():
|
||||
return state, None
|
||||
t0 = time.monotonic()
|
||||
last_exc: Exception | None = None
|
||||
# Self-healing: a model occasionally returns a row whose poses are touching
|
||||
# (no clean gutters), which slices badly. We retry such rolls; only the
|
||||
# final attempt falls back to lenient ``auto`` slicing so a stubborn row
|
||||
# still yields *something* rather than dropping the whole row.
|
||||
# Self-healing: a roll whose poses touch (no gutters) slices badly, so
|
||||
# ``components`` (raises on touching poses) drives regeneration and only
|
||||
# the final attempt uses lenient ``auto`` slicing.
|
||||
for attempt in range(_ROW_GEN_ATTEMPTS):
|
||||
if cancelled():
|
||||
return state, None
|
||||
@@ -270,14 +247,10 @@ def hatch_pet(
|
||||
reference_images=[base],
|
||||
provider=sprite,
|
||||
prefix=f"pet_row_{state}",
|
||||
# Wider canvas → each frame gets real horizontal room, so winged
|
||||
# poses keep a full, healthy size and still leave clean gutters.
|
||||
# Wider canvas: each frame gets real horizontal room and clean gutters.
|
||||
aspect_ratio="landscape",
|
||||
)
|
||||
# ``components`` requires clean per-pose gutters (raises otherwise),
|
||||
# so a touching roll is rejected and regenerated; the last attempt
|
||||
# uses ``auto`` (equal-slot fallback, never raises). Raw (fit=False)
|
||||
# so normalize_cells registers the whole pet at once.
|
||||
# fit=False keeps raw columns so normalize_cells registers the whole pet at once.
|
||||
method = "components" if strict else "auto"
|
||||
frames = atlas.extract_strip_frames(strips[0], count, method=method, fit=False)
|
||||
logger.info(
|
||||
@@ -292,51 +265,35 @@ def hatch_pet(
|
||||
slug, state, attempt + 1, _ROW_GEN_ATTEMPTS, exc,
|
||||
)
|
||||
finally:
|
||||
# The strip is an intermediate. extract_strip_frames has already
|
||||
# decoded its frames into memory, so drop the row image after
|
||||
# every attempt (success or failure). Nothing prunes
|
||||
# cache/images outside the gateway housekeeping loop, so a CLI
|
||||
# or desktop hatch would otherwise leave each strip behind for
|
||||
# good and grow the cache without bound.
|
||||
# Strips are intermediates already decoded into memory; nothing
|
||||
# prunes cache/images outside the gateway loop, so drop them now.
|
||||
for strip in strips:
|
||||
try:
|
||||
Path(strip).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
_unlink_quietly(Path(strip))
|
||||
logger.warning(
|
||||
"pet hatch %r: row %r gave up after %.1fs: %s",
|
||||
slug, state, time.monotonic() - t0, last_exc,
|
||||
)
|
||||
return state, None
|
||||
|
||||
# running-left is derived by mirroring running-right (guaranteed-consistent
|
||||
# and one fewer generation), so we don't generate it directly.
|
||||
# running-left is mirrored from running-right (consistent, one fewer generation).
|
||||
generated_specs = [spec for spec in atlas.ROW_SPECS if spec[0] != "running-left"]
|
||||
|
||||
workers = max(1, min(len(generated_specs), _MAX_PARALLEL_GENERATIONS))
|
||||
done = 0
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
futures = [pool.submit(_gen_row, spec) for spec in generated_specs]
|
||||
# as_completed runs on the caller (request) thread, so progress events
|
||||
# emitted here inherit the request transport — unlike the worker threads.
|
||||
for fut in as_completed(futures):
|
||||
if cancelled():
|
||||
logger.info("pet hatch %r: cancelled — dropping remaining rows", slug)
|
||||
for pending in futures:
|
||||
pending.cancel()
|
||||
break
|
||||
state, frames = fut.result()
|
||||
done += 1
|
||||
progress("row", f"{state}:{done}:{total_rows}")
|
||||
if frames:
|
||||
frames_by_state[state] = frames
|
||||
for state, frames in _run_parallel(
|
||||
_gen_row,
|
||||
generated_specs,
|
||||
cancelled=cancelled,
|
||||
on_cancel_log=f"pet hatch {slug!r}: cancelled — dropping remaining rows",
|
||||
):
|
||||
done += 1
|
||||
progress("row", f"{state}:{done}:{total_rows}")
|
||||
if frames:
|
||||
frames_by_state[state] = frames
|
||||
|
||||
if cancelled():
|
||||
raise GenerationError("hatch cancelled")
|
||||
|
||||
# Derive running-left from the approved running-right row (per-frame mirror,
|
||||
# preserving order/timing). Missing running-right is rejected below; a pet
|
||||
# without its canonical walk cycle is a failed hatch, not a shippable mascot.
|
||||
# Per-frame mirror preserves order/timing. A missing running-right is
|
||||
# rejected below: a pet without its canonical walk cycle is a failed hatch.
|
||||
right = frames_by_state.get("running-right")
|
||||
if right:
|
||||
done += 1
|
||||
@@ -346,15 +303,13 @@ def hatch_pet(
|
||||
else:
|
||||
logger.warning("pet hatch %r: no running-right to mirror; left walk left empty", slug)
|
||||
|
||||
# Idle is the resting state the renderer falls back to — guarantee it.
|
||||
if not frames_by_state.get("idle"):
|
||||
if not frames_by_state.get("idle"): # the renderer's resting fallback — guarantee it
|
||||
progress("row", "idle-fallback")
|
||||
frames_by_state["idle"] = [atlas.single_frame(base, fit=False)]
|
||||
|
||||
progress("compose", "")
|
||||
logger.info("pet hatch %r: composing atlas from %d states", slug, len(frames_by_state))
|
||||
# One shared scale + baseline across every state so the pet never slides or
|
||||
# pulses size between frames; compose just packs the normalized cells.
|
||||
# One shared scale + baseline across states so the pet never slides or pulses.
|
||||
sheet = atlas.compose_atlas(atlas.normalize_cells(frames_by_state))
|
||||
validation = atlas.validate_atlas(sheet)
|
||||
if not validation["ok"]:
|
||||
|
||||
@@ -120,7 +120,7 @@ def fetch_manifest(*, timeout: float = _DEFAULT_TIMEOUT, force: bool = False) ->
|
||||
"""
|
||||
global _cache
|
||||
|
||||
if not force and _cache is not None and time.monotonic() - _cache[0] < _MANIFEST_TTL:
|
||||
if not force and _cache_is_warm():
|
||||
return _cache[1]
|
||||
|
||||
try:
|
||||
@@ -144,14 +144,8 @@ def fetch_manifest(*, timeout: float = _DEFAULT_TIMEOUT, force: bool = False) ->
|
||||
if not isinstance(pets, list):
|
||||
raise ManifestError("petdex manifest had no 'pets' array")
|
||||
|
||||
entries: list[ManifestEntry] = []
|
||||
for raw in pets:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
entry = ManifestEntry.from_dict(raw)
|
||||
if entry.slug and entry.spritesheet_url:
|
||||
entries.append(entry)
|
||||
|
||||
parsed = (ManifestEntry.from_dict(raw) for raw in pets if isinstance(raw, dict))
|
||||
entries = [entry for entry in parsed if entry.slug and entry.spritesheet_url]
|
||||
_cache = (time.monotonic(), entries)
|
||||
return entries
|
||||
|
||||
|
||||
+131
-296
@@ -1,19 +1,11 @@
|
||||
"""Decode a pet spritesheet and encode frames for a terminal.
|
||||
|
||||
Shared by the base CLI (writes the escape bytes to its own stdout) and the
|
||||
TUI (``tui_gateway`` ships the encoded bytes to Ink, which writes them) so the
|
||||
decode + capability-detection + protocol-encoding logic exists exactly once.
|
||||
|
||||
Supported output modes, in fidelity order:
|
||||
|
||||
- ``kitty`` — the kitty graphics protocol (kitty, Ghostty, WezTerm).
|
||||
- ``iterm`` — iTerm2 inline images (iTerm2, WezTerm).
|
||||
- ``sixel`` — DEC sixel (xterm -ti vt340, foot, mlterm, WezTerm, …).
|
||||
- ``unicode`` — 24-bit half-block downscale; works in any truecolor terminal.
|
||||
|
||||
Frame decoding requires Pillow (a core Hermes dependency). If Pillow or the
|
||||
spritesheet is unavailable the renderer degrades to ``unicode`` text or an
|
||||
empty string rather than raising.
|
||||
Shared by the base CLI (writes escape bytes to stdout) and the TUI (ships the
|
||||
encoded bytes to Ink) so decode + capability detection + protocol encoding
|
||||
exist once. Output modes, in fidelity order: ``kitty`` (kitty, Ghostty,
|
||||
WezTerm), ``iterm`` (iTerm2, WezTerm), ``sixel`` (xterm -ti vt340, foot,
|
||||
mlterm, …), ``unicode`` (24-bit half-blocks; any truecolor terminal). Missing
|
||||
Pillow or spritesheet degrades to an empty string rather than raising.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -41,78 +33,50 @@ logger = logging.getLogger(__name__)
|
||||
RENDER_MODES = ("auto", "kitty", "iterm", "sixel", "unicode", "off")
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
# Terminal capability detection
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
# ───────────────────────── terminal capability detection ─────────────────────────
|
||||
|
||||
|
||||
def _is_wezterm() -> bool:
|
||||
return os.environ.get("TERM_PROGRAM", "").lower() == "wezterm" or bool(os.environ.get("WEZTERM_PANE"))
|
||||
|
||||
|
||||
def detect_terminal_graphics() -> str:
|
||||
"""Best-effort detection of the richest graphics protocol available.
|
||||
"""Best-effort richest protocol from env vars only (never a DA1 query that could hang a pipe).
|
||||
|
||||
Env-based (non-blocking — we never issue a DA1/terminal query that could
|
||||
hang a pipe). Returns one of ``kitty`` / ``iterm`` / ``sixel`` /
|
||||
``unicode``. Conservative: unknown terminals get ``unicode``, which works
|
||||
anywhere with truecolor.
|
||||
Returns ``kitty`` / ``iterm`` / ``sixel`` / ``unicode``; unknown terminals get
|
||||
``unicode``, which works anywhere with truecolor.
|
||||
"""
|
||||
term = os.environ.get("TERM", "").lower()
|
||||
term_program = os.environ.get("TERM_PROGRAM", "").lower()
|
||||
|
||||
# The VS Code / Cursor integrated terminal sets TERM_PROGRAM=vscode
|
||||
# authoritatively but does NOT scrub the terminal env vars it inherits when
|
||||
# launched from another emulator (ITERM_SESSION_ID, KITTY_WINDOW_ID, …).
|
||||
# Trusting those leaks emits an image protocol the embedded xterm.js can't
|
||||
# display — you get a blank frame. Inline images there are opt-in
|
||||
# (terminal.integrated.enableImages), so default to half-blocks, which
|
||||
# always render in its truecolor grid. Users who enabled images can pin
|
||||
# display.pet.render_mode explicitly.
|
||||
# VS Code/Cursor set TERM_PROGRAM=vscode but don't scrub inherited
|
||||
# ITERM_SESSION_ID/KITTY_WINDOW_ID; trusting those emits a protocol xterm.js
|
||||
# can't show (blank frame). Inline images there are opt-in, so default to
|
||||
# half-blocks; users who enabled them can pin display.pet.render_mode.
|
||||
if term_program == "vscode":
|
||||
return "unicode"
|
||||
|
||||
# kitty graphics protocol
|
||||
if os.environ.get("KITTY_WINDOW_ID") or "kitty" in term or "ghostty" in term:
|
||||
if os.environ.get("KITTY_WINDOW_ID") or "kitty" in term or "ghostty" in term or term_program == "ghostty":
|
||||
return "kitty"
|
||||
if term_program in {"ghostty"}:
|
||||
if _is_wezterm(): # speaks kitty and iterm; kitty has richer placement
|
||||
return "kitty"
|
||||
|
||||
# WezTerm speaks both kitty and iterm; prefer kitty (richer placement).
|
||||
if term_program == "wezterm" or os.environ.get("WEZTERM_PANE"):
|
||||
return "kitty"
|
||||
|
||||
# iTerm2 inline images
|
||||
if term_program == "iterm.app" or os.environ.get("ITERM_SESSION_ID"):
|
||||
return "iterm"
|
||||
|
||||
# sixel-capable terminals (env heuristics only)
|
||||
if term_program in {"mintty"} or "foot" in term or "mlterm" in term:
|
||||
if term_program == "mintty" or "foot" in term or "mlterm" in term or "sixel" in term:
|
||||
return "sixel"
|
||||
if "sixel" in term:
|
||||
return "sixel"
|
||||
|
||||
return "unicode"
|
||||
|
||||
|
||||
def supports_kitty_placeholders() -> bool:
|
||||
"""True when the terminal can paint kitty Unicode placeholders (U+10EEEE).
|
||||
"""True when the terminal paints kitty Unicode placeholders (U+10EEEE).
|
||||
|
||||
Narrower than ``detect_terminal_graphics() == "kitty"``. WezTerm speaks
|
||||
kitty APC transmits but does not implement the placeholder grid, so those
|
||||
cells render as tofu. Ghostty and kitty do. VS Code already falls out of
|
||||
``detect_terminal_graphics`` as ``unicode``.
|
||||
Narrower than ``detect_terminal_graphics() == "kitty"``: WezTerm accepts
|
||||
kitty APC transmits but lacks the placeholder grid (cells render as tofu).
|
||||
"""
|
||||
if detect_terminal_graphics() != "kitty":
|
||||
return False
|
||||
term_program = os.environ.get("TERM_PROGRAM", "").lower()
|
||||
if term_program == "wezterm" or os.environ.get("WEZTERM_PANE"):
|
||||
return False
|
||||
return True
|
||||
return detect_terminal_graphics() == "kitty" and not _is_wezterm()
|
||||
|
||||
|
||||
def resolve_mode(configured: str | None, *, stream=None) -> str:
|
||||
"""Resolve the effective render mode from config + the environment.
|
||||
|
||||
``configured`` is ``display.pet.render_mode`` (``auto`` → detect). Returns
|
||||
``off`` when not attached to a TTY (no point emitting graphics into a pipe
|
||||
or logfile).
|
||||
"""
|
||||
"""Effective render mode from ``display.pet.render_mode`` + env; ``off`` when not a TTY."""
|
||||
mode = (configured or "auto").strip().lower()
|
||||
if mode not in RENDER_MODES:
|
||||
mode = "auto"
|
||||
@@ -126,56 +90,35 @@ def resolve_mode(configured: str | None, *, stream=None) -> str:
|
||||
except (ValueError, OSError):
|
||||
return "off"
|
||||
|
||||
if mode == "auto":
|
||||
return detect_terminal_graphics()
|
||||
return mode
|
||||
return detect_terminal_graphics() if mode == "auto" else mode
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
# Frame decoding
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
# ───────────────────────── frame decoding ─────────────────────────
|
||||
|
||||
def _open_sheet(path: Path):
|
||||
from PIL import Image
|
||||
|
||||
img = Image.open(path)
|
||||
return img.convert("RGBA")
|
||||
|
||||
|
||||
# Max alpha at/below which a frame counts as blank padding. petdex sheets are
|
||||
# left-packed: a state with fewer real frames than ``FRAMES_PER_STATE`` fills
|
||||
# the trailing columns with fully transparent cells. Animating into one flashes
|
||||
# the pet blank, so we stop the row at the first such gap.
|
||||
# Max alpha at/below which a frame is blank padding. petdex sheets are
|
||||
# left-packed, so a state with fewer real frames than FRAMES_PER_STATE has
|
||||
# fully transparent trailing cells; animating into one flashes the pet blank.
|
||||
_BLANK_ALPHA = 8
|
||||
|
||||
|
||||
def _frame_is_blank(frame) -> bool:
|
||||
"""True if *frame* has no meaningfully opaque pixel (transparent padding)."""
|
||||
return frame.getchannel("A").getextrema()[1] <= _BLANK_ALPHA
|
||||
|
||||
|
||||
@lru_cache(maxsize=16)
|
||||
def _raw_frames(
|
||||
sheet_path: str,
|
||||
state_value: str,
|
||||
frame_w: int,
|
||||
frame_h: int,
|
||||
frames_per_state: int,
|
||||
) -> tuple:
|
||||
"""Cropped, padding-trimmed RGBA frames for one state row (unscaled).
|
||||
def _raw_frames(sheet_path: str, state_value: str, frame_w: int, frame_h: int, frames_per_state: int) -> tuple:
|
||||
"""Cropped RGBA frames for one state row, stopping at the first blank column.
|
||||
|
||||
Steps across the row until the first blank column so pets with ragged
|
||||
per-state frame counts never animate into empty padding. Cached; returns
|
||||
``()`` on any decode failure.
|
||||
Cached; returns ``()`` on any decode failure.
|
||||
"""
|
||||
try:
|
||||
sheet = _open_sheet(Path(sheet_path))
|
||||
from PIL import Image
|
||||
|
||||
sheet = Image.open(Path(sheet_path)).convert("RGBA")
|
||||
cols = max(1, sheet.width // frame_w)
|
||||
rows = max(1, sheet.height // frame_h)
|
||||
row = state_row_index(state_value, rows)
|
||||
top = row * frame_h
|
||||
# Clamp the row to the sheet (some pets ship fewer rows than the 8 the
|
||||
# taxonomy reserves).
|
||||
top = state_row_index(state_value, rows) * frame_h
|
||||
# Clamp to the sheet: some pets ship fewer rows than the taxonomy reserves.
|
||||
if top + frame_h > sheet.height:
|
||||
top = max(0, sheet.height - frame_h)
|
||||
|
||||
@@ -184,7 +127,7 @@ def _raw_frames(
|
||||
left = i * frame_w
|
||||
frame = sheet.crop((left, top, left + frame_w, top + frame_h))
|
||||
if _frame_is_blank(frame):
|
||||
break # trailing transparent padding — real frames end here
|
||||
break
|
||||
frames.append(frame)
|
||||
return tuple(frames)
|
||||
except Exception as exc: # noqa: BLE001 - cosmetic feature, never fatal
|
||||
@@ -202,11 +145,7 @@ def _frames_for(
|
||||
scale_w: int,
|
||||
scale_h: int,
|
||||
):
|
||||
"""Return padding-trimmed RGBA frames for one state row, scaled.
|
||||
|
||||
Thin scaling layer over :func:`_raw_frames`; both are cached so repeated
|
||||
frame requests during animation are free.
|
||||
"""
|
||||
"""Scaled :func:`_raw_frames` (both cached, so animation-time requests are free)."""
|
||||
raw = _raw_frames(sheet_path, state_value, frame_w, frame_h, frames_per_state)
|
||||
if not raw or (scale_w, scale_h) == (frame_w, frame_h):
|
||||
return list(raw)
|
||||
@@ -222,137 +161,97 @@ def state_frame_counts(
|
||||
frame_h: int = FRAME_H,
|
||||
frames_per_state: int = FRAMES_PER_STATE,
|
||||
) -> dict[str, int]:
|
||||
"""Map each driven :class:`PetState` → its real (padding-trimmed) frame count.
|
||||
"""Each driven :class:`PetState` → its real (padding-trimmed) frame count.
|
||||
|
||||
The single source of truth for "how many frames does this state actually
|
||||
have?". The CLI/TUI consume the trimmed frame lists directly; the gateway
|
||||
ships this map to the desktop canvas, which steps its own loop.
|
||||
The gateway ships this map to the desktop canvas, which steps its own loop.
|
||||
"""
|
||||
return {
|
||||
state.value: len(
|
||||
_raw_frames(str(sheet_path), state.value, frame_w, frame_h, frames_per_state)
|
||||
)
|
||||
state.value: len(_raw_frames(str(sheet_path), state.value, frame_w, frame_h, frames_per_state))
|
||||
for state in PetState
|
||||
}
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
# Encoders
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
# ───────────────────────── encoders ─────────────────────────
|
||||
|
||||
def _png_bytes(frame) -> bytes:
|
||||
|
||||
def _png_b64(frame) -> str:
|
||||
buf = io.BytesIO()
|
||||
frame.save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
return base64.standard_b64encode(buf.getvalue()).decode("ascii")
|
||||
|
||||
|
||||
def _union_alpha_bbox(frames) -> tuple[int, int, int, int] | None:
|
||||
"""Union opaque-pixel bbox across *frames* (a stable trim for animation)."""
|
||||
left = top = right = bottom = None
|
||||
def _crop_frames_to_alpha_union(frames):
|
||||
"""Crop every frame to the union opaque bbox (a stable trim across the animation).
|
||||
|
||||
kitty paints the whole transmitted rectangle, transparent margins included,
|
||||
so an untrimmed pet looks small and adrift inside its cell box.
|
||||
"""
|
||||
boxes = []
|
||||
for frame in frames:
|
||||
try:
|
||||
bbox = frame.getchannel("A").getbbox()
|
||||
except Exception: # noqa: BLE001 - cosmetic; fail open
|
||||
bbox = None
|
||||
if not bbox:
|
||||
continue
|
||||
l, t, r, b = bbox
|
||||
left = l if left is None else min(left, l)
|
||||
top = t if top is None else min(top, t)
|
||||
right = r if right is None else max(right, r)
|
||||
bottom = b if bottom is None else max(bottom, b)
|
||||
if left is None or top is None or right is None or bottom is None:
|
||||
return None
|
||||
return (left, top, right, bottom)
|
||||
|
||||
|
||||
def _crop_frames_to_alpha_union(frames):
|
||||
"""Crop every frame to the union opaque bbox so the sprite hugs its box.
|
||||
|
||||
kitty paints the whole transmitted rectangle, transparent margins included,
|
||||
which makes the visible pet look small and adrift inside a larger cell box.
|
||||
Trimming to the visible bounds keeps the pet tight in its corner.
|
||||
"""
|
||||
bbox = _union_alpha_bbox(frames)
|
||||
if not bbox:
|
||||
if bbox:
|
||||
boxes.append(bbox)
|
||||
if not boxes:
|
||||
return frames
|
||||
return [f.crop(bbox) for f in frames]
|
||||
union = (min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes))
|
||||
return [f.crop(union) for f in frames]
|
||||
|
||||
|
||||
# Nominal terminal cell size in pixels. kitty fits an image to its cell
|
||||
# rectangle preserving aspect, so a frame whose pixel size isn't a whole
|
||||
# multiple of the cell rounds up — which makes the terminal clip the bottom row
|
||||
# (the "clipped feet") and letterbox a blank row. Snapping each frame to an
|
||||
# exact cell multiple avoids that. (See ratatui-image #57: "render in multiples
|
||||
# of the font-size, to avoid stale character artifacts.")
|
||||
# rectangle preserving aspect, so a frame that isn't a whole cell multiple
|
||||
# rounds up, clipping the bottom row ("clipped feet") and letterboxing a blank
|
||||
# row. Snapping to an exact multiple avoids that (cf. ratatui-image #57).
|
||||
_CELL_W = 8
|
||||
_CELL_H = 16
|
||||
|
||||
|
||||
def _snap_frames_to_cell_grid(frames):
|
||||
"""Resize frames so width/height are exact multiples of the cell box.
|
||||
|
||||
Removes the sub-cell remainder kitty would otherwise round up + clip. All
|
||||
frames share the union-cropped size, so they snap to the same cell grid.
|
||||
"""
|
||||
"""Resize frames so width/height are exact multiples of the cell box (all frames share the union-cropped size)."""
|
||||
if not frames:
|
||||
return frames
|
||||
from PIL import Image
|
||||
|
||||
w, h = frames[0].size
|
||||
cols = max(1, round(w / _CELL_W))
|
||||
rows = max(1, round(h / _CELL_H))
|
||||
target = (cols * _CELL_W, rows * _CELL_H)
|
||||
target = (max(1, round(w / _CELL_W)) * _CELL_W, max(1, round(h / _CELL_H)) * _CELL_H)
|
||||
if (w, h) == target:
|
||||
return frames
|
||||
return [f.resize(target, Image.LANCZOS) for f in frames]
|
||||
|
||||
|
||||
def _kitty_apc(ctrl: str, data: str) -> str:
|
||||
"""Emit a kitty APC escape for *data*, chunked into ≤4096-byte ``m`` pieces."""
|
||||
chunk = 4096
|
||||
if len(data) <= chunk:
|
||||
return f"\x1b_G{ctrl},m=0;{data}\x1b\\"
|
||||
out = [f"\x1b_G{ctrl},m=1;{data[:chunk]}\x1b\\"]
|
||||
rest = data[chunk:]
|
||||
while rest:
|
||||
piece, rest = rest[:chunk], rest[chunk:]
|
||||
out.append(f"\x1b_Gm={1 if rest else 0};{piece}\x1b\\")
|
||||
return "".join(out)
|
||||
"""kitty APC escape for *data*, chunked into ≤4096-byte ``m`` pieces."""
|
||||
pieces = [data[i : i + 4096] for i in range(0, len(data), 4096)] or [""]
|
||||
last = len(pieces) - 1
|
||||
return "".join(
|
||||
f"\x1b_G{ctrl + ',' if i == 0 else ''}m={0 if i == last else 1};{piece}\x1b\\" for i, piece in enumerate(pieces)
|
||||
)
|
||||
|
||||
|
||||
def _encode_kitty(frame, *, cell_cols: int | None = None, cell_rows: int | None = None) -> str:
|
||||
"""Encode one frame via the kitty graphics protocol (transmit + display).
|
||||
|
||||
``a=T`` transmits & displays at the cursor; ``c``/``r`` request a display
|
||||
box in terminal cells so successive frames overwrite the same area.
|
||||
"""
|
||||
"""kitty transmit+display at the cursor; ``c``/``r`` pin the cell box so frames overwrite each other."""
|
||||
ctrl = "f=100,a=T,q=2"
|
||||
if cell_cols:
|
||||
ctrl += f",c={cell_cols}"
|
||||
if cell_rows:
|
||||
ctrl += f",r={cell_rows}"
|
||||
return _kitty_apc(ctrl, base64.standard_b64encode(_png_bytes(frame)).decode("ascii"))
|
||||
return _kitty_apc(ctrl, _png_b64(frame))
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
# kitty Unicode placeholders
|
||||
#
|
||||
# Ink (the TUI's React-for-terminal layer) owns the screen and measures every
|
||||
# cell's width, so it can't host raw kitty image escapes (no width to count,
|
||||
# clobbered on the next repaint). kitty's *Unicode placeholder* protocol is the
|
||||
# grid-safe path: transmit the image once (q=2, virtual placement U=1), then the
|
||||
# host app prints ordinary-width placeholder cells (U+10EEEE + diacritics) whose
|
||||
# foreground color encodes the image id. Ink counts those as width-1 text, so
|
||||
# layout stays correct and the terminal paints the image underneath.
|
||||
# ───────────────────────── kitty Unicode placeholders ─────────────────────────
|
||||
# Ink owns the screen and measures every cell's width, so it can't host raw
|
||||
# kitty image escapes. The placeholder protocol is the grid-safe path: transmit
|
||||
# once as a virtual placement (U=1), then print ordinary-width placeholder cells
|
||||
# (U+10EEEE + diacritics) whose foreground color encodes the image id; Ink counts
|
||||
# them as width-1 text and the terminal paints the image underneath.
|
||||
# https://sw.kovidgoyal.net/kitty/graphics-protocol/#unicode-placeholders
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
_KITTY_PLACEHOLDER = "\U0010eeee"
|
||||
|
||||
# Row/column diacritics, in order (index → diacritic). Verbatim from kitty's
|
||||
# gen/rowcolumn-diacritics.txt (Unicode 6.0.0, combining class 230). Index i is
|
||||
# the diacritic that encodes the number i; we only ever need the row index.
|
||||
# Row/column diacritics, index → diacritic, verbatim from kitty's
|
||||
# gen/rowcolumn-diacritics.txt. We only ever need the row index.
|
||||
_ROWCOL_DIACRITICS: tuple[int, ...] = (
|
||||
0x0305, 0x030D, 0x030E, 0x0310, 0x0312, 0x033D, 0x033E, 0x033F, 0x0346, 0x034A,
|
||||
0x034B, 0x034C, 0x0350, 0x0351, 0x0352, 0x0357, 0x035B, 0x0363, 0x0364, 0x0365,
|
||||
@@ -388,13 +287,7 @@ _ROWCOL_DIACRITICS: tuple[int, ...] = (
|
||||
|
||||
|
||||
def kitty_image_id(slug: str) -> int:
|
||||
"""Stable per-pet image id in ``[1, 0x7FFF]``.
|
||||
|
||||
The id is encoded in the placeholder's 24-bit foreground color, so it must
|
||||
be non-zero and fit comfortably under ``0xFFFFFF``. A small CRC keeps it
|
||||
deterministic per slug (so re-renders reuse the same terminal-side image)
|
||||
while making collisions between two different pets unlikely.
|
||||
"""
|
||||
"""Deterministic per-slug image id in ``[1, 0x7FFF]`` (non-zero; encoded in the placeholder fg color) so re-renders reuse the terminal-side image."""
|
||||
import zlib
|
||||
|
||||
return (zlib.crc32(slug.encode("utf-8")) % 0x7FFE) + 1
|
||||
@@ -406,40 +299,30 @@ def kitty_color_hex(image_id: int) -> str:
|
||||
|
||||
|
||||
def kitty_placeholder_rows(cols: int, rows: int) -> list[str]:
|
||||
"""Build the placeholder text grid for an *rows*×*cols* image.
|
||||
"""Placeholder text grid: first cell carries the row diacritic, the rest auto-increment the column.
|
||||
|
||||
Each line is one row of the grid: the first cell carries the row diacritic
|
||||
(column defaults to 0), and the remaining ``cols-1`` bare placeholders let
|
||||
the terminal auto-increment the column. The foreground color (the image id)
|
||||
is applied by the caller / Ink, not embedded here.
|
||||
The foreground color (image id) is applied by the caller / Ink, not here.
|
||||
"""
|
||||
cols = max(1, cols)
|
||||
out: list[str] = []
|
||||
for r in range(max(1, rows)):
|
||||
idx = min(r, len(_ROWCOL_DIACRITICS) - 1)
|
||||
first = _KITTY_PLACEHOLDER + chr(_ROWCOL_DIACRITICS[idx])
|
||||
out.append(first + _KITTY_PLACEHOLDER * (cols - 1))
|
||||
out.append(_KITTY_PLACEHOLDER + chr(_ROWCOL_DIACRITICS[idx]) + _KITTY_PLACEHOLDER * (cols - 1))
|
||||
return out
|
||||
|
||||
|
||||
def _encode_kitty_virtual(frame, *, image_id: int, cols: int, rows: int) -> str:
|
||||
"""Transmit a frame as a kitty *virtual* placement for Unicode placeholders.
|
||||
"""Transmit a frame as a kitty virtual placement (``U=1``; ``q=2`` mutes replies that would corrupt Ink's output).
|
||||
|
||||
``a=T`` transmits and creates the placement in one shot; ``U=1`` marks it
|
||||
virtual (no on-screen output, cursor untouched); ``q=2`` suppresses the
|
||||
terminal's OK/error replies that would otherwise corrupt the host app's
|
||||
output. Re-sending with the same ``i`` replaces the image, so the static
|
||||
placeholder cells animate underneath.
|
||||
Re-sending with the same ``i`` replaces the image, so static placeholder cells animate underneath.
|
||||
"""
|
||||
ctrl = f"a=T,U=1,i={image_id},c={cols},r={rows},f=100,q=2"
|
||||
return _kitty_apc(ctrl, base64.standard_b64encode(_png_bytes(frame)).decode("ascii"))
|
||||
return _kitty_apc(f"a=T,U=1,i={image_id},c={cols},r={rows},f=100,q=2", _png_b64(frame))
|
||||
|
||||
|
||||
def _encode_iterm(frame, *, cell_cols: int | None = None, cell_rows: int | None = None) -> str:
|
||||
"""Encode one frame as an iTerm2 inline image (OSC 1337 File)."""
|
||||
payload = base64.standard_b64encode(_png_bytes(frame)).decode("ascii")
|
||||
size = len(payload)
|
||||
args = ["inline=1", f"size={size}", "preserveAspectRatio=1"]
|
||||
"""iTerm2 inline image (OSC 1337 File)."""
|
||||
payload = _png_b64(frame)
|
||||
args = ["inline=1", f"size={len(payload)}", "preserveAspectRatio=1"]
|
||||
if cell_cols:
|
||||
args.append(f"width={cell_cols}")
|
||||
if cell_rows:
|
||||
@@ -448,32 +331,24 @@ def _encode_iterm(frame, *, cell_cols: int | None = None, cell_rows: int | None
|
||||
|
||||
|
||||
def _encode_sixel(frame) -> str:
|
||||
"""Encode one frame as DEC sixel.
|
||||
"""DEC sixel via a compact hand-rolled encoder (Pillow has no sixel writer).
|
||||
|
||||
Quantizes to an adaptive palette (≤255 colors) and emits the sixel band
|
||||
stream. Pillow has no sixel writer, so this is a compact hand-rolled
|
||||
encoder. Transparent pixels render as background (color register skipped).
|
||||
Quantizes to ≤255 adaptive colors; transparent pixels are skipped (render as background).
|
||||
"""
|
||||
from PIL import Image
|
||||
|
||||
rgba = frame
|
||||
# Composite onto transparent-as-skip: track alpha to decide background.
|
||||
pal = rgba.convert("RGB").quantize(colors=255, method=Image.MEDIANCUT)
|
||||
pal = frame.convert("RGB").quantize(colors=255, method=Image.MEDIANCUT)
|
||||
palette = pal.getpalette() or []
|
||||
px = pal.load()
|
||||
alpha = rgba.getchannel("A").load()
|
||||
alpha = frame.getchannel("A").load()
|
||||
w, h = pal.size
|
||||
|
||||
out = ["\x1bP0;1;0q", '"1;1;%d;%d' % (w, h)]
|
||||
# Color register definitions (sixel uses 0..100 scale).
|
||||
used = sorted({px[x, y] for y in range(h) for x in range(w)})
|
||||
for idx in used:
|
||||
r = palette[idx * 3] if idx * 3 < len(palette) else 0
|
||||
g = palette[idx * 3 + 1] if idx * 3 + 1 < len(palette) else 0
|
||||
b = palette[idx * 3 + 2] if idx * 3 + 2 < len(palette) else 0
|
||||
for idx in used: # color registers on a 0..100 scale
|
||||
r, g, b = (palette[idx * 3 + c] if idx * 3 + c < len(palette) else 0 for c in range(3))
|
||||
out.append("#%d;2;%d;%d;%d" % (idx, r * 100 // 255, g * 100 // 255, b * 100 // 255))
|
||||
|
||||
# Emit in 6-row bands.
|
||||
for band in range(0, h, 6):
|
||||
for color_idx in used:
|
||||
line = ["#%d" % color_idx]
|
||||
@@ -484,10 +359,7 @@ def _encode_sixel(frame) -> str:
|
||||
nonlocal run_char, run_len
|
||||
if run_char is None:
|
||||
return
|
||||
if run_len > 3:
|
||||
line.append("!%d%s" % (run_len, run_char))
|
||||
else:
|
||||
line.append(run_char * run_len)
|
||||
line.append("!%d%s" % (run_len, run_char) if run_len > 3 else run_char * run_len)
|
||||
run_char, run_len = None, 0
|
||||
|
||||
for x in range(w):
|
||||
@@ -516,11 +388,9 @@ Cell = tuple[tuple[int, int, int, int], tuple[int, int, int, int]]
|
||||
|
||||
|
||||
def _downscale_cells(frame, *, target_cols: int) -> list[list[Cell]]:
|
||||
"""Downscale a frame to a grid of half-block cells.
|
||||
"""Downscale a frame to rows of half-block cells (one terminal row = two pixel rows).
|
||||
|
||||
Each cell pairs a top and bottom pixel so one terminal row encodes two
|
||||
pixel rows. Returns rows of ``((tr,tg,tb,ta),(br,bg,bb,ba))`` — the
|
||||
framework-neutral representation shared by the ANSI encoder (CLI) and the
|
||||
Framework-neutral representation shared by the ANSI encoder (CLI) and the
|
||||
structured ``cells`` API (Ink).
|
||||
"""
|
||||
from PIL import Image
|
||||
@@ -528,43 +398,33 @@ def _downscale_cells(frame, *, target_cols: int) -> list[list[Cell]]:
|
||||
target_cols = max(4, target_cols)
|
||||
aspect = frame.height / max(1, frame.width)
|
||||
target_rows = max(2, int(round(target_cols * aspect * 0.5)) * 2)
|
||||
small = frame.resize((target_cols, target_rows), Image.LANCZOS).convert("RGBA")
|
||||
px = small.load()
|
||||
|
||||
grid: list[list[Cell]] = []
|
||||
for y in range(0, target_rows, 2):
|
||||
row: list[Cell] = []
|
||||
for x in range(target_cols):
|
||||
top = px[x, y]
|
||||
bottom = px[x, y + 1] if y + 1 < target_rows else (0, 0, 0, 0)
|
||||
row.append((top, bottom))
|
||||
grid.append(row)
|
||||
return grid
|
||||
px = frame.resize((target_cols, target_rows), Image.LANCZOS).convert("RGBA").load()
|
||||
return [
|
||||
[(px[x, y], px[x, y + 1] if y + 1 < target_rows else (0, 0, 0, 0)) for x in range(target_cols)]
|
||||
for y in range(0, target_rows, 2)
|
||||
]
|
||||
|
||||
|
||||
def _encode_unicode(frame, *, target_cols: int) -> str:
|
||||
"""Downscale to truecolor ANSI half-blocks (one char = 2 vertical pixels)."""
|
||||
"""Truecolor ANSI half-blocks (one char = 2 vertical pixels)."""
|
||||
lines: list[str] = []
|
||||
for row in _downscale_cells(frame, target_cols=target_cols):
|
||||
cells: list[str] = []
|
||||
for (tr, tg, tb, ta), (br, bg, bb, ba) in row:
|
||||
if ta < 32 and ba < 32:
|
||||
cells.append("\x1b[0m ") # fully transparent → blank
|
||||
continue
|
||||
cells.append(f"\x1b[38;2;{tr};{tg};{tb}m\x1b[48;2;{br};{bg};{bb}m{_HALF_BLOCK}")
|
||||
cells = [
|
||||
"\x1b[0m " if ta < 32 and ba < 32 else f"\x1b[38;2;{tr};{tg};{tb}m\x1b[48;2;{br};{bg};{bb}m{_HALF_BLOCK}"
|
||||
for (tr, tg, tb, ta), (br, bg, bb, ba) in row
|
||||
]
|
||||
lines.append("".join(cells) + "\x1b[0m")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
# Public renderer
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
# ───────────────────────── public renderer ─────────────────────────
|
||||
|
||||
|
||||
class PetRenderer:
|
||||
"""Holds a pet's spritesheet and yields encoded frames per (state, index).
|
||||
|
||||
Construct once per pet, then call :meth:`frame` on an animation timer.
|
||||
Cheap to call repeatedly — decoded frames are cached.
|
||||
Construct once per pet, then call :meth:`frame` on an animation timer;
|
||||
decoded frames are cached so repeated calls are cheap.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -594,71 +454,51 @@ class PetRenderer:
|
||||
return len(self._frames(state))
|
||||
|
||||
def _frames(self, state: PetState | str):
|
||||
value = state.value if isinstance(state, PetState) else str(state)
|
||||
scale_w = max(1, int(self.frame_w * self.scale))
|
||||
scale_h = max(1, int(self.frame_h * self.scale))
|
||||
return _frames_for(
|
||||
self.spritesheet,
|
||||
value,
|
||||
state.value if isinstance(state, PetState) else str(state),
|
||||
self.frame_w,
|
||||
self.frame_h,
|
||||
self.frames_per_state,
|
||||
scale_w,
|
||||
scale_h,
|
||||
max(1, int(self.frame_w * self.scale)),
|
||||
max(1, int(self.frame_h * self.scale)),
|
||||
)
|
||||
|
||||
def cells(self, state: PetState | str, index: int, *, cols: int | None = None) -> list[list[Cell]]:
|
||||
"""Return one frame as a half-block cell grid (framework-neutral).
|
||||
|
||||
Used by the TUI, which renders the grid with native Ink color props
|
||||
instead of raw ANSI. Returns ``[]`` when no frame is available.
|
||||
"""
|
||||
"""One frame as a half-block cell grid for Ink's native color props; ``[]`` when unavailable."""
|
||||
frames = self._frames(state)
|
||||
if not frames:
|
||||
return []
|
||||
frame = frames[index % len(frames)]
|
||||
return _downscale_cells(frame, target_cols=cols or self.unicode_cols)
|
||||
return _downscale_cells(frames[index % len(frames)], target_cols=cols or self.unicode_cols)
|
||||
|
||||
def _cell_box(self, frame) -> tuple[int, int]:
|
||||
"""Terminal cell box for a scaled frame (~8×16 px per cell).
|
||||
"""Terminal cell box (~8×16 px per cell) for a scaled frame.
|
||||
|
||||
Must match :meth:`frame` graphics sizing — kitty stretches the image to
|
||||
fill ``c``×``r`` cells, so these must reflect the scaled pixel
|
||||
dimensions, not a native-aspect column count (that upscales small pets).
|
||||
kitty stretches the image to fill ``c``×``r`` cells, so this must track
|
||||
the scaled pixel size, not a native-aspect column count (that upscales small pets).
|
||||
"""
|
||||
return max(1, frame.width // 8), max(1, frame.height // 16)
|
||||
|
||||
def kitty_payload(self, state: PetState | str, *, image_id: int) -> dict | None:
|
||||
"""Build the kitty Unicode-placeholder payload for one state.
|
||||
"""kitty Unicode-placeholder payload ``{cols, rows, placeholder, frames}`` for one state.
|
||||
|
||||
Returns ``{cols, rows, placeholder, frames}`` where ``frames`` is a
|
||||
list of transmit escapes (one per animation frame, all reusing
|
||||
``image_id``) and ``placeholder`` is the static text grid Ink paints.
|
||||
Placement geometry is derived from the scaled frame pixels (via
|
||||
:meth:`_cell_box`), not ``unicode_cols`` — kitty upscales to fill
|
||||
``c``×``r`` cells. ``None`` when no frame is available.
|
||||
``frames`` are transmit escapes (all reusing ``image_id``); ``placeholder``
|
||||
is the static text grid Ink paints. ``None`` when no frame is available.
|
||||
"""
|
||||
frames = self._frames(state)
|
||||
if not frames:
|
||||
return None
|
||||
frames = _crop_frames_to_alpha_union(frames)
|
||||
frames = _snap_frames_to_cell_grid(frames)
|
||||
frames = _snap_frames_to_cell_grid(_crop_frames_to_alpha_union(frames))
|
||||
cols, rows = self._cell_box(frames[0])
|
||||
return {
|
||||
"cols": cols,
|
||||
"rows": rows,
|
||||
"placeholder": kitty_placeholder_rows(cols, rows),
|
||||
"frames": [
|
||||
_encode_kitty_virtual(f, image_id=image_id, cols=cols, rows=rows) for f in frames
|
||||
],
|
||||
"frames": [_encode_kitty_virtual(f, image_id=image_id, cols=cols, rows=rows) for f in frames],
|
||||
}
|
||||
|
||||
def frame(self, state: PetState | str, index: int) -> str:
|
||||
"""Return the encoded escape string for one frame, or ``""``.
|
||||
|
||||
``index`` is taken modulo the available frame count so callers can pass
|
||||
a free-running counter.
|
||||
"""
|
||||
"""Encoded escape string for one frame (``index`` taken modulo the frame count), or ``""``."""
|
||||
if self.mode == "off":
|
||||
return ""
|
||||
frames = self._frames(state)
|
||||
@@ -688,11 +528,6 @@ def build_renderer(
|
||||
unicode_cols: int = 20,
|
||||
stream=None,
|
||||
) -> PetRenderer:
|
||||
"""Convenience factory: resolve the mode from config+env, then construct."""
|
||||
"""Resolve the mode from config+env, then construct a :class:`PetRenderer`."""
|
||||
mode = resolve_mode(configured_mode, stream=stream)
|
||||
return PetRenderer(
|
||||
spritesheet,
|
||||
mode=mode,
|
||||
scale=scale,
|
||||
unicode_cols=unicode_cols,
|
||||
)
|
||||
return PetRenderer(spritesheet, mode=mode, scale=scale, unicode_cols=unicode_cols)
|
||||
|
||||
+10
-15
@@ -64,18 +64,13 @@ def derive_pet_state(
|
||||
7. ``busy`` → ``RUN`` (turn in flight, unspecified work)
|
||||
8. otherwise → ``IDLE``
|
||||
"""
|
||||
if error:
|
||||
return PetState.FAILED
|
||||
if celebrate:
|
||||
return PetState.JUMP
|
||||
if just_completed:
|
||||
return PetState.WAVE
|
||||
if awaiting_input:
|
||||
return PetState.WAITING
|
||||
if tool_running:
|
||||
return PetState.RUN
|
||||
if reasoning:
|
||||
return PetState.REVIEW
|
||||
if busy:
|
||||
return PetState.RUN
|
||||
return PetState.IDLE
|
||||
ranked = (
|
||||
(error, PetState.FAILED),
|
||||
(celebrate, PetState.JUMP),
|
||||
(just_completed, PetState.WAVE),
|
||||
(awaiting_input, PetState.WAITING),
|
||||
(tool_running, PetState.RUN),
|
||||
(reasoning, PetState.REVIEW),
|
||||
(busy, PetState.RUN),
|
||||
)
|
||||
return next((state for flag, state in ranked if flag), PetState.IDLE)
|
||||
|
||||
+79
-138
@@ -1,17 +1,10 @@
|
||||
"""On-disk pet store — install / list / resolve pets.
|
||||
|
||||
Pets live under ``get_hermes_home()/pets/<slug>/`` so every profile gets its
|
||||
own set (we deliberately do **not** reuse petdex's ``~/.codex/pets`` default —
|
||||
that's owned by the petdex npm CLI and isn't profile-aware). Each installed
|
||||
pet directory holds:
|
||||
|
||||
pets/<slug>/
|
||||
pet.json # {id, displayName, description, spritesheetPath}
|
||||
spritesheet.webp # (or .png)
|
||||
|
||||
The active pet is resolved from the caller-supplied ``display.pet.slug`` config
|
||||
value (falling back to the first installed pet), so this module stays free of
|
||||
the config loader.
|
||||
Pets live under ``get_hermes_home()/pets/<slug>/`` (profile-scoped; we do NOT
|
||||
reuse petdex's ``~/.codex/pets``, which the petdex CLI owns). Each pet dir holds
|
||||
``pet.json`` ({id, displayName, description, spritesheetPath}) plus
|
||||
``spritesheet.webp`` (or .png). The active pet is resolved from the
|
||||
caller-supplied ``display.pet.slug`` so this module stays free of the config loader.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -27,6 +20,7 @@ from hermes_constants import get_hermes_home
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_DOWNLOAD_TIMEOUT = 60.0
|
||||
_HTTP_HEADERS = {"User-Agent": "hermes-agent-petdex"}
|
||||
|
||||
|
||||
class PetStoreError(RuntimeError):
|
||||
@@ -60,6 +54,13 @@ def pets_dir() -> Path:
|
||||
return path
|
||||
|
||||
|
||||
def _thumb_path(slug: str) -> Path:
|
||||
"""Cached thumbnail for *slug* (lives OUTSIDE the pet dir, under ``pets/.thumbs/``)."""
|
||||
path = pets_dir() / ".thumbs"
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path / f"{slug}.png"
|
||||
|
||||
|
||||
def _read_pet_json(directory: Path) -> dict:
|
||||
pet_json = directory / "pet.json"
|
||||
if not pet_json.is_file():
|
||||
@@ -71,37 +72,28 @@ def _read_pet_json(directory: Path) -> dict:
|
||||
return {}
|
||||
|
||||
|
||||
def _resolve_spritesheet(directory: Path, meta: dict) -> Path:
|
||||
"""Find the spritesheet for a pet dir.
|
||||
def _write_pet_json(directory: Path, meta: dict) -> None:
|
||||
(directory / "pet.json").write_text(json.dumps(meta, indent=2), encoding="utf-8")
|
||||
|
||||
Honors ``spritesheetPath`` from pet.json, else probes the conventional
|
||||
filenames (``spritesheet.{webp,png}`` and petdex R2's ``sprite.webp``).
|
||||
"""
|
||||
|
||||
def _resolve_spritesheet(directory: Path, meta: dict) -> Path:
|
||||
"""Honor ``spritesheetPath``, else probe conventional names (incl. petdex R2's ``sprite.webp``)."""
|
||||
declared = str(meta.get("spritesheetPath", "") or "").strip()
|
||||
if declared:
|
||||
candidate = directory / declared
|
||||
if candidate.is_file():
|
||||
return candidate
|
||||
for name in ("spritesheet.webp", "spritesheet.png", "sprite.webp", "sprite.png"):
|
||||
for name in ([declared] if declared else []) + ["spritesheet.webp", "spritesheet.png", "sprite.webp", "sprite.png"]:
|
||||
candidate = directory / name
|
||||
if candidate.is_file():
|
||||
return candidate
|
||||
# Default expectation even if missing, so callers get a stable path.
|
||||
return directory / "spritesheet.webp"
|
||||
return directory / "spritesheet.webp" # stable default even when missing
|
||||
|
||||
|
||||
def _safe_slug(slug: str) -> str:
|
||||
"""Normalize a slug to a single bare path segment.
|
||||
|
||||
Pet slugs index into ``pets_dir()/<slug>/`` for load/remove, so a value
|
||||
carrying path separators (``../``, absolute paths) could escape the pets
|
||||
directory. Strip every separator and reject ``.``/``..`` so callers can
|
||||
only ever name a direct child of the pets directory.
|
||||
Slugs index ``pets_dir()/<slug>/`` for load/remove, so separators (``../``,
|
||||
absolute paths) must not escape the pets directory; ``.``/``..`` are rejected.
|
||||
"""
|
||||
segment = Path(str(slug).strip()).name
|
||||
if segment in ("", ".", ".."):
|
||||
return ""
|
||||
return segment
|
||||
return "" if segment in ("", ".", "..") else segment
|
||||
|
||||
|
||||
def load_pet(slug: str) -> InstalledPet | None:
|
||||
@@ -123,6 +115,13 @@ def load_pet(slug: str) -> InstalledPet | None:
|
||||
)
|
||||
|
||||
|
||||
def _loaded_pet_or_raise(slug: str, error: str) -> InstalledPet:
|
||||
pet = load_pet(slug)
|
||||
if pet is None or not pet.exists:
|
||||
raise PetStoreError(error)
|
||||
return pet
|
||||
|
||||
|
||||
def installed_pets() -> list[InstalledPet]:
|
||||
"""Return every installed pet (dirs containing a usable spritesheet)."""
|
||||
out: list[InstalledPet] = []
|
||||
@@ -136,11 +135,7 @@ def installed_pets() -> list[InstalledPet]:
|
||||
|
||||
|
||||
def resolve_active_pet(configured_slug: str | None = None) -> InstalledPet | None:
|
||||
"""Resolve which pet to display.
|
||||
|
||||
Precedence: the configured slug (``display.pet.slug``) if it's installed,
|
||||
otherwise the first installed pet alphabetically, otherwise ``None``.
|
||||
"""
|
||||
"""The configured slug (``display.pet.slug``) if installed, else the first pet alphabetically."""
|
||||
if configured_slug:
|
||||
pet = load_pet(configured_slug.strip())
|
||||
if pet and pet.exists:
|
||||
@@ -152,9 +147,8 @@ def resolve_active_pet(configured_slug: str | None = None) -> InstalledPet | Non
|
||||
def install_pet(slug: str, *, force: bool = False, timeout: float = _DOWNLOAD_TIMEOUT) -> InstalledPet:
|
||||
"""Download *slug* from the manifest into the pets directory.
|
||||
|
||||
Idempotent: a fully-installed pet is returned as-is unless *force*. Raises
|
||||
:class:`PetStoreError` / :class:`~agent.pet.manifest.ManifestError` on
|
||||
failure.
|
||||
Idempotent: a fully-installed pet is returned as-is unless *force*. Raises
|
||||
:class:`PetStoreError` / :class:`~agent.pet.manifest.ManifestError` on failure.
|
||||
"""
|
||||
from agent.pet.manifest import find_entry
|
||||
|
||||
@@ -169,9 +163,8 @@ def install_pet(slug: str, *, force: bool = False, timeout: float = _DOWNLOAD_TI
|
||||
if entry is None:
|
||||
raise PetStoreError(f"pet '{slug}' is not in the petdex manifest")
|
||||
|
||||
# Host-pin every asset URL to petdex. The manifest is trusted (HTTPS from
|
||||
# petdex.dev), but pin the asset hosts too so a compromised/spoofed manifest
|
||||
# can't redirect the download at an arbitrary host. Matches thumbnail_png.
|
||||
# Host-pin asset URLs so a compromised/spoofed manifest can't redirect the
|
||||
# download to an arbitrary host (matches thumbnail_png).
|
||||
if not _is_petdex_host(entry.spritesheet_url):
|
||||
raise PetStoreError(f"refusing non-petdex spritesheet host for '{slug}'")
|
||||
|
||||
@@ -180,28 +173,22 @@ def install_pet(slug: str, *, force: bool = False, timeout: float = _DOWNLOAD_TI
|
||||
|
||||
sprite_ext = ".png" if entry.spritesheet_url.lower().split("?")[0].endswith(".png") else ".webp"
|
||||
sprite_path = directory / f"spritesheet{sprite_ext}"
|
||||
|
||||
_download(entry.spritesheet_url, sprite_path, timeout=timeout)
|
||||
|
||||
# Fetch the upstream pet.json if present; otherwise synthesize a minimal
|
||||
# one so the local layout is self-describing.
|
||||
# Prefer the upstream pet.json; else synthesize one so the layout is self-describing.
|
||||
meta: dict = {}
|
||||
if entry.pet_json_url and _is_petdex_host(entry.pet_json_url):
|
||||
try:
|
||||
meta = _download_json(entry.pet_json_url, timeout=timeout)
|
||||
except Exception as exc: # noqa: BLE001 - non-fatal, fall back below
|
||||
logger.debug("pet.json fetch failed for %s: %s", slug, exc)
|
||||
if not isinstance(meta, dict) or not meta:
|
||||
if not meta:
|
||||
meta = {"id": slug, "displayName": entry.display_name, "description": ""}
|
||||
meta["spritesheetPath"] = sprite_path.name
|
||||
meta.setdefault("id", slug)
|
||||
meta.setdefault("displayName", entry.display_name)
|
||||
(directory / "pet.json").write_text(json.dumps(meta, indent=2), encoding="utf-8")
|
||||
|
||||
pet = load_pet(slug)
|
||||
if pet is None or not pet.exists:
|
||||
raise PetStoreError(f"install of '{slug}' did not produce a spritesheet")
|
||||
return pet
|
||||
_write_pet_json(directory, meta)
|
||||
return _loaded_pet_or_raise(slug, f"install of '{slug}' did not produce a spritesheet")
|
||||
|
||||
|
||||
def slugify(name: str) -> str:
|
||||
@@ -244,12 +231,11 @@ def register_local_pet(
|
||||
display_name: str = "",
|
||||
description: str = "",
|
||||
) -> InstalledPet:
|
||||
"""Write a locally-generated pet into the store and return it.
|
||||
"""Write a locally-generated pet (PIL image, WebP/PNG bytes, or path) into the store.
|
||||
|
||||
*spritesheet* may be a PIL image, raw WebP/PNG bytes, or a path. The pet
|
||||
appears in :func:`installed_pets` immediately, and because :func:`install_pet`
|
||||
returns an already-on-disk pet before consulting the manifest, it can be
|
||||
adopted (``pet.select`` / ``/pet <slug>``) without a manifest entry.
|
||||
It appears in :func:`installed_pets` immediately and, because :func:`install_pet`
|
||||
returns an on-disk pet before consulting the manifest, can be adopted without
|
||||
a manifest entry.
|
||||
"""
|
||||
slug = slugify(slug)
|
||||
directory = pets_dir() / slug
|
||||
@@ -260,33 +246,27 @@ def register_local_pet(
|
||||
except Exception as exc: # noqa: BLE001 - normalize to one error type
|
||||
raise PetStoreError(f"could not write spritesheet for '{slug}': {exc}") from exc
|
||||
|
||||
meta = {
|
||||
"id": slug,
|
||||
"displayName": display_name or slug,
|
||||
"description": description or "",
|
||||
"spritesheetPath": sprite_path.name,
|
||||
"createdBy": "generator",
|
||||
}
|
||||
(directory / "pet.json").write_text(json.dumps(meta, indent=2), encoding="utf-8")
|
||||
|
||||
pet = load_pet(slug)
|
||||
if pet is None or not pet.exists:
|
||||
raise PetStoreError(f"register of generated pet '{slug}' did not produce a spritesheet")
|
||||
return pet
|
||||
_write_pet_json(
|
||||
directory,
|
||||
{
|
||||
"id": slug,
|
||||
"displayName": display_name or slug,
|
||||
"description": description or "",
|
||||
"spritesheetPath": sprite_path.name,
|
||||
"createdBy": "generator",
|
||||
},
|
||||
)
|
||||
return _loaded_pet_or_raise(slug, f"register of generated pet '{slug}' did not produce a spritesheet")
|
||||
|
||||
|
||||
def export_pet(slug: str) -> tuple[str, bytes]:
|
||||
"""Zip an installed pet's folder (pet.json + spritesheet) → (filename, bytes).
|
||||
|
||||
Dotfiles (cached thumbs, backups) are skipped so the archive is a clean,
|
||||
re-importable pet package. Raises :class:`PetStoreError` if not installed.
|
||||
"""
|
||||
"""Zip an installed pet's folder → ``(filename, bytes)``; dotfiles (thumbs, backups) skipped."""
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
root = pets_dir()
|
||||
directory = root / slug.strip()
|
||||
# Guard against traversal: the target must be a direct child of pets_dir.
|
||||
# Traversal guard: the target must be a direct child of pets_dir.
|
||||
if directory.resolve().parent != root.resolve() or not directory.is_dir():
|
||||
raise PetStoreError(f"pet '{slug}' is not installed")
|
||||
|
||||
@@ -304,12 +284,6 @@ _THUMB_FRAME_H = 208
|
||||
_THUMB_W = 96 # rendered ~40px; 2x+ keeps it crisp on HiDPI
|
||||
|
||||
|
||||
def _thumbs_dir() -> Path:
|
||||
path = pets_dir() / ".thumbs"
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def _is_petdex_host(url: str) -> bool:
|
||||
"""True only for petdex.dev hosts — bounds server-side fetch (anti-SSRF)."""
|
||||
from urllib.parse import urlparse
|
||||
@@ -322,23 +296,18 @@ def _is_petdex_host(url: str) -> bool:
|
||||
|
||||
|
||||
def thumbnail_png(slug: str, *, source_url: str = "", timeout: float = 30.0) -> bytes | None:
|
||||
"""Return a small idle-frame PNG for *slug*, cached on disk.
|
||||
"""Small idle-frame (top-left cell) PNG for *slug*, cached on disk.
|
||||
|
||||
Crops the top-left (idle, frame 0) cell of the spritesheet and downsamples
|
||||
it to a thumbnail. Source preference: an installed spritesheet on disk, else
|
||||
*source_url* — but only when it points at petdex (so the gateway never
|
||||
fetches an arbitrary client-supplied URL). Returns ``None`` when there's no
|
||||
usable source or Pillow/network fails; callers render a placeholder.
|
||||
|
||||
Doing this server-side sidesteps the renderer's CSP / R2 hotlink limits that
|
||||
break a direct ``<img src=cdn>`` and lets the result ride the authenticated
|
||||
gateway as a same-origin data URL.
|
||||
Source: the installed spritesheet, else *source_url* only when it points at
|
||||
petdex (the gateway never fetches an arbitrary client URL). ``None`` when no
|
||||
usable source or Pillow/network fails. Server-side so the result rides the
|
||||
authenticated gateway as a same-origin data URL, sidestepping CSP/hotlink limits.
|
||||
"""
|
||||
slug = slug.strip()
|
||||
if not slug:
|
||||
return None
|
||||
|
||||
cache = _thumbs_dir() / f"{slug}.png"
|
||||
cache = _thumb_path(slug)
|
||||
if cache.is_file():
|
||||
try:
|
||||
return cache.read_bytes()
|
||||
@@ -351,18 +320,13 @@ def thumbnail_png(slug: str, *, source_url: str = "", timeout: float = 30.0) ->
|
||||
try:
|
||||
sheet_bytes = pet.spritesheet.read_bytes()
|
||||
except OSError:
|
||||
sheet_bytes = None
|
||||
pass
|
||||
|
||||
if sheet_bytes is None and source_url and _is_petdex_host(source_url):
|
||||
try:
|
||||
import httpx
|
||||
|
||||
resp = httpx.get(
|
||||
source_url,
|
||||
timeout=timeout,
|
||||
follow_redirects=True,
|
||||
headers={"User-Agent": "hermes-agent-petdex"},
|
||||
)
|
||||
resp = httpx.get(source_url, timeout=timeout, follow_redirects=True, headers=_HTTP_HEADERS)
|
||||
resp.raise_for_status()
|
||||
sheet_bytes = resp.content
|
||||
except Exception as exc: # noqa: BLE001 - cosmetic, degrade to placeholder
|
||||
@@ -377,11 +341,8 @@ def thumbnail_png(slug: str, *, source_url: str = "", timeout: float = 30.0) ->
|
||||
from PIL import Image
|
||||
|
||||
with Image.open(io.BytesIO(sheet_bytes)) as im:
|
||||
frame = im.convert("RGBA").crop(
|
||||
(0, 0, min(_THUMB_FRAME_W, im.width), min(_THUMB_FRAME_H, im.height))
|
||||
)
|
||||
height = round(_THUMB_W * _THUMB_FRAME_H / _THUMB_FRAME_W)
|
||||
frame = frame.resize((_THUMB_W, height), Image.NEAREST)
|
||||
frame = im.convert("RGBA").crop((0, 0, min(_THUMB_FRAME_W, im.width), min(_THUMB_FRAME_H, im.height)))
|
||||
frame = frame.resize((_THUMB_W, round(_THUMB_W * _THUMB_FRAME_H / _THUMB_FRAME_W)), Image.NEAREST)
|
||||
buf = io.BytesIO()
|
||||
frame.save(buf, format="PNG")
|
||||
data = buf.getvalue()
|
||||
@@ -397,18 +358,16 @@ def thumbnail_png(slug: str, *, source_url: str = "", timeout: float = 30.0) ->
|
||||
|
||||
|
||||
def remove_pet(slug: str) -> bool:
|
||||
"""Delete an installed pet directory. Returns True if anything was removed."""
|
||||
"""Delete an installed pet directory. Returns True if anything was removed."""
|
||||
import shutil
|
||||
|
||||
slug = _safe_slug(slug)
|
||||
if not slug:
|
||||
return False
|
||||
|
||||
# The cached thumbnail lives in pets/.thumbs/<slug>.png — OUTSIDE the pet
|
||||
# dir, so rmtree won't catch it. Drop it too, or a later pet that reuses this
|
||||
# slug renders this one's stale thumbnail.
|
||||
# Drop the cached thumb too or a later pet reusing this slug shows the stale one.
|
||||
try:
|
||||
(_thumbs_dir() / f"{slug}.png").unlink(missing_ok=True)
|
||||
_thumb_path(slug).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
@@ -422,25 +381,19 @@ def remove_pet(slug: str) -> bool:
|
||||
def rename_pet(slug: str, display_name: str) -> str | None:
|
||||
"""Rename a pet's ``displayName`` AND realign its slug/dir to match.
|
||||
|
||||
Generated pets are hatched under a provisional, prompt-derived slug; when
|
||||
the user names the pet on the reveal screen we make that name the real
|
||||
identity so lists/subtitles show what they typed, not the prompt. The dir is
|
||||
renamed to ``slugify(name)`` (and the cached thumbnail moved alongside it)
|
||||
whenever that yields a free, different slug — otherwise the slug is left as
|
||||
is. Returns the resulting slug on success, or ``None`` on failure.
|
||||
Generated pets hatch under a provisional prompt-derived slug; naming on the
|
||||
reveal screen makes that name the real identity. The dir (and cached thumb)
|
||||
moves to ``slugify(name)`` when that's a free, different slug; otherwise the
|
||||
slug stays. Returns the resulting slug, or ``None`` on failure.
|
||||
"""
|
||||
slug = _safe_slug(slug)
|
||||
display_name = (display_name or "").strip()
|
||||
if not slug or not display_name:
|
||||
return None
|
||||
directory = pets_dir() / slug
|
||||
pet_json = directory / "pet.json"
|
||||
if not pet_json.is_file():
|
||||
if not (directory / "pet.json").is_file():
|
||||
return None
|
||||
try:
|
||||
meta = json.loads(pet_json.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
meta = {}
|
||||
meta = _read_pet_json(directory)
|
||||
if not isinstance(meta, dict):
|
||||
meta = {}
|
||||
meta["displayName"] = display_name
|
||||
@@ -451,18 +404,17 @@ def rename_pet(slug: str, display_name: str) -> str | None:
|
||||
try:
|
||||
directory.rename(pets_dir() / desired)
|
||||
try:
|
||||
(_thumbs_dir() / f"{slug}.png").rename(_thumbs_dir() / f"{desired}.png")
|
||||
_thumb_path(slug).rename(_thumb_path(desired))
|
||||
except OSError:
|
||||
pass
|
||||
directory = pets_dir() / desired
|
||||
pet_json = directory / "pet.json"
|
||||
new_slug = desired
|
||||
meta["id"] = new_slug
|
||||
except OSError:
|
||||
new_slug = slug # keep the provisional slug if the move fails
|
||||
|
||||
try:
|
||||
pet_json.write_text(json.dumps(meta, indent=2), encoding="utf-8")
|
||||
_write_pet_json(directory, meta)
|
||||
except OSError:
|
||||
return None
|
||||
return new_slug
|
||||
@@ -472,13 +424,7 @@ def _download(url: str, dest: Path, *, timeout: float) -> None:
|
||||
import httpx
|
||||
|
||||
try:
|
||||
with httpx.stream(
|
||||
"GET",
|
||||
url,
|
||||
timeout=timeout,
|
||||
follow_redirects=True,
|
||||
headers={"User-Agent": "hermes-agent-petdex"},
|
||||
) as resp:
|
||||
with httpx.stream("GET", url, timeout=timeout, follow_redirects=True, headers=_HTTP_HEADERS) as resp:
|
||||
resp.raise_for_status()
|
||||
tmp = dest.with_suffix(dest.suffix + ".part")
|
||||
with tmp.open("wb") as fh:
|
||||
@@ -492,12 +438,7 @@ def _download(url: str, dest: Path, *, timeout: float) -> None:
|
||||
def _download_json(url: str, *, timeout: float) -> dict:
|
||||
import httpx
|
||||
|
||||
resp = httpx.get(
|
||||
url,
|
||||
timeout=timeout,
|
||||
follow_redirects=True,
|
||||
headers={"User-Agent": "hermes-agent-petdex"},
|
||||
)
|
||||
resp = httpx.get(url, timeout=timeout, follow_redirects=True, headers=_HTTP_HEADERS)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
+49
-157
@@ -1,27 +1,9 @@
|
||||
"""Process-level bootstrap helpers for ``run_agent``.
|
||||
|
||||
Three concerns, all tied to ``AIAgent`` boot-time / runtime IO setup:
|
||||
|
||||
1. **Lazy OpenAI SDK import** — ``_load_openai_cls`` + ``_OpenAIProxy``
|
||||
defer the 240ms-ish ``from openai import OpenAI`` cost until first use,
|
||||
while preserving ``isinstance(client, OpenAI)`` checks and
|
||||
``patch("run_agent.OpenAI", ...)`` test patterns.
|
||||
|
||||
2. **Crash-resistant stdio** — ``_SafeWriter`` wraps stdout/stderr so
|
||||
``OSError: Input/output error`` from broken pipes (systemd, Docker,
|
||||
thread teardown races) cannot crash the agent. ``_install_safe_stdio``
|
||||
applies the wrapper.
|
||||
|
||||
3. **HTTP proxy resolution** — ``_get_proxy_from_env`` reads
|
||||
``HTTPS_PROXY`` / ``HTTP_PROXY`` / ``ALL_PROXY``;
|
||||
``_get_proxy_for_base_url`` respects ``NO_PROXY`` for the given base URL.
|
||||
4. **Codex dual-stack resilience** — the synchronous ChatGPT/Codex transport
|
||||
races resolved IPv6/IPv4 addresses so a blackholed family cannot exhaust
|
||||
the request watchdog before a working address is attempted.
|
||||
|
||||
``run_agent`` re-exports every name so existing
|
||||
``from run_agent import _get_proxy_from_env`` imports keep working
|
||||
unchanged.
|
||||
Lazy OpenAI SDK import (``_load_openai_cls`` / ``_OpenAIProxy``, preserving
|
||||
``isinstance`` and ``patch("run_agent.OpenAI")`` patterns), crash-resistant
|
||||
stdio (``_SafeWriter``), env-only HTTP proxy resolution, and Codex dual-stack
|
||||
(Happy Eyeballs) connection racing. ``run_agent`` re-exports every name.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -38,8 +20,6 @@ from typing import Any, Optional
|
||||
from utils import base_url_hostname, normalize_proxy_url
|
||||
|
||||
|
||||
# Cached at module level so we only pay the OpenAI SDK import cost once
|
||||
# per process (after the first lazy load).
|
||||
_OPENAI_CLS_CACHE = None
|
||||
_HAPPY_EYEBALLS_DELAY_SECONDS = 0.25
|
||||
|
||||
@@ -74,18 +54,13 @@ def _happy_eyeballs_create_connection(
|
||||
source_address: Optional[tuple[str, int]] = None,
|
||||
socket_options=(),
|
||||
):
|
||||
"""Connect using staggered non-blocking attempts across resolved families.
|
||||
"""RFC 8305-style connect: staggered non-blocking attempts across families.
|
||||
|
||||
``socket.create_connection`` tries every address serially. A host with
|
||||
broken-but-advertised IPv6 can therefore consume the full connect timeout
|
||||
for each AAAA record before trying a working IPv4 address. This follows the
|
||||
Happy Eyeballs shape from RFC 8305: retain resolver preference, interleave
|
||||
families, and start the next candidate after a short delay.
|
||||
``socket.create_connection`` tries addresses serially, so broken-but-
|
||||
advertised IPv6 can burn the whole timeout per AAAA record before IPv4.
|
||||
"""
|
||||
host, port = address
|
||||
addrinfos = _interleave_addrinfos(
|
||||
socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
|
||||
)
|
||||
addrinfos = _interleave_addrinfos(socket.getaddrinfo(host, port, type=socket.SOCK_STREAM))
|
||||
if not addrinfos:
|
||||
raise OSError(f"getaddrinfo returned no addresses for {host}")
|
||||
|
||||
@@ -97,11 +72,7 @@ def _happy_eyeballs_create_connection(
|
||||
next_launch = time.monotonic()
|
||||
pending = list(addrinfos)
|
||||
in_progress = {
|
||||
0,
|
||||
errno.EINPROGRESS,
|
||||
errno.EWOULDBLOCK,
|
||||
errno.EALREADY,
|
||||
errno.EINTR,
|
||||
0, errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY, errno.EINTR,
|
||||
getattr(errno, "WSAEWOULDBLOCK", 10035),
|
||||
}
|
||||
|
||||
@@ -111,15 +82,11 @@ def _happy_eyeballs_create_connection(
|
||||
try:
|
||||
if source_address is not None:
|
||||
local_infos = socket.getaddrinfo(
|
||||
source_address[0],
|
||||
source_address[1],
|
||||
family=family,
|
||||
type=socktype,
|
||||
source_address[0], source_address[1], family=family, type=socktype
|
||||
)
|
||||
if not local_infos:
|
||||
raise OSError(
|
||||
f"getaddrinfo returned no local {family} address for "
|
||||
f"{source_address[0]}"
|
||||
f"getaddrinfo returned no local {family} address for {source_address[0]}"
|
||||
)
|
||||
candidate.bind(local_infos[0][4])
|
||||
candidate.setblocking(False)
|
||||
@@ -157,11 +124,7 @@ def _happy_eyeballs_create_connection(
|
||||
wait_timeout = None if deadline is None else max(0.0, deadline - now)
|
||||
if pending:
|
||||
until_launch = max(0.0, next_launch - now)
|
||||
wait_timeout = (
|
||||
until_launch
|
||||
if wait_timeout is None
|
||||
else min(wait_timeout, until_launch)
|
||||
)
|
||||
wait_timeout = until_launch if wait_timeout is None else min(wait_timeout, until_launch)
|
||||
|
||||
events = selector.select(wait_timeout)
|
||||
for key, _mask in events:
|
||||
@@ -218,12 +181,8 @@ class _HappyEyeballsSyncBackend:
|
||||
return self._fallback
|
||||
|
||||
def connect_tcp(
|
||||
self,
|
||||
host: str,
|
||||
port: int,
|
||||
timeout: Optional[float] = None,
|
||||
local_address: Optional[str] = None,
|
||||
socket_options=None,
|
||||
self, host: str, port: int, timeout: Optional[float] = None,
|
||||
local_address: Optional[str] = None, socket_options=None,
|
||||
):
|
||||
from httpcore import ConnectError, ConnectTimeout
|
||||
from httpcore._backends.sync import SyncStream
|
||||
@@ -231,10 +190,7 @@ class _HappyEyeballsSyncBackend:
|
||||
source_address = None if local_address is None else (local_address, 0)
|
||||
try:
|
||||
sock = _happy_eyeballs_create_connection(
|
||||
(host, port),
|
||||
timeout,
|
||||
source_address=source_address,
|
||||
socket_options=socket_options or (),
|
||||
(host, port), timeout, source_address=source_address, socket_options=socket_options or ()
|
||||
)
|
||||
except socket.timeout as exc:
|
||||
raise ConnectTimeout(str(exc)) from exc
|
||||
@@ -256,47 +212,34 @@ def _uses_codex_cloud_transport(base_url: str) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _enable_happy_eyeballs(transport) -> None:
|
||||
"""Install the sync racing backend on one httpx transport, if compatible.
|
||||
def _enable_happy_eyeballs(transport, skip_pool_types: tuple = ()) -> None:
|
||||
"""Install the racing backend on one httpx transport.
|
||||
|
||||
Reaches into httpx/httpcore private attributes (``transport._pool`` /
|
||||
``pool._network_backend``); safe because httpcore is pinned (1.0.x) and
|
||||
both lookups are hasattr-guarded — on an incompatible httpcore this
|
||||
degrades to the default serial backend instead of crashing.
|
||||
Reaches into private ``transport._pool._network_backend`` (httpcore is
|
||||
pinned 1.0.x); hasattr-guarded so an incompatible httpcore degrades to the
|
||||
default serial backend instead of crashing. Pools of ``skip_pool_types``
|
||||
(proxies) are left alone.
|
||||
"""
|
||||
pool = getattr(transport, "_pool", None)
|
||||
if pool is not None and hasattr(pool, "_network_backend"):
|
||||
pool._network_backend = _HappyEyeballsSyncBackend()
|
||||
if pool is None or not hasattr(pool, "_network_backend"):
|
||||
return
|
||||
if skip_pool_types and isinstance(pool, skip_pool_types):
|
||||
return
|
||||
pool._network_backend = _HappyEyeballsSyncBackend()
|
||||
|
||||
|
||||
def enable_happy_eyeballs_on_client(client) -> None:
|
||||
"""Install the sync racing backend on every direct transport of a client.
|
||||
"""Install the racing backend on every direct transport of a ready-built httpx.Client
|
||||
(for callers that build clients inline, e.g. Codex OAuth/device-login in hermes_cli.auth).
|
||||
|
||||
Covers a ready-built ``httpx.Client`` (its default transport plus any
|
||||
mounts), for callers that construct clients inline instead of going
|
||||
through :func:`build_keepalive_http_client` — e.g. the Codex OAuth token
|
||||
refresh / device-login / usage-probe clients in ``hermes_cli.auth``.
|
||||
|
||||
Proxy-backed transports (``httpcore.HTTPProxy`` / SOCKS pools) are left
|
||||
untouched: with a proxy in play the TCP connect goes to the proxy host,
|
||||
which is out of scope for the direct-transport racing added in #94388.
|
||||
Async clients are also left untouched — httpcore's async backend already
|
||||
performs RFC 8305 racing natively via
|
||||
``anyio.connect_tcp(happy_eyeballs_delay=0.25)``.
|
||||
|
||||
Best-effort and hasattr-guarded like ``_enable_happy_eyeballs``; on an
|
||||
incompatible httpx/httpcore this silently keeps the default backend.
|
||||
Proxy-backed pools are skipped (TCP connect goes to the proxy host) and
|
||||
async clients need nothing (anyio already races per RFC 8305). Best-effort.
|
||||
"""
|
||||
try:
|
||||
import httpcore
|
||||
|
||||
proxy_pool_types = tuple(
|
||||
t
|
||||
for t in (
|
||||
getattr(httpcore, "HTTPProxy", None),
|
||||
getattr(httpcore, "SOCKSProxy", None),
|
||||
)
|
||||
if t is not None
|
||||
t for t in (getattr(httpcore, "HTTPProxy", None), getattr(httpcore, "SOCKSProxy", None)) if t is not None
|
||||
)
|
||||
except Exception:
|
||||
return
|
||||
@@ -304,12 +247,7 @@ def enable_happy_eyeballs_on_client(client) -> None:
|
||||
transports = [getattr(client, "_transport", None)]
|
||||
transports.extend((getattr(client, "_mounts", None) or {}).values())
|
||||
for transport in transports:
|
||||
pool = getattr(transport, "_pool", None)
|
||||
if pool is None or not hasattr(pool, "_network_backend"):
|
||||
continue
|
||||
if proxy_pool_types and isinstance(pool, proxy_pool_types):
|
||||
continue
|
||||
pool._network_backend = _HappyEyeballsSyncBackend()
|
||||
_enable_happy_eyeballs(transport, proxy_pool_types)
|
||||
|
||||
|
||||
def _load_openai_cls() -> type:
|
||||
@@ -337,22 +275,11 @@ class _OpenAIProxy:
|
||||
|
||||
|
||||
class _SafeWriter:
|
||||
"""Transparent stdio wrapper that catches OSError/ValueError from broken pipes.
|
||||
"""Transparent stdio wrapper swallowing OSError/ValueError from broken pipes.
|
||||
|
||||
When hermes-agent runs as a systemd service, Docker container, or headless
|
||||
daemon, the stdout/stderr pipe can become unavailable (idle timeout, buffer
|
||||
exhaustion, socket reset). Any print() call then raises
|
||||
``OSError: [Errno 5] Input/output error``, which can crash agent setup or
|
||||
run_conversation() — especially via double-fault when an except handler
|
||||
also tries to print.
|
||||
|
||||
Additionally, when subagents run in ThreadPoolExecutor threads, the shared
|
||||
stdout handle can close between thread teardown and cleanup, raising
|
||||
``ValueError: I/O operation on closed file`` instead of OSError.
|
||||
|
||||
This wrapper delegates all writes to the underlying stream and silently
|
||||
catches both OSError and ValueError. It is transparent when the wrapped
|
||||
stream is healthy.
|
||||
Headless runs (systemd, Docker) lose the stdout pipe → ``OSError: [Errno 5]``;
|
||||
subagent threads can see the shared handle close → ``ValueError``. Either
|
||||
would otherwise crash the agent (often via double-fault in an except handler).
|
||||
"""
|
||||
|
||||
__slots__ = ("_inner",)
|
||||
@@ -386,11 +313,7 @@ class _SafeWriter:
|
||||
|
||||
|
||||
def _get_proxy_from_env() -> Optional[str]:
|
||||
"""Read proxy URL from environment variables.
|
||||
|
||||
Checks HTTPS_PROXY, HTTP_PROXY, ALL_PROXY (and lowercase variants) in order.
|
||||
Returns the first valid proxy URL found, or None if no proxy is configured.
|
||||
"""
|
||||
"""First configured proxy URL from HTTPS_PROXY / HTTP_PROXY / ALL_PROXY (any case), or None."""
|
||||
for key in ("HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY",
|
||||
"https_proxy", "http_proxy", "all_proxy"):
|
||||
value = os.environ.get(key, "").strip()
|
||||
@@ -418,43 +341,23 @@ def _get_proxy_for_base_url(base_url: Optional[str]) -> Optional[str]:
|
||||
return proxy
|
||||
|
||||
|
||||
def build_keepalive_http_client(
|
||||
base_url: str = "",
|
||||
*,
|
||||
async_mode: bool = False,
|
||||
verify: Any = True,
|
||||
) -> Optional[Any]:
|
||||
def build_keepalive_http_client(base_url: str = "", *, async_mode: bool = False, verify: Any = True) -> Optional[Any]:
|
||||
"""Build an httpx client for OpenAI SDK calls with env-only proxy policy.
|
||||
|
||||
Uses explicit ``HTTPS_PROXY`` / ``NO_PROXY`` env vars via
|
||||
``_get_proxy_for_base_url``. Plain no-proxy mounts disable httpx's default
|
||||
``trust_env`` proxy path, so macOS system proxy settings from
|
||||
``urllib.request.getproxies()`` (which omit the ExceptionsList) are not
|
||||
applied. Mirrors ``AIAgent._build_keepalive_http_client``.
|
||||
|
||||
Connection lifecycle is managed at the HTTP pool layer
|
||||
(``keepalive_expiry=20.0`` reaps idle connections before reverse proxies'
|
||||
typical 30-60 s timeouts) instead of the former custom
|
||||
``socket_options`` transport, which broke streaming behind reverse
|
||||
proxies (#54049, #12952) and stalled TLS handshakes by stripping
|
||||
``TCP_NODELAY``.
|
||||
|
||||
``verify`` is forwarded to httpx so auxiliary-client calls (compression,
|
||||
vision, web_extract, title generation, etc.) honor the same per-provider
|
||||
``ssl_ca_cert`` / ``ssl_verify`` and ``HERMES_CA_BUNDLE`` settings the main
|
||||
client uses. It is passed on the client AND on the plain no-proxy mounts
|
||||
(a mounted transport owns the SSL context for its scheme).
|
||||
Explicit no-proxy mounts disable httpx's ``trust_env`` path so macOS system
|
||||
proxies (which omit the ExceptionsList) are never applied. ``keepalive_expiry``
|
||||
reaps idle connections before reverse proxies' 30-60 s timeouts (a custom
|
||||
socket_options transport broke streaming and stripped TCP_NODELAY). ``verify``
|
||||
lets auxiliary calls honor the same ``ssl_ca_cert``/``ssl_verify``/``HERMES_CA_BUNDLE``
|
||||
as the main client; it goes on the client AND the mounts, since a mounted
|
||||
transport owns its SSL context.
|
||||
"""
|
||||
try:
|
||||
import httpx
|
||||
|
||||
proxy = _get_proxy_for_base_url(base_url)
|
||||
|
||||
limits = httpx.Limits(
|
||||
max_keepalive_connections=20,
|
||||
max_connections=100,
|
||||
keepalive_expiry=20.0,
|
||||
)
|
||||
limits = httpx.Limits(max_keepalive_connections=20, max_connections=100, keepalive_expiry=20.0)
|
||||
# Generous read=None for SSE streaming endpoints.
|
||||
timeout = httpx.Timeout(connect=15.0, read=None, write=15.0, pool=10.0)
|
||||
|
||||
@@ -464,21 +367,12 @@ def build_keepalive_http_client(
|
||||
if proxy is None:
|
||||
http_transport = transport_cls(verify=verify)
|
||||
https_transport = transport_cls(verify=verify)
|
||||
# Async transports need no explicit racing: httpcore's anyio
|
||||
# backend already implements RFC 8305 natively
|
||||
# (``anyio.connect_tcp(happy_eyeballs_delay=0.25)``), covered by
|
||||
# tests/agent/test_codex_happy_eyeballs.py.
|
||||
# Async transports race natively (anyio happy_eyeballs_delay=0.25).
|
||||
if not async_mode and _uses_codex_cloud_transport(base_url):
|
||||
_enable_happy_eyeballs(http_transport)
|
||||
_enable_happy_eyeballs(https_transport)
|
||||
mounts = {"http://": http_transport, "https://": https_transport}
|
||||
return client_cls(
|
||||
limits=limits,
|
||||
timeout=timeout,
|
||||
proxy=proxy,
|
||||
mounts=mounts or None,
|
||||
verify=verify,
|
||||
)
|
||||
return client_cls(limits=limits, timeout=timeout, proxy=proxy, mounts=mounts or None, verify=verify)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
@@ -491,9 +385,7 @@ def _install_safe_stdio() -> None:
|
||||
setattr(sys, stream_name, _SafeWriter(stream))
|
||||
|
||||
|
||||
# Module-level proxy instance — drops in for ``openai.OpenAI``. Imported as
|
||||
# ``from agent.process_bootstrap import OpenAI`` (or re-exported via
|
||||
# ``run_agent`` for legacy tests).
|
||||
# Drop-in for ``openai.OpenAI`` (also re-exported via ``run_agent``).
|
||||
OpenAI = _OpenAIProxy()
|
||||
|
||||
|
||||
|
||||
+9
-19
@@ -1,17 +1,12 @@
|
||||
"""Token-free detection of user *reactions* to the agent.
|
||||
|
||||
Currently the only reaction is ``vibe`` — an expression of affection or
|
||||
gratitude toward the agent (``ily``, ``<3``, ``love you``, ``good bot``, a heart
|
||||
emoji, …). Detection is a curated regex/lexicon: **no model call, no tokens**.
|
||||
|
||||
This is the single source of truth shared by every surface — the CLI pet, the
|
||||
TUI heart, and the desktop floating hearts all react off the same signal,
|
||||
delivered via ``AIAgent.reaction_callback`` (wired per interactive host).
|
||||
|
||||
Generalized on purpose: :func:`detect_reaction` returns a reaction *kind*
|
||||
string, so new kinds (other emoji reactions, etc.) can be added here without
|
||||
touching any caller. We match affection specifically — not general positive
|
||||
sentiment — so "this is great" does NOT fire, but "good bot" / "❤️" do.
|
||||
The only reaction today is ``vibe`` — affection/gratitude aimed at the agent
|
||||
(``ily``, ``<3``, ``good bot``, a heart emoji). Detection is a curated regex:
|
||||
no model call. Single source of truth for the CLI pet, TUI heart and desktop
|
||||
hearts via ``AIAgent.reaction_callback``. :func:`detect_reaction` returns a
|
||||
*kind* string so new kinds can be added without touching callers. Matches
|
||||
affection specifically, not general positive sentiment ("this is great" does
|
||||
NOT fire).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,8 +16,7 @@ import re
|
||||
#: The affection/gratitude reaction — the only kind today.
|
||||
VIBE = "vibe"
|
||||
|
||||
# Curated affection lexicon. Kept deliberately narrow: gratitude + love aimed at
|
||||
# the agent, heart emoji, and ``<3`` (but not the broken heart ``</3``).
|
||||
# Narrow lexicon: gratitude + love aimed at the agent, hearts, ``<3`` (not ``</3``).
|
||||
_VIBE_RE = re.compile(
|
||||
"|".join(
|
||||
(
|
||||
@@ -46,11 +40,7 @@ _VIBE_RE = re.compile(
|
||||
|
||||
|
||||
def detect_reaction(text: str | None) -> str | None:
|
||||
"""Return the reaction kind for *text* (currently :data:`VIBE`), or ``None``.
|
||||
|
||||
Pure, token-free, and safe to call on every user turn.
|
||||
"""
|
||||
"""Return the reaction kind for *text* (currently :data:`VIBE`), or ``None``."""
|
||||
if not text:
|
||||
return None
|
||||
|
||||
return VIBE if _VIBE_RE.search(text) else None
|
||||
|
||||
+20
-36
@@ -1,31 +1,24 @@
|
||||
"""Shared session activity observation contract (#72016 / #72039).
|
||||
"""Shared session activity observation contract.
|
||||
|
||||
Observation-only: timestamp + bounded description/provenance.
|
||||
Notification, timeout, kill, and retry policy stay in their own components.
|
||||
Consumers distinguish work (API / tool / compacting / stalled) from the
|
||||
description text itself — there is no separate phase enum.
|
||||
|
||||
Provenance is a small closed enum of *noun* sources (where the stamp came
|
||||
from). The default agent activity clock (``_touch_activity``) stamps
|
||||
``unknown`` unless a caller passes an explicit ``provenance=``; named
|
||||
values are for special writers.
|
||||
Observation-only: timestamp + bounded description/provenance. Notification,
|
||||
timeout, kill and retry policy live in their own components. Provenance is a
|
||||
small closed enum of *noun* sources; the default agent clock stamps ``unknown``
|
||||
unless a writer passes an explicit ``provenance=``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from enum import Enum
|
||||
from typing import Any, Mapping, Optional
|
||||
|
||||
ACTIVITY_DESCRIPTION_MAX = 120
|
||||
|
||||
# Durable SessionDB activity heartbeat cadence (seconds between writes per
|
||||
# session). Contract: MUST stay >= 30s — the SessionDB write path is
|
||||
# contended (deadline/patience retry, compression-lock patience), and the
|
||||
# heartbeat is an observation-only projection that never justifies extra
|
||||
# write pressure. This cadence is deliberately a code constant, independent
|
||||
# of any compression.* or agent.* config, so no configuration can turn the
|
||||
# heartbeat into a high-frequency writer. Matches the kanban auto-heartbeat
|
||||
# cadence. force_persist (terminal stamps) is the only bypass.
|
||||
# Durable SessionDB heartbeat cadence. Contract: MUST stay >= 30s — the
|
||||
# SessionDB write path is contended and the heartbeat is an observation-only
|
||||
# projection that never justifies extra write pressure. Deliberately a code
|
||||
# constant (no config can turn it into a high-frequency writer); matches the
|
||||
# kanban auto-heartbeat. force_persist (terminal stamps) is the only bypass.
|
||||
SESSION_ACTIVITY_HEARTBEAT_MIN_INTERVAL_SECONDS = 60.0
|
||||
|
||||
|
||||
@@ -33,7 +26,7 @@ class ActivityProvenance(str, Enum):
|
||||
"""Where a durable/in-memory activity stamp came from."""
|
||||
|
||||
UNKNOWN = "unknown"
|
||||
# Compression writers (#72424 / activity contract): heartbeat, host timeout, cooldown.
|
||||
# Compression writers: heartbeat, host timeout, cooldown, turn hold.
|
||||
AGENT_COMPRESSION = "agent.compression"
|
||||
AGENT_COMPRESSION_TIMEOUT = "agent.compression_timeout"
|
||||
AGENT_COMPRESSION_COOLDOWN = "agent.compression_cooldown"
|
||||
@@ -54,21 +47,15 @@ def normalize_activity_provenance(
|
||||
"""Return a known provenance, or ``UNKNOWN`` when unset/unrecognized."""
|
||||
if isinstance(provenance, ActivityProvenance):
|
||||
return provenance
|
||||
value = (provenance or "").strip()
|
||||
try:
|
||||
return ActivityProvenance(value)
|
||||
return ActivityProvenance((provenance or "").strip())
|
||||
except ValueError:
|
||||
return ActivityProvenance.UNKNOWN
|
||||
|
||||
|
||||
def reset_session_activity_persist_window(agent: Any) -> None:
|
||||
"""Clear the agent's durable SessionDB activity persist rate-limit window.
|
||||
|
||||
The next ``_touch_activity`` / ``_persist_session_activity_if_due`` will
|
||||
write through even if a stamp landed within the last 60s. Used for
|
||||
terminal compression labels that must not stay stuck on mid-compress
|
||||
text (e.g. "context compression in progress" after /compress).
|
||||
"""
|
||||
"""Clear the durable persist rate-limit so the next stamp writes through
|
||||
(terminal compression labels must not stay stuck on mid-compress text)."""
|
||||
try:
|
||||
agent._session_activity_last_persist_mono = 0.0
|
||||
except Exception:
|
||||
@@ -84,23 +71,20 @@ def build_activity_snapshot(
|
||||
extra: Optional[Mapping[str, Any]] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build the shared activity snapshot (plus optional caller extras)."""
|
||||
import time as _time
|
||||
|
||||
when = float(last_activity_at) if last_activity_at is not None else None
|
||||
clock = float(now if now is not None else _time.time())
|
||||
clock = float(now if now is not None else time.time())
|
||||
desc = bound_activity_description(last_activity_description)
|
||||
prov = normalize_activity_provenance(last_activity_provenance)
|
||||
elapsed = round(clock - when, 1) if when is not None else None
|
||||
prov = normalize_activity_provenance(last_activity_provenance).value
|
||||
snap: dict[str, Any] = {
|
||||
"last_activity_at": when,
|
||||
"last_activity_description": desc,
|
||||
"last_activity_provenance": prov.value,
|
||||
"seconds_since_activity": elapsed,
|
||||
"last_activity_provenance": prov,
|
||||
"seconds_since_activity": round(clock - when, 1) if when is not None else None,
|
||||
# Short aliases used by existing gateway/delegate readers.
|
||||
"last_activity_ts": when,
|
||||
"last_activity_desc": desc,
|
||||
"description": desc,
|
||||
"provenance": prov.value,
|
||||
"provenance": prov,
|
||||
}
|
||||
if extra:
|
||||
snap.update(dict(extra))
|
||||
|
||||
+303
-671
File diff suppressed because it is too large
Load Diff
+102
-180
@@ -1,8 +1,7 @@
|
||||
"""Public, plugin-safe lifecycle API for delegated Hermes subagents.
|
||||
|
||||
This module deliberately exposes immutable contracts, not ``AIAgent`` objects.
|
||||
It is the supported boundary for plugins that need to supervise fresh child
|
||||
sessions; plugins must obtain it from ``PluginContext.subagent_lifecycle``.
|
||||
Exposes immutable contracts, not ``AIAgent`` objects; plugins obtain it via
|
||||
``PluginContext.subagent_lifecycle``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -157,9 +156,7 @@ class _Registry:
|
||||
|
||||
|
||||
_REGISTRY = _Registry()
|
||||
# Daemon worker pool: a wedged/abandoned child must never block interpreter
|
||||
# exit at atexit-join time (same rationale as _run_single_child's timeout
|
||||
# executor and the async-delegation registry pool).
|
||||
# Daemon pool: a wedged/abandoned child must never block interpreter exit.
|
||||
from tools.daemon_pool import DaemonThreadPoolExecutor as _DaemonExecutor
|
||||
|
||||
_EXECUTOR = _DaemonExecutor(max_workers=8, thread_name_prefix="hermes-lifecycle")
|
||||
@@ -184,12 +181,52 @@ def get_active_subagent_parent() -> Any:
|
||||
return _ACTIVE_PARENT_AGENT.get()
|
||||
|
||||
|
||||
def _opt_str(value: Any) -> bool:
|
||||
return value is None or isinstance(value, str)
|
||||
|
||||
|
||||
def _finite_number(value: Any) -> bool:
|
||||
return not isinstance(value, bool) and isinstance(value, (int, float)) and math.isfinite(value)
|
||||
|
||||
|
||||
# Per-field shape check applied to a (possibly deserialized) handle before trusting it.
|
||||
_HANDLE_FIELD_CHECKS: tuple[tuple[str, Callable[[Any], bool]], ...] = (
|
||||
("contract_version", lambda v: type(v) is int and v == PUBLIC_CONTRACT_VERSION),
|
||||
("subagent_id", lambda v: isinstance(v, str) and bool(v)),
|
||||
("parent_session_id", _opt_str),
|
||||
("correlation_id", _opt_str),
|
||||
("created_at", _finite_number),
|
||||
("provider", _opt_str),
|
||||
("model", _opt_str),
|
||||
("role", lambda v: isinstance(v, str)),
|
||||
("depth", lambda v: type(v) is int),
|
||||
("capability", lambda v: isinstance(v, str)),
|
||||
)
|
||||
|
||||
|
||||
# Launch-request fields the public contract deliberately rejects: (predicate, error).
|
||||
_UNSUPPORTED_REQUEST_FIELDS: tuple[tuple[Callable[[SubagentLaunchRequest], bool], str], ...] = (
|
||||
(lambda r: r.timeout_seconds is not None,
|
||||
"Per-launch timeout is not supported; configure delegation timeout explicitly."),
|
||||
(lambda r: r.working_directory is not None,
|
||||
"working_directory is not supported because Hermes delegates use isolated task environments."),
|
||||
(lambda r: bool(r.blocked_tools),
|
||||
"Per-tool blocking is not supported; use allowed_toolsets. Hermes always blocks unsafe child tools."),
|
||||
)
|
||||
|
||||
|
||||
def _handle_is_well_formed(handle: Any) -> bool:
|
||||
return isinstance(handle, SubagentHandle) and all(
|
||||
check(getattr(handle, field)) for field, check in _HANDLE_FIELD_CHECKS
|
||||
)
|
||||
|
||||
|
||||
class SubagentLifecycleService:
|
||||
"""Stable public service returned by :attr:`PluginContext.subagent_lifecycle`.
|
||||
|
||||
Running children are in-process only. Completed results remain available
|
||||
until process exit; ``reconnect`` accurately reports that a serialized
|
||||
handle cannot reconnect after a restart instead of launching work again.
|
||||
Running children are in-process only. Completed results remain available
|
||||
until process exit; ``reconnect`` reports that a serialized handle cannot
|
||||
reconnect after a restart instead of launching work again.
|
||||
"""
|
||||
|
||||
def __init__(self, parent_agent_resolver: Callable[[], Any]) -> None:
|
||||
@@ -198,37 +235,26 @@ class SubagentLifecycleService:
|
||||
def launch(self, request: SubagentLaunchRequest) -> SubagentHandle:
|
||||
parent = self._parent_agent_resolver()
|
||||
if parent is None:
|
||||
raise SubagentLifecycleError(
|
||||
"No active Hermes parent session is available."
|
||||
)
|
||||
raise SubagentLifecycleError("No active Hermes parent session is available.")
|
||||
self._validate_request(request, parent)
|
||||
parent_session_id = str(getattr(parent, "session_id", "") or "") or None
|
||||
if request.parent_session_id and request.parent_session_id != parent_session_id:
|
||||
raise SubagentLifecycleError(
|
||||
"parent_session_id does not match the active session."
|
||||
)
|
||||
raise SubagentLifecycleError("parent_session_id does not match the active session.")
|
||||
correlation_key = (parent_session_id, request.correlation_id or "")
|
||||
with _REGISTRY.lock:
|
||||
self._cleanup_locked()
|
||||
if request.correlation_id and correlation_key in _REGISTRY.correlations:
|
||||
raise SubagentLifecycleError(
|
||||
"Duplicate correlation_id for this parent session."
|
||||
)
|
||||
raise SubagentLifecycleError("Duplicate correlation_id for this parent session.")
|
||||
|
||||
# Delegate construction remains internal so plugin code never imports
|
||||
# private delegation helpers or manipulates the active-child registry.
|
||||
from tools.delegate_tool import (
|
||||
_build_child_preserving_parent_tools,
|
||||
DEFAULT_MAX_ITERATIONS,
|
||||
)
|
||||
# Delegate construction stays internal so plugin code never imports
|
||||
# private delegation helpers or touches the active-child registry.
|
||||
from tools.delegate_tool import _build_child_preserving_parent_tools, DEFAULT_MAX_ITERATIONS
|
||||
|
||||
child = _build_child_preserving_parent_tools(
|
||||
task_index=0,
|
||||
goal=request.goal,
|
||||
context=request.context,
|
||||
toolsets=list(request.allowed_toolsets)
|
||||
if request.allowed_toolsets
|
||||
else None,
|
||||
toolsets=list(request.allowed_toolsets) if request.allowed_toolsets else None,
|
||||
model=request.model,
|
||||
max_iterations=DEFAULT_MAX_ITERATIONS,
|
||||
task_count=1,
|
||||
@@ -262,20 +288,14 @@ class SubagentLifecycleService:
|
||||
def status(self, handle: SubagentHandle) -> SubagentStatus:
|
||||
record = self._record(handle)
|
||||
if record is None:
|
||||
return SubagentStatus(
|
||||
handle, SubagentState.UNKNOWN, time.time(), "UNKNOWN_HANDLE"
|
||||
)
|
||||
return SubagentStatus(handle, SubagentState.UNKNOWN, time.time(), "UNKNOWN_HANDLE")
|
||||
with _REGISTRY.lock:
|
||||
return SubagentStatus(record.handle, record.state, record.updated_at)
|
||||
|
||||
def wait(
|
||||
self, handle: SubagentHandle, *, timeout_seconds: Optional[float] = None
|
||||
) -> SubagentTerminalState:
|
||||
def wait(self, handle: SubagentHandle, *, timeout_seconds: Optional[float] = None) -> SubagentTerminalState:
|
||||
record = self._record(handle)
|
||||
if record is None:
|
||||
return SubagentTerminalState(
|
||||
handle, SubagentState.UNKNOWN, True, diagnostic="UNKNOWN_HANDLE"
|
||||
)
|
||||
return SubagentTerminalState(handle, SubagentState.UNKNOWN, True, diagnostic="UNKNOWN_HANDLE")
|
||||
future = record.future
|
||||
if future is not None:
|
||||
try:
|
||||
@@ -285,9 +305,7 @@ class SubagentLifecycleService:
|
||||
except Exception:
|
||||
pass
|
||||
with _REGISTRY.lock:
|
||||
return SubagentTerminalState(
|
||||
record.handle, record.state, record.result is not None
|
||||
)
|
||||
return SubagentTerminalState(record.handle, record.state, record.result is not None)
|
||||
|
||||
def cancel(self, handle: SubagentHandle, *, reason: str) -> SubagentCancelResult:
|
||||
record = self._record(handle)
|
||||
@@ -295,16 +313,13 @@ class SubagentLifecycleService:
|
||||
return SubagentCancelResult(False, unknown_handle=True)
|
||||
with _REGISTRY.lock:
|
||||
if record.result is not None:
|
||||
return SubagentCancelResult(
|
||||
False, already_terminal=True, state=record.state
|
||||
)
|
||||
return SubagentCancelResult(False, already_terminal=True, state=record.state)
|
||||
agent = record.agent
|
||||
record.state = SubagentState.CANCEL_REQUESTED
|
||||
record.updated_at = time.time()
|
||||
unsupported = SubagentCancelResult(False, unsupported=True, state=SubagentState.CANCEL_REQUESTED)
|
||||
if agent is None:
|
||||
return SubagentCancelResult(
|
||||
False, unsupported=True, state=SubagentState.CANCEL_REQUESTED
|
||||
)
|
||||
return unsupported
|
||||
try:
|
||||
accepted = request_hard_interrupt(
|
||||
agent,
|
||||
@@ -312,74 +327,32 @@ class SubagentLifecycleService:
|
||||
tool_reason="subagent cancellation requested",
|
||||
)
|
||||
except Exception:
|
||||
return SubagentCancelResult(
|
||||
False, unsupported=True, state=SubagentState.CANCEL_REQUESTED
|
||||
)
|
||||
accepted = False
|
||||
if not accepted:
|
||||
return SubagentCancelResult(
|
||||
False, unsupported=True, state=SubagentState.CANCEL_REQUESTED
|
||||
)
|
||||
return unsupported
|
||||
return SubagentCancelResult(True, state=SubagentState.CANCEL_REQUESTED)
|
||||
|
||||
def result(self, handle: SubagentHandle) -> SubagentResult:
|
||||
record = self._record(handle)
|
||||
if record is None:
|
||||
return SubagentResult(
|
||||
handle,
|
||||
SubagentState.UNKNOWN,
|
||||
False,
|
||||
error_classification="UNKNOWN_HANDLE",
|
||||
)
|
||||
return SubagentResult(handle, SubagentState.UNKNOWN, False, error_classification="UNKNOWN_HANDLE")
|
||||
with _REGISTRY.lock:
|
||||
if record.result is not None:
|
||||
return record.result
|
||||
return SubagentResult(
|
||||
record.handle, record.state, False, error_classification="NOT_READY"
|
||||
)
|
||||
return SubagentResult(record.handle, record.state, False, error_classification="NOT_READY")
|
||||
|
||||
def reconnect(self, handle: SubagentHandle) -> SubagentReconnectResult:
|
||||
record = self._record(handle)
|
||||
if record is None:
|
||||
return SubagentReconnectResult(
|
||||
False, SubagentState.UNKNOWN, "RECONNECT_UNAVAILABLE"
|
||||
)
|
||||
return SubagentReconnectResult(False, SubagentState.UNKNOWN, "RECONNECT_UNAVAILABLE")
|
||||
with _REGISTRY.lock:
|
||||
return SubagentReconnectResult(True, record.state)
|
||||
|
||||
def _record(self, handle: SubagentHandle) -> Optional[_Record]:
|
||||
if (
|
||||
not isinstance(handle, SubagentHandle)
|
||||
or type(handle.contract_version) is not int
|
||||
or handle.contract_version != PUBLIC_CONTRACT_VERSION
|
||||
):
|
||||
if not _handle_is_well_formed(handle):
|
||||
return None
|
||||
if (
|
||||
not isinstance(handle.subagent_id, str)
|
||||
or not handle.subagent_id
|
||||
or (
|
||||
handle.parent_session_id is not None
|
||||
and not isinstance(handle.parent_session_id, str)
|
||||
)
|
||||
or (
|
||||
handle.correlation_id is not None
|
||||
and not isinstance(handle.correlation_id, str)
|
||||
)
|
||||
or isinstance(handle.created_at, bool)
|
||||
or not isinstance(handle.created_at, (int, float))
|
||||
or not math.isfinite(handle.created_at)
|
||||
or (handle.provider is not None and not isinstance(handle.provider, str))
|
||||
or (handle.model is not None and not isinstance(handle.model, str))
|
||||
or not isinstance(handle.role, str)
|
||||
or type(handle.depth) is not int
|
||||
or not isinstance(handle.capability, str)
|
||||
):
|
||||
return None
|
||||
if not hmac.compare_digest(
|
||||
handle.capability,
|
||||
self._capability(
|
||||
handle.subagent_id, handle.parent_session_id, handle.created_at
|
||||
),
|
||||
):
|
||||
expected = self._capability(handle.subagent_id, handle.parent_session_id, handle.created_at)
|
||||
if not hmac.compare_digest(handle.capability, expected):
|
||||
return None
|
||||
parent = self._parent_agent_resolver()
|
||||
active_parent_id = str(getattr(parent, "session_id", "") or "") or None
|
||||
@@ -403,8 +376,7 @@ class SubagentLifecycleService:
|
||||
record = _REGISTRY.records.pop(subagent_id)
|
||||
if record.handle.correlation_id:
|
||||
_REGISTRY.correlations.pop(
|
||||
(record.handle.parent_session_id, record.handle.correlation_id),
|
||||
None,
|
||||
(record.handle.parent_session_id, record.handle.correlation_id), None
|
||||
)
|
||||
|
||||
def _run(self, record: _Record, goal: str, parent: Any) -> None:
|
||||
@@ -417,60 +389,34 @@ class SubagentLifecycleService:
|
||||
from tools.delegate_tool import _run_child_lifecycle
|
||||
|
||||
raw = _run_child_lifecycle(0, goal, record.agent, parent)
|
||||
status = (
|
||||
str(raw.get("status", "error")) if isinstance(raw, dict) else "error"
|
||||
)
|
||||
if status == "completed":
|
||||
state = SubagentState.SUCCEEDED
|
||||
elif status == "interrupted":
|
||||
state = (
|
||||
SubagentState.CANCELLED
|
||||
if record.state == SubagentState.CANCEL_REQUESTED
|
||||
else SubagentState.INTERRUPTED
|
||||
)
|
||||
is_dict = isinstance(raw, dict)
|
||||
if not is_dict:
|
||||
raw = {}
|
||||
status = str(raw.get("status", "error"))
|
||||
if status == "interrupted":
|
||||
cancelled = record.state == SubagentState.CANCEL_REQUESTED
|
||||
state = SubagentState.CANCELLED if cancelled else SubagentState.INTERRUPTED
|
||||
else:
|
||||
state = SubagentState.FAILED
|
||||
summary = raw.get("summary") if isinstance(raw, dict) else None
|
||||
summary = str(summary)[:_MAX_RESULT_CHARS] if summary is not None else None
|
||||
error = raw.get("error") if isinstance(raw, dict) else None
|
||||
result = SubagentResult(
|
||||
record.handle,
|
||||
state,
|
||||
True,
|
||||
summary=summary,
|
||||
completed_at=time.time(),
|
||||
started_at=record.started_at,
|
||||
error_classification=None
|
||||
if state == SubagentState.SUCCEEDED
|
||||
else status.upper(),
|
||||
state = SubagentState.SUCCEEDED if status == "completed" else SubagentState.FAILED
|
||||
summary = raw.get("summary")
|
||||
error = raw.get("error")
|
||||
fields: dict[str, Any] = dict(
|
||||
summary=str(summary)[:_MAX_RESULT_CHARS] if summary is not None else None,
|
||||
error_classification=None if state == SubagentState.SUCCEEDED else status.upper(),
|
||||
error_message=str(error)[:_MAX_RESULT_CHARS] if error else None,
|
||||
usage_metadata={"api_calls": raw.get("api_calls", 0)}
|
||||
if isinstance(raw, dict)
|
||||
else {},
|
||||
tool_execution_summary={
|
||||
"duration_seconds": raw.get("duration_seconds", 0)
|
||||
}
|
||||
if isinstance(raw, dict)
|
||||
else {},
|
||||
usage_metadata={"api_calls": raw.get("api_calls", 0)} if is_dict else {},
|
||||
tool_execution_summary={"duration_seconds": raw.get("duration_seconds", 0)} if is_dict else {},
|
||||
)
|
||||
except Exception as exc:
|
||||
result = SubagentResult(
|
||||
record.handle,
|
||||
SubagentState.FAILED,
|
||||
True,
|
||||
started_at=record.started_at,
|
||||
completed_at=time.time(),
|
||||
error_classification=type(exc).__name__,
|
||||
error_message=str(exc)[:_MAX_RESULT_CHARS],
|
||||
)
|
||||
state = SubagentState.FAILED
|
||||
fields = dict(error_classification=type(exc).__name__, error_message=str(exc)[:_MAX_RESULT_CHARS])
|
||||
result = SubagentResult(
|
||||
record.handle, state, True, started_at=record.started_at, completed_at=time.time(), **fields
|
||||
)
|
||||
payload = dataclasses.asdict(result)
|
||||
payload.pop("result_hash", None)
|
||||
result = dataclasses.replace(
|
||||
result,
|
||||
result_hash=hashlib.sha256(
|
||||
json.dumps(payload, sort_keys=True, default=str).encode()
|
||||
).hexdigest(),
|
||||
)
|
||||
digest = hashlib.sha256(json.dumps(payload, sort_keys=True, default=str).encode()).hexdigest()
|
||||
result = dataclasses.replace(result, result_hash=digest)
|
||||
with _REGISTRY.lock:
|
||||
record.agent = None
|
||||
record.result = result
|
||||
@@ -479,9 +425,7 @@ class SubagentLifecycleService:
|
||||
record.updated_at = result.completed_at or time.time()
|
||||
|
||||
@staticmethod
|
||||
def _capability(
|
||||
subagent_id: str, parent_session_id: Optional[str], created_at: float
|
||||
) -> str:
|
||||
def _capability(subagent_id: str, parent_session_id: Optional[str], created_at: float) -> str:
|
||||
value = f"{subagent_id}|{parent_session_id or ''}|{created_at:.6f}".encode()
|
||||
return hmac.new(_SECRET, value, hashlib.sha256).hexdigest()
|
||||
|
||||
@@ -493,34 +437,18 @@ class SubagentLifecycleService:
|
||||
or not request.goal.strip()
|
||||
or len(request.goal) > _MAX_GOAL_CHARS
|
||||
):
|
||||
raise SubagentLifecycleError(
|
||||
"goal must be a non-empty string of at most 16000 characters."
|
||||
)
|
||||
raise SubagentLifecycleError("goal must be a non-empty string of at most 16000 characters.")
|
||||
if request.context is not None and (
|
||||
not isinstance(request.context, str)
|
||||
or len(request.context) > _MAX_CONTEXT_CHARS
|
||||
not isinstance(request.context, str) or len(request.context) > _MAX_CONTEXT_CHARS
|
||||
):
|
||||
raise SubagentLifecycleError(
|
||||
"context must be a string of at most 32000 characters."
|
||||
)
|
||||
raise SubagentLifecycleError("context must be a string of at most 32000 characters.")
|
||||
if request.role not in {"leaf", "orchestrator"}:
|
||||
raise SubagentLifecycleError("role must be 'leaf' or 'orchestrator'.")
|
||||
if request.timeout_seconds is not None:
|
||||
raise SubagentLifecycleError(
|
||||
"Per-launch timeout is not supported; configure delegation timeout explicitly."
|
||||
)
|
||||
if request.working_directory is not None:
|
||||
raise SubagentLifecycleError(
|
||||
"working_directory is not supported because Hermes delegates use isolated task environments."
|
||||
)
|
||||
if request.blocked_tools:
|
||||
raise SubagentLifecycleError(
|
||||
"Per-tool blocking is not supported; use allowed_toolsets. Hermes always blocks unsafe child tools."
|
||||
)
|
||||
for rejected, message in _UNSUPPORTED_REQUEST_FIELDS:
|
||||
if rejected(request):
|
||||
raise SubagentLifecycleError(message)
|
||||
try:
|
||||
metadata_bytes = len(
|
||||
json.dumps(dict(request.metadata), sort_keys=True).encode()
|
||||
)
|
||||
metadata_bytes = len(json.dumps(dict(request.metadata), sort_keys=True).encode())
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise SubagentLifecycleError("metadata must be JSON-serializable.") from exc
|
||||
if metadata_bytes > _MAX_METADATA_BYTES:
|
||||
@@ -530,13 +458,7 @@ class SubagentLifecycleService:
|
||||
|
||||
unknown = set(request.allowed_toolsets) - set(TOOLSETS)
|
||||
if unknown:
|
||||
raise SubagentLifecycleError(
|
||||
f"Unknown toolsets: {', '.join(sorted(unknown))}."
|
||||
)
|
||||
raise SubagentLifecycleError(f"Unknown toolsets: {', '.join(sorted(unknown))}.")
|
||||
enabled = getattr(parent, "enabled_toolsets", None)
|
||||
if enabled is not None and not set(request.allowed_toolsets).issubset(
|
||||
set(enabled)
|
||||
):
|
||||
raise SubagentLifecycleError(
|
||||
"Requested toolsets would broaden parent permissions."
|
||||
)
|
||||
if enabled is not None and not set(request.allowed_toolsets).issubset(set(enabled)):
|
||||
raise SubagentLifecycleError("Requested toolsets would broaden parent permissions.")
|
||||
|
||||
@@ -1,19 +1,11 @@
|
||||
"""Thread-scoped stdout/stderr silencing for background worker threads.
|
||||
|
||||
``contextlib.redirect_stdout``/``redirect_stderr`` reassign the *process-global*
|
||||
``sys.stdout``/``sys.stderr``. When a daemon worker thread (e.g. the background
|
||||
memory/skill review) wraps its whole body in those context managers, every other
|
||||
thread in the process — including a gateway's asyncio event-loop thread driving a
|
||||
Telegram long-poll — sees ``sys.stdout``/``sys.stderr`` pointing at ``devnull``
|
||||
for the full duration. Any bare ``print`` / ``sys.stderr.write`` from those other
|
||||
threads is silently lost during that window (see issue #55769 / #55925).
|
||||
|
||||
This module installs a thin proxy as ``sys.stdout``/``sys.stderr`` that routes
|
||||
writes per-thread: threads registered as "silenced" go to a sink; every other
|
||||
thread passes through to the *original* stream. The proxy is installed once,
|
||||
idempotently, and is never uninstalled (uninstalling would race other threads
|
||||
mid-write), so the only observable effect for unregistered threads is one extra
|
||||
attribute lookup per write.
|
||||
``contextlib.redirect_stdout`` reassigns the *process-global* stream, so a
|
||||
daemon worker silencing itself also silences every other thread (gateway
|
||||
event loop included) for the duration. This module installs a per-thread
|
||||
routing proxy as ``sys.stdout``/``sys.stderr``: silenced threads write to a
|
||||
sink, everyone else passes through to the original stream. Installed once,
|
||||
idempotently, and never uninstalled (that would race other threads mid-write).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -27,12 +19,10 @@ from typing import Iterator, TextIO
|
||||
__all__ = ["thread_scoped_silence"]
|
||||
|
||||
_install_lock = threading.Lock()
|
||||
# Maps the proxy we installed for a given attribute ("stdout"/"stderr") so we
|
||||
# never double-wrap and so we can recover the original stream.
|
||||
# Proxy installed per attribute ("stdout"/"stderr"): never double-wrap.
|
||||
_installed: dict[str, "_ThreadRoutingStream"] = {}
|
||||
# One process-lifetime sink per stream. Temporary process-global redirects can
|
||||
# displace and later restore a routing proxy; they must not allocate another
|
||||
# permanent /dev/null descriptor every time that happens.
|
||||
# One process-lifetime sink per stream: global redirects that displace and
|
||||
# restore a proxy must not leak a new /dev/null descriptor each time.
|
||||
_sinks: dict[str, TextIO] = {}
|
||||
_routing_states: dict[str, "_RoutingState"] = {}
|
||||
|
||||
@@ -47,14 +37,8 @@ class _RoutingState:
|
||||
|
||||
|
||||
class _ThreadRoutingStream:
|
||||
"""A ``sys.stdout``/``sys.stderr`` stand-in that routes writes per-thread.
|
||||
|
||||
Threads whose ident is in ``_silenced`` write to ``_sink``; all other
|
||||
threads write to ``_passthrough`` (the original stream captured at install
|
||||
time). Attribute access for anything other than the methods we override
|
||||
is delegated to the *current* target so things like ``.encoding`` /
|
||||
``.fileno()`` behave like the underlying stream for the calling thread.
|
||||
"""
|
||||
"""``sys.stdout``/``sys.stderr`` stand-in routing writes per calling thread;
|
||||
unknown attributes delegate to the current thread's target."""
|
||||
|
||||
def __init__(self, passthrough: TextIO, state: _RoutingState) -> None:
|
||||
self._passthrough = passthrough
|
||||
@@ -65,7 +49,6 @@ class _ThreadRoutingStream:
|
||||
return self._state.sink
|
||||
return self._passthrough
|
||||
|
||||
# --- registration -----------------------------------------------------
|
||||
def silence(self, ident: int) -> None:
|
||||
with self._state.lock:
|
||||
self._state.silenced[ident] = self._state.silenced.get(ident, 0) + 1
|
||||
@@ -78,7 +61,6 @@ class _ThreadRoutingStream:
|
||||
else:
|
||||
self._state.silenced.pop(ident, None)
|
||||
|
||||
# --- file-like surface ------------------------------------------------
|
||||
def write(self, data): # type: ignore[no-untyped-def]
|
||||
try:
|
||||
return self._target().write(data)
|
||||
@@ -108,8 +90,6 @@ class _ThreadRoutingStream:
|
||||
return self._target().fileno()
|
||||
|
||||
def __getattr__(self, name): # type: ignore[no-untyped-def]
|
||||
# Delegate everything we don't override (encoding, buffer, mode, ...)
|
||||
# to the calling thread's current target.
|
||||
return getattr(self._target(), name)
|
||||
|
||||
|
||||
@@ -119,17 +99,15 @@ def _ensure_installed(attr: str, passthrough: TextIO) -> "_ThreadRoutingStream":
|
||||
proxy = _installed.get(attr)
|
||||
current = getattr(sys, attr, None)
|
||||
if isinstance(current, _ThreadRoutingStream):
|
||||
# A redirect context can restore an older routing proxy after a
|
||||
# temporary replacement. Adopt it instead of wrapping it and
|
||||
# growing an unbounded proxy chain.
|
||||
# A redirect context may restore an older proxy; adopt it rather
|
||||
# than wrapping it into an unbounded chain.
|
||||
_installed[attr] = current
|
||||
_routing_states[attr] = current._state
|
||||
return current
|
||||
if proxy is not None and current is proxy:
|
||||
return proxy
|
||||
# Capture whatever is currently bound as the passthrough. If a prior
|
||||
# global redirect_stdout is active, route non-silenced threads to that
|
||||
# stream to preserve the old behavior.
|
||||
# Route non-silenced threads to whatever is currently bound (an active
|
||||
# global redirect keeps its old behavior).
|
||||
passthrough = current if current is not None else passthrough
|
||||
sink = _sinks.get(attr)
|
||||
if sink is None or sink.closed:
|
||||
@@ -147,12 +125,7 @@ def _ensure_installed(attr: str, passthrough: TextIO) -> "_ThreadRoutingStream":
|
||||
|
||||
@contextlib.contextmanager
|
||||
def thread_scoped_silence() -> Iterator[None]:
|
||||
"""Silence ``stdout``/``stderr`` for the *current thread only*.
|
||||
|
||||
Other threads keep writing to the real streams. Use this around a worker
|
||||
thread's body instead of ``contextlib.redirect_stdout(devnull)`` when the
|
||||
process is multi-threaded and another thread must keep its console output.
|
||||
"""
|
||||
"""Silence ``stdout``/``stderr`` for the *current thread only*."""
|
||||
ident = threading.get_ident()
|
||||
out_proxy = _ensure_installed("stdout", sys.__stdout__ or sys.stdout)
|
||||
err_proxy = _ensure_installed("stderr", sys.__stderr__ or sys.stderr)
|
||||
|
||||
+205
-457
@@ -1,26 +1,12 @@
|
||||
"""Tool-dispatch helpers — parallelism gating, multimodal envelopes, mutation tracking.
|
||||
|
||||
Pure module-level utilities extracted from ``run_agent.py``:
|
||||
|
||||
* ``_is_destructive_command`` — terminal-command heuristic used to gate
|
||||
parallel batch dispatch.
|
||||
* ``_should_parallelize_tool_batch`` / ``_extract_parallel_scope_paths`` /
|
||||
``_extract_parallel_scope_path`` / ``_paths_overlap`` — the rules engine
|
||||
deciding when a multi-tool batch can run concurrently (V4A patch scope
|
||||
uses patch-body file headers, not a decoy ``path=``).
|
||||
* ``_is_multimodal_tool_result`` / ``_multimodal_text_summary`` /
|
||||
``_append_subdir_hint_to_multimodal`` — envelope helpers for the
|
||||
``{"_multimodal": True, "content": [...], "text_summary": ...}`` dict
|
||||
shape returned by tools like ``computer_use``.
|
||||
* ``_extract_file_mutation_targets`` / ``_extract_landed_file_mutation_paths`` /
|
||||
``_extract_error_preview`` —
|
||||
per-turn file-mutation verifier inputs.
|
||||
* ``_trajectory_normalize_msg`` — strip image blobs from a message for
|
||||
trajectory saving.
|
||||
|
||||
All helpers are stateless. ``run_agent`` re-exports each name so existing
|
||||
``from run_agent import ...`` imports in tests and other modules keep
|
||||
working unchanged.
|
||||
Stateless module-level utilities extracted from ``run_agent.py``, which
|
||||
re-exports each name so existing ``from run_agent import ...`` imports keep
|
||||
working. Groups: batch-parallelism planner (path-overlap admission; V4A patch
|
||||
scope comes from patch-body headers, not a decoy ``path=``), multimodal
|
||||
``{"_multimodal": True, "content": [...], "text_summary": ...}`` envelope
|
||||
helpers, per-turn file-mutation verifier inputs, trajectory normalisation, and
|
||||
the tool-result message constructor with its untrusted-content wrapping.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -40,8 +26,7 @@ from tools.threat_patterns import scan_for_threats
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Tools that must never run concurrently (interactive / user-facing).
|
||||
# When any of these appear in a batch, we fall back to sequential execution.
|
||||
# Interactive / user-facing tools never run concurrently: any of these in a batch is a barrier.
|
||||
_NEVER_PARALLEL_TOOLS = frozenset({"clarify"})
|
||||
|
||||
# Read-only tools with no shared mutable session state.
|
||||
@@ -60,16 +45,12 @@ _PARALLEL_SAFE_TOOLS = frozenset({
|
||||
"web_search",
|
||||
})
|
||||
|
||||
# Filesystem tools whose parallel admission is decided by path overlap.
|
||||
# Readers may share a subtree with other readers; a writer conflicts with
|
||||
# ANY overlapping reservation (reader or writer). This is what keeps a
|
||||
# batched ``search_files``/``read_file`` from observing pre-mutation file
|
||||
# state when the model batches it alongside the ``patch``/``write_file``
|
||||
# it depends on (the classic same-block write→read race).
|
||||
# Filesystem tools admitted by path overlap. Readers may share a subtree; a
|
||||
# writer conflicts with ANY overlapping reservation. This keeps a batched
|
||||
# read_file/search_files from observing pre-mutation state when the model
|
||||
# batches it alongside the patch/write_file it depends on.
|
||||
_PATH_SCOPED_READERS = frozenset({"read_file", "search_files"})
|
||||
_PATH_SCOPED_WRITERS = frozenset({"write_file", "patch"})
|
||||
|
||||
# File tools can run concurrently when they target independent paths.
|
||||
_PATH_SCOPED_TOOLS = _PATH_SCOPED_READERS | _PATH_SCOPED_WRITERS
|
||||
|
||||
# Patterns that indicate a terminal command may modify/delete files.
|
||||
@@ -92,47 +73,29 @@ _REDIRECT_OVERWRITE = re.compile(r'[^>]>[^>]|^>[^>]')
|
||||
|
||||
def _is_destructive_command(cmd: str) -> bool:
|
||||
"""Heuristic: does this terminal command look like it modifies/deletes files?"""
|
||||
if not cmd:
|
||||
return False
|
||||
if _DESTRUCTIVE_PATTERNS.search(cmd):
|
||||
return True
|
||||
if _REDIRECT_OVERWRITE.search(cmd):
|
||||
return True
|
||||
return False
|
||||
return bool(cmd) and bool(_DESTRUCTIVE_PATTERNS.search(cmd) or _REDIRECT_OVERWRITE.search(cmd))
|
||||
|
||||
|
||||
def _is_mcp_tool_parallel_safe(tool_name: str) -> bool:
|
||||
"""Check if an MCP tool comes from a server with parallel tool calls enabled.
|
||||
|
||||
Lazy-imports from ``tools.mcp_tool`` to avoid circular dependencies.
|
||||
Returns False if the MCP module is not available.
|
||||
"""
|
||||
"""Whether an MCP tool's server opted into parallel calls; False if MCP is unavailable."""
|
||||
try:
|
||||
from tools.mcp_tool import is_mcp_tool_parallel_safe
|
||||
from tools.mcp_tool import is_mcp_tool_parallel_safe # lazy: avoids import cycle
|
||||
return is_mcp_tool_parallel_safe(tool_name)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# Read-only bridge lookups: dispatch_tool_search / dispatch_tool_describe are
|
||||
# stateless catalog reads (the catalog is rebuilt from the current tool-defs
|
||||
# list on every call), so a batch of them can run concurrently.
|
||||
# Stateless catalog reads (rebuilt from the current tool-defs on every call) — parallel-safe.
|
||||
_PARALLEL_SAFE_BRIDGE_LOOKUPS = frozenset({"tool_search", "tool_describe"})
|
||||
|
||||
|
||||
def _peel_bridge_call(tool_name: str, function_args: dict) -> tuple[str, dict]:
|
||||
"""Resolve a ``tool_call`` bridge invocation to its underlying tool.
|
||||
"""Resolve a ``tool_call`` bridge invocation to ``(underlying_name, underlying_args)``.
|
||||
|
||||
The batch planner admits calls to a parallel run by tool NAME, but when
|
||||
tool search is active the model emits the literal name ``tool_call`` for
|
||||
every deferred tool — so a server opted in via
|
||||
``supports_parallel_tool_calls: true`` silently lost concurrency the
|
||||
moment the bridge activated. Peel the wrapper here so admission is
|
||||
decided on the underlying tool, exactly like the executors' unwrap.
|
||||
|
||||
Returns ``(underlying_name, underlying_args)`` when the wrapper parses
|
||||
cleanly, else ``(tool_name, function_args)`` unchanged — an unparseable
|
||||
bridge call stays a sequential barrier and fails at dispatch as before.
|
||||
With tool search active the model emits the literal name ``tool_call`` for
|
||||
every deferred tool, so admission must be decided on the underlying tool
|
||||
(as the executors' unwrap does). An unparseable bridge call is returned
|
||||
unchanged: it stays a sequential barrier and fails at dispatch as before.
|
||||
"""
|
||||
try:
|
||||
from tools.tool_search import TOOL_CALL_NAME, resolve_underlying_call
|
||||
@@ -146,147 +109,97 @@ def _peel_bridge_call(tool_name: str, function_args: dict) -> tuple[str, dict]:
|
||||
return tool_name, function_args
|
||||
|
||||
|
||||
def _batch_admission(tool_call, execution_cwd: Optional[Path]) -> tuple[str, List[Path], bool] | None:
|
||||
"""Classify one call for the planner: ``None`` = sequential barrier, else
|
||||
``(effective_name, scoped_paths, is_writer)`` (empty paths = unscoped parallel-safe)."""
|
||||
tool_name = tool_call.function.name
|
||||
if tool_name in _NEVER_PARALLEL_TOOLS:
|
||||
return None
|
||||
try:
|
||||
function_args = json.loads(tool_call.function.arguments)
|
||||
except Exception:
|
||||
_raw = tool_call.function.arguments
|
||||
logging.debug(
|
||||
"Could not parse args for %s — treating as sequential barrier; raw=%s",
|
||||
tool_name,
|
||||
_raw[:200] if isinstance(_raw, str) else repr(_raw)[:200],
|
||||
)
|
||||
return None
|
||||
if not isinstance(function_args, dict):
|
||||
logging.debug(
|
||||
"Non-dict args for %s (%s) — treating as sequential barrier",
|
||||
tool_name,
|
||||
type(function_args).__name__,
|
||||
)
|
||||
return None
|
||||
|
||||
name, args = _peel_bridge_call(tool_name, function_args)
|
||||
if name in _NEVER_PARALLEL_TOOLS:
|
||||
return None
|
||||
if name in _PATH_SCOPED_TOOLS:
|
||||
scoped = _extract_parallel_scope_paths(name, args, execution_cwd=execution_cwd)
|
||||
return (name, scoped, name in _PATH_SCOPED_WRITERS) if scoped else None
|
||||
if name in _PARALLEL_SAFE_TOOLS or name in _PARALLEL_SAFE_BRIDGE_LOOKUPS or _is_mcp_tool_parallel_safe(name):
|
||||
return name, [], False
|
||||
return None
|
||||
|
||||
|
||||
def _plan_tool_batch_segments(tool_calls, *, execution_cwd: Optional[Path] = None) -> List[tuple]:
|
||||
"""Split a tool-call batch into ordered ``(kind, calls)`` segments.
|
||||
"""Split a tool-call batch into ordered ``("parallel"|"sequential", calls)`` segments.
|
||||
|
||||
``kind`` is ``"parallel"`` (a maximal contiguous run of parallel-safe
|
||||
calls) or ``"sequential"`` (one or more barrier calls that must run
|
||||
in-order on the sequential path). Segments preserve the model's
|
||||
original call order exactly — a later call never crosses an earlier
|
||||
barrier — so tool-result ordering and side-effect boundaries are
|
||||
identical to fully-sequential execution. The per-call safety rules
|
||||
are the same ones the old all-or-nothing gate applied to the whole
|
||||
batch:
|
||||
|
||||
* ``_NEVER_PARALLEL_TOOLS`` (interactive tools) → barrier.
|
||||
* Unparseable / non-dict arguments → barrier.
|
||||
* Path-scoped tools (``read_file``/``search_files``/``write_file``/
|
||||
``patch``) join a parallel run only when their target path(s) do not
|
||||
CONFLICT with a path already reserved in the same run. Reservations
|
||||
carry a reader/writer role: reader↔reader overlap is harmless (two
|
||||
reads of the same file commute) and stays parallel; any overlap
|
||||
involving a writer closes the run so the conflicting call starts a
|
||||
NEW run after the first completes. ``search_files`` reserves its
|
||||
search root (default ``.``) as a reader — a search batched after a
|
||||
write into the searched subtree is ordered behind that write instead
|
||||
of racing it. For V4A ``patch(mode="patch")`` the reserved paths are
|
||||
the file headers in the patch body, not a possibly-stale ``path=``
|
||||
argument.
|
||||
* Anything not in ``_PARALLEL_SAFE_TOOLS`` and not an opted-in MCP
|
||||
tool → barrier.
|
||||
|
||||
Parallel runs shorter than two calls are demoted to sequential (no
|
||||
concurrency win, and the sequential executor owns the richer inline
|
||||
dispatch), and adjacent sequential segments are merged.
|
||||
Segments preserve the model's call order exactly — a later call never
|
||||
crosses an earlier barrier — so result ordering and side-effect boundaries
|
||||
match fully-sequential execution. Barriers: ``_NEVER_PARALLEL_TOOLS``,
|
||||
unparseable/non-dict args, and anything not parallel-safe (built-in list,
|
||||
bridge lookups, opted-in MCP tools). Path-scoped tools join a run only when
|
||||
their paths don't conflict with the run's reservations: reader↔reader
|
||||
overlap commutes and stays parallel; any overlap involving a writer closes
|
||||
the run so the call starts a NEW run after the conflicting one lands.
|
||||
``search_files`` reserves its root (default ``.``) as a reader. Parallel
|
||||
runs shorter than two calls demote to sequential (the sequential executor
|
||||
owns the richer inline dispatch); adjacent sequential segments merge.
|
||||
"""
|
||||
segments: list[list] = [] # [kind, calls] pairs, normalized to tuples on return
|
||||
segments: List[tuple] = []
|
||||
current: list = []
|
||||
# (canonical_path, is_writer) reservations for the current parallel run.
|
||||
reserved_paths: list[tuple[Path, bool]] = []
|
||||
reserved_paths: list[tuple[Path, bool]] = [] # (canonical_path, is_writer) for the current run
|
||||
|
||||
def _close_parallel() -> None:
|
||||
nonlocal current, reserved_paths
|
||||
if current:
|
||||
segments.append(["parallel", current])
|
||||
current = []
|
||||
reserved_paths = []
|
||||
if len(current) >= 2:
|
||||
segments.append(("parallel", current))
|
||||
elif current:
|
||||
_extend_sequential(current)
|
||||
current = []
|
||||
reserved_paths = []
|
||||
|
||||
def _add_sequential(tc) -> None:
|
||||
_close_parallel()
|
||||
def _extend_sequential(calls: list) -> None:
|
||||
if segments and segments[-1][0] == "sequential":
|
||||
segments[-1][1].append(tc)
|
||||
segments[-1][1].extend(calls)
|
||||
else:
|
||||
segments.append(["sequential", [tc]])
|
||||
segments.append(("sequential", list(calls)))
|
||||
|
||||
for tool_call in tool_calls:
|
||||
tool_name = tool_call.function.name
|
||||
|
||||
if tool_name in _NEVER_PARALLEL_TOOLS:
|
||||
_add_sequential(tool_call)
|
||||
admission = _batch_admission(tool_call, execution_cwd)
|
||||
if admission is None:
|
||||
_close_parallel()
|
||||
_extend_sequential([tool_call])
|
||||
continue
|
||||
|
||||
try:
|
||||
function_args = json.loads(tool_call.function.arguments)
|
||||
except Exception:
|
||||
_raw = tool_call.function.arguments
|
||||
logging.debug(
|
||||
"Could not parse args for %s — treating as sequential barrier; raw=%s",
|
||||
tool_name,
|
||||
_raw[:200] if isinstance(_raw, str) else repr(_raw)[:200],
|
||||
)
|
||||
_add_sequential(tool_call)
|
||||
continue
|
||||
if not isinstance(function_args, dict):
|
||||
logging.debug(
|
||||
"Non-dict args for %s (%s) — treating as sequential barrier",
|
||||
tool_name,
|
||||
type(function_args).__name__,
|
||||
)
|
||||
_add_sequential(tool_call)
|
||||
continue
|
||||
|
||||
# Bridge unwrap: admission is decided on the UNDERLYING tool, not on
|
||||
# the literal wrapper name the model emitted. Read-only bridge
|
||||
# lookups (tool_search / tool_describe) are parallel-safe as-is.
|
||||
effective_name, effective_args = _peel_bridge_call(tool_name, function_args)
|
||||
|
||||
if effective_name in _NEVER_PARALLEL_TOOLS:
|
||||
_add_sequential(tool_call)
|
||||
continue
|
||||
|
||||
if effective_name in _PATH_SCOPED_TOOLS:
|
||||
scoped_paths = _extract_parallel_scope_paths(
|
||||
effective_name, effective_args, execution_cwd=execution_cwd
|
||||
)
|
||||
if not scoped_paths:
|
||||
_add_sequential(tool_call)
|
||||
continue
|
||||
is_writer = effective_name in _PATH_SCOPED_WRITERS
|
||||
if any(
|
||||
(is_writer or existing_is_writer)
|
||||
and _paths_overlap(scoped_path, existing)
|
||||
for scoped_path in scoped_paths
|
||||
for existing, existing_is_writer in reserved_paths
|
||||
):
|
||||
# Same-subtree conflict inside this run: close it so this
|
||||
# call starts a fresh run AFTER the conflicting one lands.
|
||||
# Reader↔reader overlap never conflicts — concurrent reads
|
||||
# of the same subtree commute.
|
||||
_close_parallel()
|
||||
reserved_paths.extend((p, is_writer) for p in scoped_paths)
|
||||
current.append(tool_call)
|
||||
continue
|
||||
|
||||
if (
|
||||
effective_name in _PARALLEL_SAFE_TOOLS
|
||||
or effective_name in _PARALLEL_SAFE_BRIDGE_LOOKUPS
|
||||
or _is_mcp_tool_parallel_safe(effective_name)
|
||||
_name, scoped_paths, is_writer = admission
|
||||
if any(
|
||||
(is_writer or existing_is_writer) and _paths_overlap(scoped_path, existing)
|
||||
for scoped_path in scoped_paths
|
||||
for existing, existing_is_writer in reserved_paths
|
||||
):
|
||||
current.append(tool_call)
|
||||
continue
|
||||
|
||||
_add_sequential(tool_call)
|
||||
_close_parallel()
|
||||
reserved_paths.extend((p, is_writer) for p in scoped_paths)
|
||||
current.append(tool_call)
|
||||
|
||||
_close_parallel()
|
||||
|
||||
normalized: list[list] = []
|
||||
for kind, calls in segments:
|
||||
if kind == "parallel" and len(calls) < 2:
|
||||
kind = "sequential"
|
||||
if normalized and normalized[-1][0] == "sequential" and kind == "sequential":
|
||||
normalized[-1][1].extend(calls)
|
||||
else:
|
||||
normalized.append([kind, calls])
|
||||
return [(kind, calls) for kind, calls in normalized]
|
||||
return segments
|
||||
|
||||
|
||||
def _should_parallelize_tool_batch(tool_calls) -> bool:
|
||||
"""Return True when the WHOLE tool-call batch is safe to run concurrently.
|
||||
|
||||
Thin view over ``_plan_tool_batch_segments`` kept for callers/tests that
|
||||
only care about the homogeneous case: True iff the planner produces a
|
||||
single all-parallel segment.
|
||||
"""
|
||||
"""True iff the planner yields a single all-parallel segment for the WHOLE batch."""
|
||||
if len(tool_calls) <= 1:
|
||||
return False
|
||||
segments = _plan_tool_batch_segments(tool_calls)
|
||||
@@ -294,19 +207,13 @@ def _should_parallelize_tool_batch(tool_calls) -> bool:
|
||||
|
||||
|
||||
def _canonical_path(raw_path: str, execution_cwd: Optional[Path] = None) -> Path:
|
||||
"""Return a canonical, OS-aware path for overlap detection.
|
||||
|
||||
Uses ``os.path.realpath`` to resolve symlinks on existing path components
|
||||
and ``os.path.normcase`` for case-insensitive platforms (Windows).
|
||||
Falls back to ``Path.cwd()`` when *execution_cwd* is not supplied.
|
||||
"""
|
||||
"""Canonical, OS-aware path for overlap detection (realpath for symlinks on
|
||||
existing components, normcase for case-insensitive platforms); relative
|
||||
paths resolve against *execution_cwd* or ``Path.cwd()``."""
|
||||
expanded = Path(raw_path).expanduser()
|
||||
base = execution_cwd if execution_cwd is not None else Path.cwd()
|
||||
candidate = expanded if expanded.is_absolute() else base / expanded
|
||||
# realpath resolves symlinks on path components that exist; for
|
||||
# not-yet-created files it canonicalises as far as possible.
|
||||
resolved = os.path.normcase(os.path.realpath(os.path.abspath(str(candidate))))
|
||||
return Path(resolved)
|
||||
return Path(os.path.normcase(os.path.realpath(os.path.abspath(str(candidate)))))
|
||||
|
||||
|
||||
def _extract_parallel_scope_paths(
|
||||
@@ -314,17 +221,12 @@ def _extract_parallel_scope_paths(
|
||||
function_args: dict,
|
||||
execution_cwd: Optional[Path] = None,
|
||||
) -> List[Path]:
|
||||
"""Return every canonical path this call reserves for overlap checks.
|
||||
"""Every canonical path this call reserves for overlap checks.
|
||||
|
||||
*execution_cwd* should be the working directory that the tool will
|
||||
actually use at runtime. When omitted the process cwd is used,
|
||||
which may differ from the tool execution environment on some
|
||||
platforms (e.g. WSL, sandboxed sub-processes).
|
||||
|
||||
For ``patch`` in V4A ``mode=patch``, scope comes from patch-body
|
||||
``*** Update/Add/Delete/Move File:`` headers (not a possibly-decoy
|
||||
``path=``). An empty result means the planner cannot determine the
|
||||
scope and must treat the call as a sequential barrier.
|
||||
*execution_cwd* should be the cwd the tool will actually use (may differ
|
||||
from the process cwd on WSL / sandboxed backends). For V4A ``patch`` the
|
||||
scope comes from patch-body file headers. An empty result means the scope
|
||||
is unknown and the planner must treat the call as a sequential barrier.
|
||||
"""
|
||||
if tool_name not in _PATH_SCOPED_TOOLS:
|
||||
return []
|
||||
@@ -337,25 +239,15 @@ def _extract_parallel_scope_paths(
|
||||
if isinstance(raw_path, str) and raw_path.strip():
|
||||
raw_paths.append(raw_path)
|
||||
elif tool_name == "search_files":
|
||||
# ``search_files`` defaults its search root to the cwd when
|
||||
# ``path`` is omitted — reserve that root rather than falling
|
||||
# back to a sequential barrier (an empty result here would
|
||||
# demote every bare search to a barrier and destroy read
|
||||
# parallelism).
|
||||
# search_files defaults its root to the cwd; reserve that rather than
|
||||
# demoting every bare search to a barrier.
|
||||
raw_paths.append(".")
|
||||
|
||||
scoped: List[Path] = []
|
||||
seen: set[str] = set()
|
||||
for raw in raw_paths:
|
||||
if not isinstance(raw, str) or not raw.strip():
|
||||
continue
|
||||
canonical = _canonical_path(raw, execution_cwd)
|
||||
key = str(canonical)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
scoped.append(canonical)
|
||||
return scoped
|
||||
# dict.fromkeys dedupes while preserving first-seen order.
|
||||
return list(dict.fromkeys(
|
||||
_canonical_path(raw, execution_cwd)
|
||||
for raw in raw_paths if isinstance(raw, str) and raw.strip()
|
||||
))
|
||||
|
||||
|
||||
def _extract_parallel_scope_path(
|
||||
@@ -363,41 +255,24 @@ def _extract_parallel_scope_path(
|
||||
function_args: dict,
|
||||
execution_cwd: Optional[Path] = None,
|
||||
) -> Optional[Path]:
|
||||
"""Return the primary canonical file target for path-scoped tools.
|
||||
|
||||
Thin view over ``_extract_parallel_scope_paths`` kept for callers/tests
|
||||
that only need a single representative path. For multi-file V4A
|
||||
patches this is the first header target.
|
||||
"""
|
||||
scoped = _extract_parallel_scope_paths(
|
||||
tool_name, function_args, execution_cwd=execution_cwd
|
||||
)
|
||||
"""Primary canonical target (first header target for multi-file V4A patches), or None."""
|
||||
scoped = _extract_parallel_scope_paths(tool_name, function_args, execution_cwd=execution_cwd)
|
||||
return scoped[0] if scoped else None
|
||||
|
||||
|
||||
def _paths_overlap(left: Path, right: Path) -> bool:
|
||||
"""Return True when two paths may refer to the same subtree.
|
||||
|
||||
Both *left* and *right* must already be canonical (as returned by
|
||||
``_extract_parallel_scope_paths`` / ``_canonical_path``) so that
|
||||
symlink aliases and case differences are already normalised.
|
||||
"""
|
||||
"""True when two already-canonical paths may refer to the same subtree."""
|
||||
left_parts = left.parts
|
||||
right_parts = right.parts
|
||||
if not left_parts or not right_parts:
|
||||
# Empty paths shouldn't reach here (guarded upstream), but be safe.
|
||||
# Empty paths are guarded upstream; only two non-empty equal prefixes overlap.
|
||||
return bool(left_parts) == bool(right_parts) and bool(left_parts)
|
||||
common_len = min(len(left_parts), len(right_parts))
|
||||
return left_parts[:common_len] == right_parts[:common_len]
|
||||
|
||||
|
||||
def _is_multimodal_tool_result(value: Any) -> bool:
|
||||
"""True if the value is a multimodal tool result envelope.
|
||||
|
||||
Multimodal handlers (e.g. tools/computer_use) return a dict with
|
||||
`_multimodal=True`, a `content` key holding OpenAI-style content
|
||||
parts, and an optional `text_summary` for string-only fallbacks.
|
||||
"""
|
||||
"""True for the multimodal envelope: dict with ``_multimodal=True`` and a ``content`` list."""
|
||||
return (
|
||||
isinstance(value, dict)
|
||||
and value.get("_multimodal") is True
|
||||
@@ -405,23 +280,17 @@ def _is_multimodal_tool_result(value: Any) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _multimodal_text_summary(value: Any) -> str:
|
||||
"""Extract a plain text view of a multimodal tool result.
|
||||
def _is_text_part(p: Any) -> bool:
|
||||
return isinstance(p, dict) and p.get("type") == "text"
|
||||
|
||||
Used wherever downstream code needs a string — logging, previews,
|
||||
persistence size heuristics, fall-back content for providers that
|
||||
don't support multipart tool messages.
|
||||
"""
|
||||
|
||||
def _multimodal_text_summary(value: Any) -> str:
|
||||
"""Plain-text view of a tool result (logging, previews, string-only providers)."""
|
||||
if _is_multimodal_tool_result(value):
|
||||
if value.get("text_summary"):
|
||||
return str(value["text_summary"])
|
||||
parts = []
|
||||
for p in value.get("content") or []:
|
||||
if isinstance(p, dict) and p.get("type") == "text":
|
||||
parts.append(str(p.get("text", "")))
|
||||
if parts:
|
||||
return "\n".join(parts)
|
||||
return "[multimodal tool result]"
|
||||
parts = [str(p.get("text", "")) for p in value.get("content") or [] if _is_text_part(p)]
|
||||
return "\n".join(parts) if parts else "[multimodal tool result]"
|
||||
if isinstance(value, str):
|
||||
return value
|
||||
try:
|
||||
@@ -431,17 +300,12 @@ def _multimodal_text_summary(value: Any) -> str:
|
||||
|
||||
|
||||
def _append_subdir_hint_to_multimodal(value: Dict[str, Any], hint: str) -> None:
|
||||
"""Mutate a multimodal tool-result envelope to append a subdir hint.
|
||||
|
||||
The hint is added to the first text part so the model sees it; image
|
||||
parts are left untouched. `text_summary` is also updated for
|
||||
string-fallback callers.
|
||||
"""
|
||||
"""Append a subdir hint to the envelope's first text part (and ``text_summary``) in place."""
|
||||
if not _is_multimodal_tool_result(value):
|
||||
return
|
||||
parts = value.get("content") or []
|
||||
for p in parts:
|
||||
if isinstance(p, dict) and p.get("type") == "text":
|
||||
if _is_text_part(p):
|
||||
p["text"] = str(p.get("text", "")) + hint
|
||||
break
|
||||
else:
|
||||
@@ -451,52 +315,34 @@ def _append_subdir_hint_to_multimodal(value: Dict[str, Any], hint: str) -> None:
|
||||
value["text_summary"] = value["text_summary"] + hint
|
||||
|
||||
|
||||
def _extract_file_mutation_targets(tool_name: str, args: Dict[str, Any]) -> List[str]:
|
||||
"""Return the file paths a ``write_file`` or ``patch`` call is targeting.
|
||||
# ``\s*`` (not ``\s+``) after ``***`` matches patch_parser / file_tools, which
|
||||
# accept ``***Update File:`` with no space.
|
||||
_V4A_FILE_HEADER = re.compile(r'^\*\*\*\s*(?:Update|Add|Delete)\s+File:\s*(.+)$', re.MULTILINE)
|
||||
_V4A_MOVE_HEADER = re.compile(r'^\*\*\*\s*Move\s+File:\s*(.+?)\s*->\s*(.+)$', re.MULTILINE)
|
||||
|
||||
For ``write_file`` and ``patch`` in replace mode this is just ``args["path"]``.
|
||||
For ``patch`` in V4A patch mode we parse the patch content for
|
||||
``*** Update File:`` / ``*** Add File:`` / ``*** Delete File:`` headers so
|
||||
the verifier can track each file in a multi-file patch separately.
|
||||
|
||||
def _extract_file_mutation_targets(tool_name: str, args: Dict[str, Any]) -> List[str]:
|
||||
"""File paths a ``write_file`` / ``patch`` call targets.
|
||||
|
||||
Replace mode uses ``args["path"]``; V4A patch mode parses the
|
||||
``*** Update/Add/Delete/Move File:`` headers so each file in a multi-file
|
||||
patch is tracked separately.
|
||||
"""
|
||||
if tool_name not in _FILE_MUTATING_TOOLS:
|
||||
return []
|
||||
if tool_name == "write_file":
|
||||
p = args.get("path")
|
||||
return [str(p)] if p else []
|
||||
# tool_name == "patch"
|
||||
mode = args.get("mode") or "replace"
|
||||
mode = "replace" if tool_name == "write_file" else (args.get("mode") or "replace")
|
||||
if mode == "replace":
|
||||
p = args.get("path")
|
||||
return [str(p)] if p else []
|
||||
if mode == "patch":
|
||||
body = args.get("patch") or ""
|
||||
if not isinstance(body, str) or not body:
|
||||
return []
|
||||
paths: List[str] = []
|
||||
# ``\s*`` (not ``\s+``) after ``***`` matches patch_parser / file_tools:
|
||||
# they accept ``***Update File:`` with no space after the asterisks.
|
||||
for _m in re.finditer(
|
||||
r'^\*\*\*\s*(?:Update|Add|Delete)\s+File:\s*(.+)$',
|
||||
body,
|
||||
re.MULTILINE,
|
||||
):
|
||||
p = _m.group(1).strip()
|
||||
if p:
|
||||
paths.append(p)
|
||||
for _m in re.finditer(
|
||||
r'^\*\*\*\s*Move\s+File:\s*(.+?)\s*->\s*(.+)$',
|
||||
body,
|
||||
re.MULTILINE,
|
||||
):
|
||||
src = _m.group(1).strip()
|
||||
dst = _m.group(2).strip()
|
||||
if src:
|
||||
paths.append(src)
|
||||
if dst:
|
||||
paths.append(dst)
|
||||
return paths
|
||||
return []
|
||||
if mode != "patch":
|
||||
return []
|
||||
body = args.get("patch") or ""
|
||||
if not isinstance(body, str) or not body:
|
||||
return []
|
||||
paths = [m.group(1).strip() for m in _V4A_FILE_HEADER.finditer(body)]
|
||||
for m in _V4A_MOVE_HEADER.finditer(body):
|
||||
paths.extend((m.group(1).strip(), m.group(2).strip()))
|
||||
return [p for p in paths if p]
|
||||
|
||||
|
||||
def _extract_landed_file_mutation_paths(
|
||||
@@ -504,7 +350,8 @@ def _extract_landed_file_mutation_paths(
|
||||
args: Dict[str, Any],
|
||||
result: Any,
|
||||
) -> List[str]:
|
||||
"""Return the concrete file paths a successful mutation reports."""
|
||||
"""Concrete file paths a successful mutation reports (``files_modified`` /
|
||||
``resolved_path`` in the JSON result), falling back to the declared targets."""
|
||||
targets = _extract_file_mutation_targets(tool_name, args)
|
||||
if tool_name not in _FILE_MUTATING_TOOLS or not isinstance(result, str):
|
||||
return targets
|
||||
@@ -516,28 +363,17 @@ def _extract_landed_file_mutation_paths(
|
||||
return targets
|
||||
|
||||
files = data.get("files_modified")
|
||||
if isinstance(files, list):
|
||||
landed = [str(p) for p in files if p]
|
||||
if landed:
|
||||
return landed
|
||||
|
||||
landed = [str(p) for p in files if p] if isinstance(files, list) else []
|
||||
if landed:
|
||||
return landed
|
||||
resolved = data.get("resolved_path")
|
||||
if resolved:
|
||||
return [str(resolved)]
|
||||
|
||||
return targets
|
||||
return [str(resolved)] if resolved else targets
|
||||
|
||||
|
||||
def _extract_error_preview(result: Any, max_len: int = 180) -> str:
|
||||
"""Pull a one-line error summary out of a tool result for footer display."""
|
||||
"""One-line error summary of a tool result for footer display."""
|
||||
text = _multimodal_text_summary(result) if result is not None else ""
|
||||
if not isinstance(text, str):
|
||||
try:
|
||||
text = str(text)
|
||||
except Exception:
|
||||
return ""
|
||||
# Try to parse JSON and pull the ``error`` field — tool handlers return
|
||||
# ``{"success": false, "error": "..."}``; raw string wins if parse fails.
|
||||
# Handlers return {"success": false, "error": "..."}; the raw string wins if parse fails.
|
||||
stripped = text.strip()
|
||||
if stripped.startswith("{"):
|
||||
try:
|
||||
@@ -546,7 +382,6 @@ def _extract_error_preview(result: Any, max_len: int = 180) -> str:
|
||||
text = data["error"]
|
||||
except Exception:
|
||||
pass
|
||||
# Collapse whitespace, trim to max_len.
|
||||
text = " ".join(text.split())
|
||||
if len(text) > max_len:
|
||||
text = text[: max_len - 1] + "…"
|
||||
@@ -554,25 +389,20 @@ def _extract_error_preview(result: Any, max_len: int = 180) -> str:
|
||||
|
||||
|
||||
def _trajectory_normalize_msg(msg: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Strip image blobs from a message for trajectory saving.
|
||||
|
||||
Returns a shallow copy with multimodal tool results replaced by their
|
||||
text_summary, and image parts in content lists replaced by
|
||||
`[screenshot]` placeholders. Keeps the message schema otherwise intact.
|
||||
"""
|
||||
"""Shallow copy with image blobs stripped for trajectory saving: multimodal
|
||||
results become their text summary, image parts become ``[screenshot]``."""
|
||||
if not isinstance(msg, dict):
|
||||
return msg
|
||||
content = msg.get("content")
|
||||
if _is_multimodal_tool_result(content):
|
||||
return {**msg, "content": _multimodal_text_summary(content)}
|
||||
if isinstance(content, list):
|
||||
cleaned = []
|
||||
for p in content:
|
||||
if isinstance(p, dict) and p.get("type") in {"image", "image_url", "input_image"}:
|
||||
cleaned.append({"type": "text", "text": "[screenshot]"})
|
||||
else:
|
||||
cleaned.append(p)
|
||||
return {**msg, "content": cleaned}
|
||||
return {**msg, "content": [
|
||||
{"type": "text", "text": "[screenshot]"}
|
||||
if isinstance(p, dict) and p.get("type") in {"image", "image_url", "input_image"}
|
||||
else p
|
||||
for p in content
|
||||
]}
|
||||
return msg
|
||||
|
||||
|
||||
@@ -590,33 +420,19 @@ def make_tool_result_message(
|
||||
*,
|
||||
effect_disposition: str | None = None,
|
||||
) -> dict:
|
||||
"""Build a tool-result message dict with both the OpenAI-format ``name``
|
||||
field (required by the wire format and provider adapters) and the internal
|
||||
``tool_name`` field (written to the session DB messages table).
|
||||
"""Build a tool-result message with the OpenAI ``name`` field (wire format)
|
||||
and the internal ``tool_name`` field (session DB).
|
||||
|
||||
Content from high-risk tools (``web_extract``, ``web_search``, ``browser_*``,
|
||||
``mcp_*``) gets wrapped in semantic delimiters telling the model the content
|
||||
is untrusted data, not instructions. This is the architectural defense
|
||||
against indirect prompt injection from poisoned web pages, GitHub issues,
|
||||
and MCP responses — it changes how the model interprets the content rather
|
||||
than relying on regex pattern matching catching every payload.
|
||||
|
||||
Wrapping applies to plain string content and to multimodal content
|
||||
lists (``[{"type": "text", "text": "..."}, {"type": "image_url", ...}]``):
|
||||
each text-type part is wrapped individually using the same rules as plain
|
||||
string content (short text passes through unchanged; longer text is
|
||||
neutralized and framed). Non-text parts (e.g. image_url) are preserved.
|
||||
The outer list itself is rebuilt rather than returned by identity, so
|
||||
callers should compare by value, not by ``is``.
|
||||
Content from high-risk tools (web_extract, web_search, browser_*, mcp_*) is
|
||||
wrapped in untrusted-data delimiters — the architectural defense against
|
||||
indirect prompt injection; see ``_maybe_wrap_untrusted``.
|
||||
"""
|
||||
# Keep the constructor safe for every caller, including replay recovery
|
||||
# paths that do not go through the live executor's canonical-id helper.
|
||||
# Replay-recovery callers bypass the executor's canonical-id helper, so normalize here too.
|
||||
tool_call_id = _normalize_tool_call_id(tool_call_id)
|
||||
|
||||
# Order matters: detect provider-side elision on the RAW content and
|
||||
# append the notice first, THEN wrap — so the notice lives inside the
|
||||
# untrusted block next to the data it describes, appended exactly once
|
||||
# at construction time (cache-safe).
|
||||
# Order matters: detect elision on the RAW content and append the notice
|
||||
# first, THEN wrap, so the notice sits inside the untrusted block next to
|
||||
# the data it describes — once, at construction time (cache-safe).
|
||||
wrapped = _maybe_wrap_untrusted(name, _maybe_append_elision_notice(name, content))
|
||||
message = stamp_message_timestamp({
|
||||
"role": "tool",
|
||||
@@ -637,63 +453,41 @@ def make_tool_result_message(
|
||||
return message
|
||||
|
||||
|
||||
# Tools whose results carry attacker-controllable content. Wrapping their
|
||||
# string output in ``<untrusted_tool_result>`` delimiters tells the model the
|
||||
# payload is data, not instructions — the architectural piece of the
|
||||
# promptware defense. Skipped for short outputs (under 32 chars) where the
|
||||
# overhead of the wrapper outweighs any indirect-injection risk.
|
||||
_UNTRUSTED_TOOL_NAMES = frozenset({
|
||||
"web_extract",
|
||||
"web_search",
|
||||
})
|
||||
|
||||
_UNTRUSTED_TOOL_PREFIXES = (
|
||||
"browser_",
|
||||
"mcp_",
|
||||
)
|
||||
|
||||
# Tools whose results carry attacker-controllable content. Short outputs
|
||||
# (under 32 chars) skip wrapping: the overhead outweighs any injection risk.
|
||||
_UNTRUSTED_TOOL_NAMES = frozenset({"web_extract", "web_search"})
|
||||
_UNTRUSTED_TOOL_PREFIXES = ("browser_", "mcp_")
|
||||
_UNTRUSTED_WRAP_MIN_CHARS = 32
|
||||
|
||||
# Matches the delimiter token in any case so attacker content can't forge or
|
||||
# prematurely close the boundary with a differently-cased variant the model
|
||||
# would still read as a tag (e.g. ``</UNTRUSTED_TOOL_RESULT>``).
|
||||
# Case-insensitive so attacker content can't forge or prematurely close the
|
||||
# boundary with a differently-cased tag the model would still read as one.
|
||||
_DELIMITER_TOKEN_RE = re.compile(r"untrusted_tool_result", re.IGNORECASE)
|
||||
|
||||
|
||||
def _is_untrusted_tool(name: Optional[str]) -> bool:
|
||||
if not name:
|
||||
return False
|
||||
if name in _UNTRUSTED_TOOL_NAMES:
|
||||
return True
|
||||
return any(name.startswith(p) for p in _UNTRUSTED_TOOL_PREFIXES)
|
||||
return bool(name) and (name in _UNTRUSTED_TOOL_NAMES or name.startswith(_UNTRUSTED_TOOL_PREFIXES))
|
||||
|
||||
|
||||
# --- Upstream-elision detection --------------------------------------------
|
||||
#
|
||||
# Some MCP servers elide data SERVER-SIDE and mark the elision inside the
|
||||
# payload itself (e.g. Composio: '...13 more items' inside a JSON array,
|
||||
# '"has_more": true', 'Complete response was large (N tokens). Full data
|
||||
# saved to sandbox in /mnt/files/...', 'data_preview' envelopes). Because the
|
||||
# result looks structurally complete, models treat the visible slice as the
|
||||
# whole dataset and falsely claim completeness. When one of these markers is
|
||||
# present, we append ONE compact notice at result-construction time — before
|
||||
# the message enters history, never mutated later, so prompt caching is safe.
|
||||
def _is_text_item(item: Any) -> bool:
|
||||
return _is_text_part(item) and isinstance(item.get("text"), str)
|
||||
|
||||
# Conservative patterns only: each one is an explicit provider-side "there is
|
||||
# more data than what you can see" signal, not a generic truncation heuristic.
|
||||
|
||||
# --- Upstream-elision detection ---
|
||||
# Some MCP servers elide data SERVER-SIDE and mark it inside the payload
|
||||
# ('...13 more items', '"has_more": true', 'saved to sandbox', 'data_preview'
|
||||
# envelopes). The result looks structurally complete, so models treat the
|
||||
# visible slice as the whole dataset. Conservative, explicit markers only —
|
||||
# not a generic truncation heuristic. One notice is appended at construction
|
||||
# time, never mutated later (prompt-cache safe).
|
||||
_UPSTREAM_ELISION_PATTERNS = (
|
||||
re.compile(r"\.\.\.\s*\d+\s+more\s+items?", re.IGNORECASE),
|
||||
re.compile(r'"has_more"\s*:\s*true', re.IGNORECASE),
|
||||
re.compile(r"saved to sandbox", re.IGNORECASE),
|
||||
re.compile(r"data_preview", re.IGNORECASE),
|
||||
)
|
||||
|
||||
# Results smaller than this can't meaningfully hide an elided enumeration —
|
||||
# skip the scan entirely so tiny results pay nothing.
|
||||
# Tiny results can't hide an elided enumeration; markers for the sizes that
|
||||
# matter (20-50K) are always inside the first 64KB.
|
||||
_ELISION_SCAN_MIN_CHARS = 1_000
|
||||
|
||||
# Bound the regex scan: markers appear near the elided structure, which for
|
||||
# the payload sizes that matter (20-50K) is always inside the first 64KB.
|
||||
_ELISION_SCAN_MAX_CHARS = 65_536
|
||||
|
||||
_UPSTREAM_ELISION_NOTICE = (
|
||||
@@ -704,53 +498,31 @@ _UPSTREAM_ELISION_NOTICE = (
|
||||
|
||||
|
||||
def _detect_upstream_elision(content: Any) -> bool:
|
||||
"""True when a string tool result carries provider-side elision markers.
|
||||
|
||||
Cheap and safe by construction: non-string content is never scanned,
|
||||
results under ``_ELISION_SCAN_MIN_CHARS`` short-circuit, and the regex
|
||||
scan is capped at the first ``_ELISION_SCAN_MAX_CHARS`` chars.
|
||||
"""
|
||||
if not isinstance(content, str):
|
||||
return False
|
||||
if len(content) < _ELISION_SCAN_MIN_CHARS:
|
||||
"""True when a string result carries provider-side elision markers (bounded scan)."""
|
||||
if not isinstance(content, str) or len(content) < _ELISION_SCAN_MIN_CHARS:
|
||||
return False
|
||||
window = content[:_ELISION_SCAN_MAX_CHARS]
|
||||
return any(p.search(window) for p in _UPSTREAM_ELISION_PATTERNS)
|
||||
|
||||
|
||||
def _maybe_append_elision_notice(name: str, content: Any) -> Any:
|
||||
"""Append the incompleteness notice to untrusted string results that
|
||||
embed upstream elision markers. Returns ``content`` unchanged otherwise.
|
||||
|
||||
Runs on the RAW result before untrusted-wrapping so the notice sits with
|
||||
the data it describes, and only at result-construction time (cache-safe).
|
||||
"""
|
||||
if not _is_untrusted_tool(name):
|
||||
return content
|
||||
if _detect_upstream_elision(content):
|
||||
"""Append the incompleteness notice to untrusted string results with elision markers."""
|
||||
if _is_untrusted_tool(name) and _detect_upstream_elision(content):
|
||||
return content + _UPSTREAM_ELISION_NOTICE
|
||||
return content
|
||||
|
||||
|
||||
def _tool_output_risk_metadata(name: str, content: Any) -> Optional[Dict[str, Any]]:
|
||||
"""Classify textual attacker-controlled output without retaining a copy.
|
||||
"""Internal-only advisory classification of attacker-controlled output.
|
||||
|
||||
The advisory metadata is internal-only. It records deterministic finding
|
||||
identifiers, never blocks or redacts the normal result, and deliberately
|
||||
omits raw scanned text.
|
||||
Records deterministic finding ids, never blocks or redacts, and omits the scanned text.
|
||||
"""
|
||||
if not _is_untrusted_tool(name):
|
||||
return None
|
||||
if isinstance(content, str):
|
||||
text_parts = [content]
|
||||
elif isinstance(content, list):
|
||||
text_parts = [
|
||||
item["text"]
|
||||
for item in content
|
||||
if isinstance(item, dict)
|
||||
and item.get("type") == "text"
|
||||
and isinstance(item.get("text"), str)
|
||||
]
|
||||
text_parts = [item["text"] for item in content if _is_text_item(item)]
|
||||
if not text_parts:
|
||||
return None
|
||||
else:
|
||||
@@ -769,40 +541,20 @@ def _tool_output_risk_metadata(name: str, content: Any) -> Optional[Dict[str, An
|
||||
|
||||
|
||||
def _neutralize_delimiters(content: str) -> str:
|
||||
"""Defang any literal ``untrusted_tool_result`` delimiter embedded in
|
||||
attacker-controlled content so it can't break out of the wrapper.
|
||||
|
||||
Without this, a poisoned web page / GitHub issue / MCP response that
|
||||
contains ``</untrusted_tool_result>`` would close the trust boundary early
|
||||
— everything the attacker writes after it then reads as trusted instructions
|
||||
outside the block. Replacing the underscores with hyphens leaves the text
|
||||
readable but means it no longer matches the real (underscore) delimiter.
|
||||
"""
|
||||
"""Defang embedded ``untrusted_tool_result`` tokens so poisoned content
|
||||
can't close the trust boundary early (hyphens keep it readable but non-matching)."""
|
||||
return _DELIMITER_TOKEN_RE.sub("untrusted-tool-result", content)
|
||||
|
||||
|
||||
def _maybe_wrap_untrusted(name: str, content: Any) -> Any:
|
||||
"""Wrap content from high-risk tools in untrusted-data delimiters.
|
||||
"""Wrap high-risk tool content in untrusted-data delimiters.
|
||||
|
||||
Handles plain string content and multimodal content lists
|
||||
(``[{"type": "text", "text": "..."}, {"type": "image_url", ...}]``).
|
||||
Text parts inside a multimodal list are wrapped individually — the same
|
||||
rules as plain string content — so vision-capable adapters still receive
|
||||
a valid content list while an injection payload embedded in a text chunk
|
||||
is still marked as untrusted data. Non-text parts (image_url, etc.) are
|
||||
preserved unchanged. The outer list is rebuilt rather than returned by
|
||||
identity, so callers must compare by value, not by ``is``.
|
||||
|
||||
Returns ``content`` unchanged when:
|
||||
- the tool is not in the high-risk set
|
||||
- the content is neither a string nor a list (dict, None, …)
|
||||
- (string) the content is too short to be worth wrapping
|
||||
|
||||
Wrapped string content is always neutralized (any embedded delimiter token
|
||||
is defanged) and wrapped in exactly one well-formed block. There is no
|
||||
"already wrapped" fast-path: such a check is attacker-forgeable — content
|
||||
that merely starts with the opening tag would be returned with no data
|
||||
framing at all — so re-wrapping (harmlessly) is the safe choice.
|
||||
Strings are neutralized and wrapped in exactly one block; text parts of a
|
||||
multimodal list are wrapped individually (non-text parts preserved, outer
|
||||
list rebuilt — compare by value, not ``is``). Unchanged when the tool is
|
||||
not high-risk, the content is neither str nor list, or a string is too
|
||||
short. There is deliberately no "already wrapped" fast-path: it would be
|
||||
attacker-forgeable, so harmless re-wrapping is the safe choice.
|
||||
"""
|
||||
if not _is_untrusted_tool(name):
|
||||
return content
|
||||
@@ -821,11 +573,7 @@ def _maybe_wrap_untrusted(name: str, content: Any) -> Any:
|
||||
)
|
||||
if isinstance(content, list):
|
||||
return [
|
||||
{**item, "text": _maybe_wrap_untrusted(name, item["text"])}
|
||||
if isinstance(item, dict)
|
||||
and item.get("type") == "text"
|
||||
and isinstance(item.get("text"), str)
|
||||
else item
|
||||
{**item, "text": _maybe_wrap_untrusted(name, item["text"])} if _is_text_item(item) else item
|
||||
for item in content
|
||||
]
|
||||
return content
|
||||
|
||||
+248
-531
File diff suppressed because it is too large
Load Diff
+74
-204
@@ -1,57 +1,20 @@
|
||||
"""Turn liveness watchdog (#95548): force-abort turns that stall silently.
|
||||
"""Turn liveness watchdog: force-abort turns that stall silently.
|
||||
|
||||
A conversation turn can stall mid-flight (observed in #95548 between
|
||||
"model returned tool_calls" and tool execution, after a slow model
|
||||
response + desktop WS disconnect) with no error logged, no further
|
||||
progress, and the durable session turn lease kept renewing — so nothing
|
||||
ever force-aborts the turn and the session stays stuck until the process
|
||||
is killed.
|
||||
A turn can wedge mid-flight with no error and its durable lease still
|
||||
renewing, so nothing ever frees the session. This module owns the policy:
|
||||
config resolution (``agent.turn_liveness`` in config.yaml, validated — a typo,
|
||||
NaN or Inf warns and falls back rather than disabling the timeout or freezing
|
||||
the poll), the sampling state machine, and the watcher thread.
|
||||
``AIAgent.run_conversation`` supplies the commit/deactivate callbacks that own
|
||||
turn-lease state.
|
||||
|
||||
This module owns the watchdog policy end to end:
|
||||
|
||||
* configuration — :func:`resolve_turn_liveness_settings` reads the
|
||||
``agent.turn_liveness`` section of config.yaml and validates it;
|
||||
* state machine — :class:`TurnLivenessWatchdog` samples the agent's
|
||||
activity clock and drives the stall decision;
|
||||
* thread mechanics — the polling loop, stop handling, and the stall
|
||||
commit point.
|
||||
|
||||
``AIAgent.run_conversation`` (``run_agent.py``) keeps only the smallest
|
||||
integration seam: it resolves the settings, supplies the commit and
|
||||
deactivate callbacks that own turn-lease state, and starts the thread
|
||||
next to the durable lease refresher.
|
||||
|
||||
Config surface (config.yaml)::
|
||||
|
||||
agent:
|
||||
turn_liveness:
|
||||
timeout_s: 600.0 # idle bound; <= 0 disables the watchdog
|
||||
poll_s: 15.0 # sampling interval (seconds)
|
||||
|
||||
Both values are validated. A non-numeric typo, ``NaN``, or ``Inf`` logs a
|
||||
warning and falls back to the documented default — it never crashes
|
||||
startup, and a bogus value can never silently disable the watchdog
|
||||
(``NaN``) or freeze the watcher thread (``Inf`` poll).
|
||||
|
||||
Race safety (#95663 review): the watchdog samples the activity clock and
|
||||
binds the abort decision to the observed ``(generation, timestamp)`` pair.
|
||||
The commit callback revalidates that pair under the *same* lock
|
||||
``AIAgent._touch_activity`` uses to stamp the clock, so a turn that
|
||||
resumed while the stall was being logged/emitted is never hard-cancelled
|
||||
— it continues and its lease keeps renewing. The revalidated generation
|
||||
is carried into ``AIAgent.interrupt`` (``require_generation``) as a
|
||||
cancellation claim consumed at the final mutation edge: ``interrupt``
|
||||
reserves the claim under the activity lock, ``_touch_activity``
|
||||
invalidates the reservation the instant real progress lands, and the
|
||||
claim survives every blocking boundary, including the compression
|
||||
commit fence. Claim consumption and the first observable interrupt
|
||||
state publish in ONE activity-lock critical section, so a turn that
|
||||
resumes can only ever interleave before that section (the reservation
|
||||
is invalidated and the abort declines) or after it (the interrupt
|
||||
already committed under the lock) — never between "claim consumed" and
|
||||
"state published". A turn that resumes anywhere in the window is never
|
||||
hard-cancelled, and an exceptional interrupt path declines the abort
|
||||
fail-closed instead of mutating interrupt state.
|
||||
Race safety: the watchdog binds its abort decision to the observed
|
||||
``(generation, timestamp)`` pair; the commit callback revalidates that pair
|
||||
under the same lock ``_touch_activity`` stamps with, so a turn that resumed
|
||||
while the stall was being surfaced is never hard-cancelled. The revalidated
|
||||
generation flows into ``AIAgent.interrupt`` (``require_generation``) as a
|
||||
claim consumed at the final mutation edge, in ONE activity-lock critical
|
||||
section with the first interrupt-state publish.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -73,13 +36,8 @@ _CONFIG_POLL_KEY = "agent.turn_liveness.poll_s"
|
||||
|
||||
|
||||
class ActivitySnapshot(NamedTuple):
|
||||
"""One observation of the activity clock, bound to an abort decision.
|
||||
|
||||
``generation`` + ``activity_ts`` uniquely identify the observed stamp.
|
||||
The commit callback must revalidate this pair under the lock shared
|
||||
with ``AIAgent._touch_activity``; if it no longer matches, the
|
||||
observation is stale and the abort must be declined.
|
||||
"""
|
||||
"""One activity-clock observation; ``(generation, activity_ts)`` must be
|
||||
revalidated by the commit callback under the shared lock."""
|
||||
|
||||
generation: int
|
||||
activity_ts: Optional[float]
|
||||
@@ -87,27 +45,19 @@ class ActivitySnapshot(NamedTuple):
|
||||
|
||||
|
||||
def _warn_invalid_value(key: str, raw: Any, default: float) -> None:
|
||||
logger.warning(
|
||||
"Invalid %s in config.yaml: %r — falling back to default %.1f.",
|
||||
key,
|
||||
raw,
|
||||
default,
|
||||
)
|
||||
logger.warning("Invalid %s in config.yaml: %r — falling back to default %.1f.", key, raw, default)
|
||||
|
||||
|
||||
def _resolve_finite_seconds(raw: Any, *, default: float, key: str) -> float:
|
||||
"""Coerce one duration knob, rejecting typos, NaN and Inf.
|
||||
"""Coerce one duration knob, rejecting typos, NaN and Inf (never raises).
|
||||
|
||||
A non-numeric value must not raise into durable-turn startup, and a
|
||||
non-finite value must not silently change behavior (``NaN`` would
|
||||
disable the timeout via the ``> 0`` comparison; ``Inf`` would freeze
|
||||
the poll loop in ``Event.wait``).
|
||||
NaN would silently disable the timeout via the ``> 0`` comparison and
|
||||
Inf would freeze the poll loop in ``Event.wait``.
|
||||
"""
|
||||
try:
|
||||
value = float(raw)
|
||||
except (TypeError, ValueError):
|
||||
_warn_invalid_value(key, raw, default)
|
||||
return default
|
||||
value = math.nan
|
||||
if not math.isfinite(value):
|
||||
_warn_invalid_value(key, raw, default)
|
||||
return default
|
||||
@@ -117,25 +67,16 @@ def _resolve_finite_seconds(raw: Any, *, default: float, key: str) -> float:
|
||||
def resolve_turn_liveness_settings(
|
||||
config: Optional[Dict[str, Any]] = None,
|
||||
) -> Tuple[Optional[float], float]:
|
||||
"""Resolve ``(timeout_s, poll_s)`` from the ``agent.turn_liveness`` section.
|
||||
"""Resolve ``(timeout_s, poll_s)``; ``timeout_s <= 0`` opts out (``None``).
|
||||
|
||||
Precedence: explicit config.yaml value wins over the default; any
|
||||
invalid value (typo, NaN, Inf, non-positive poll) falls back to the
|
||||
default with a warning. ``timeout_s <= 0`` is the documented opt-out
|
||||
and yields ``(None, poll_s)`` — the caller then never arms the
|
||||
watchdog. The resolver never raises.
|
||||
Invalid values (typo, NaN, Inf, non-positive poll) warn and fall back to
|
||||
the default. Never raises.
|
||||
"""
|
||||
section: Dict[str, Any] = {}
|
||||
if isinstance(config, dict):
|
||||
agent_cfg = config.get("agent")
|
||||
if isinstance(agent_cfg, dict):
|
||||
raw_section = agent_cfg.get("turn_liveness")
|
||||
if isinstance(raw_section, dict):
|
||||
section = raw_section
|
||||
elif raw_section is not None:
|
||||
_warn_invalid_value(
|
||||
"agent.turn_liveness", raw_section, DEFAULT_TURN_LIVENESS_TIMEOUT_S
|
||||
)
|
||||
agent_cfg = config.get("agent") if isinstance(config, dict) else None
|
||||
raw_section = agent_cfg.get("turn_liveness") if isinstance(agent_cfg, dict) else None
|
||||
section: Dict[str, Any] = raw_section if isinstance(raw_section, dict) else {}
|
||||
if raw_section is not None and not isinstance(raw_section, dict):
|
||||
_warn_invalid_value("agent.turn_liveness", raw_section, DEFAULT_TURN_LIVENESS_TIMEOUT_S)
|
||||
|
||||
timeout_s = _resolve_finite_seconds(
|
||||
section.get("timeout_s", DEFAULT_TURN_LIVENESS_TIMEOUT_S),
|
||||
@@ -150,7 +91,6 @@ def resolve_turn_liveness_settings(
|
||||
if poll_s <= 0:
|
||||
_warn_invalid_value(_CONFIG_POLL_KEY, poll_s, DEFAULT_TURN_LIVENESS_POLL_S)
|
||||
poll_s = DEFAULT_TURN_LIVENESS_POLL_S
|
||||
# <= 0 is the documented opt-out, not an error.
|
||||
if timeout_s <= 0:
|
||||
timeout_s = None
|
||||
return timeout_s, poll_s
|
||||
@@ -159,11 +99,8 @@ def resolve_turn_liveness_settings(
|
||||
class TurnLivenessWatchdog:
|
||||
"""Sampled-idle watchdog thread bound to one conversation turn.
|
||||
|
||||
``run_agent.py`` owns the turn-lease state (stop event, turn-active
|
||||
flag, interrupt plumbing); this class only reads the activity clock
|
||||
and calls back at the stall commit point. All synchronization with
|
||||
``AIAgent._touch_activity`` goes through ``activity_lock``, which
|
||||
must be the SAME lock the agent stamps its activity clock with.
|
||||
``activity_lock`` must be the SAME lock ``AIAgent._touch_activity`` stamps
|
||||
the activity clock with; run_agent owns the lease state and callbacks.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -190,55 +127,26 @@ class TurnLivenessWatchdog:
|
||||
self._deactivate_turn = deactivate_turn
|
||||
|
||||
def make_thread(self) -> threading.Thread:
|
||||
"""Build the (not yet started) watcher thread.
|
||||
|
||||
``run_agent.py`` creates the watchdog before the turn begins but
|
||||
starts the thread at turn entry, right after the turn-active flag
|
||||
and the activity clock are stamped.
|
||||
"""
|
||||
return threading.Thread(
|
||||
target=self._watch,
|
||||
name="turn-liveness-watchdog",
|
||||
daemon=True,
|
||||
)
|
||||
|
||||
def start(self) -> threading.Thread:
|
||||
"""Spawn the watcher thread and return it (already running)."""
|
||||
thread = self.make_thread()
|
||||
thread.start()
|
||||
return thread
|
||||
"""Build the (not yet started) watcher thread; run_agent starts it at
|
||||
turn entry, after the turn-active flag and activity clock are stamped."""
|
||||
return threading.Thread(target=self._watch, name="turn-liveness-watchdog", daemon=True)
|
||||
|
||||
def _watch(self) -> None:
|
||||
while not self._stop_event.wait(self._poll_s):
|
||||
snapshot = self._sample()
|
||||
if snapshot is None:
|
||||
# Turn is no longer active; nothing to watch.
|
||||
return
|
||||
return # turn no longer active
|
||||
if snapshot.idle_seconds < self._timeout_s:
|
||||
continue
|
||||
# Pre-commit surface is OBSERVATIONAL only: it reports the
|
||||
# stall and that a recovery attempt is beginning. It must not
|
||||
# claim the abort or the lease withdrawal has committed — the
|
||||
# next operation can still veto the outcome. The definitive
|
||||
# aborted/lease-stopped settlement is published by
|
||||
# _surface_committed_abort only after _commit_abort succeeds
|
||||
# and the turn is deactivated (#95663 review).
|
||||
# Observational only: the commit below can still veto the abort
|
||||
# if progress resumed; the definitive settlement is published
|
||||
# by _surface_committed_abort after commit + deactivate.
|
||||
self._surface_stall(snapshot)
|
||||
# Commit point: bind the abort to the sampled generation/ts
|
||||
# and revalidate under the lock shared with `_touch_activity`.
|
||||
# If progress resumed while the stall was being surfaced, the
|
||||
# turn continues and this loop resumes sampling — the lease
|
||||
# keeps renewing. The commit also carries the revalidated
|
||||
# generation into the interrupt path, which reserves it as a
|
||||
# claim, survives every blocking boundary (compression
|
||||
# fence), and consumes it at the final mutation edge — progress
|
||||
# landing anywhere in that window declines the abort.
|
||||
if not self._commit_abort(snapshot, self._abort_message(snapshot)):
|
||||
message = f"Turn made no progress for {int(snapshot.idle_seconds)}s; aborting to release the session."
|
||||
if not self._commit_abort(snapshot, message):
|
||||
continue
|
||||
# Stop renewing the durable lease: a wedge the hard interrupt
|
||||
# cannot unwind must not keep the lease alive forever (the
|
||||
# issue's "lease keeps renewing" masking). The TTL expiry then
|
||||
# lets stale-turn cleanup reclaim the row.
|
||||
# Stop renewing the lease so a wedge the interrupt cannot unwind
|
||||
# expires via TTL instead of masking forever.
|
||||
self._deactivate_turn()
|
||||
self._surface_committed_abort(snapshot)
|
||||
return
|
||||
@@ -247,97 +155,59 @@ class TurnLivenessWatchdog:
|
||||
with self._activity_lock:
|
||||
if not self._is_turn_active():
|
||||
return None
|
||||
generation = getattr(
|
||||
self._agent, "_turn_liveness_activity_generation", 0
|
||||
)
|
||||
generation = getattr(self._agent, "_turn_liveness_activity_generation", 0)
|
||||
activity_ts = getattr(self._agent, "_last_activity_ts", None)
|
||||
now = time.time()
|
||||
if activity_ts is None:
|
||||
idle_seconds = 0.0
|
||||
else:
|
||||
idle_seconds = max(0.0, now - activity_ts)
|
||||
return ActivitySnapshot(
|
||||
generation=generation,
|
||||
activity_ts=activity_ts,
|
||||
idle_seconds=idle_seconds,
|
||||
)
|
||||
idle_seconds = 0.0 if activity_ts is None else max(0.0, time.time() - activity_ts)
|
||||
return ActivitySnapshot(generation, activity_ts, idle_seconds)
|
||||
|
||||
def _abort_message(self, snapshot: ActivitySnapshot) -> str:
|
||||
return (
|
||||
f"Turn made no progress for {int(snapshot.idle_seconds)}s; "
|
||||
"aborting to release the session."
|
||||
)
|
||||
def _emit_warning(self, text: str, debug_msg: str) -> None:
|
||||
emit_warning = getattr(self._agent, "_emit_warning", None)
|
||||
if not callable(emit_warning):
|
||||
return
|
||||
try:
|
||||
emit_warning(text)
|
||||
except Exception:
|
||||
logger.debug(debug_msg, exc_info=True)
|
||||
|
||||
def _surface_stall(self, snapshot: ActivitySnapshot) -> None:
|
||||
"""Observationally surface the stall: log it loudly and emit a
|
||||
UI-visible warning that a recovery attempt is beginning.
|
||||
"""Log + UI-warn that recovery is beginning (not that it committed).
|
||||
|
||||
Deliberately does NOT claim the abort or the lease withdrawal has
|
||||
committed: the next operation (``_commit_abort``) can still veto
|
||||
the outcome when the turn resumed while this surface window was
|
||||
open. The definitive aborted/lease-stopped settlement is
|
||||
published by :meth:`_surface_committed_abort` only after the
|
||||
abort wins and the turn is deactivated.
|
||||
|
||||
Rate-limited: a turn whose aborts keep declining (resumed
|
||||
activity, exceptional interrupt path) must not re-log and
|
||||
re-warn every poll interval — the first surface carries the
|
||||
signal, repeats are suppressed until activity actually moves
|
||||
again (a new generation re-arms the surface).
|
||||
Rate-limited per activity generation so repeatedly declined aborts
|
||||
do not re-log every poll; a new generation re-arms the surface.
|
||||
"""
|
||||
generation = snapshot.generation
|
||||
if getattr(self, "_last_surfaced_generation", None) == generation:
|
||||
return
|
||||
self._last_surfaced_generation = generation
|
||||
session_id = getattr(self._agent, "session_id", None) or self._session_id
|
||||
last_desc = getattr(self._agent, "_last_activity_desc", None)
|
||||
logger.error(
|
||||
"Turn liveness watchdog fired for session %s: "
|
||||
"no progress for %.1fs (last activity: %r). "
|
||||
"Attempting recovery: force-interrupting the turn and "
|
||||
"stopping lease renewal if it cannot resume (#95548).",
|
||||
session_id,
|
||||
getattr(self._agent, "session_id", None) or self._session_id,
|
||||
snapshot.idle_seconds,
|
||||
last_desc,
|
||||
getattr(self._agent, "_last_activity_desc", None),
|
||||
)
|
||||
self._emit_warning(
|
||||
"⚠️ This turn stopped making progress "
|
||||
f"({int(snapshot.idle_seconds)}s without activity); "
|
||||
"attempting recovery so the session can continue.",
|
||||
"Failed to emit turn liveness warning",
|
||||
)
|
||||
emit_warning = getattr(self._agent, "_emit_warning", None)
|
||||
if not callable(emit_warning):
|
||||
return
|
||||
try:
|
||||
emit_warning(
|
||||
"⚠️ This turn stopped making progress "
|
||||
f"({int(snapshot.idle_seconds)}s without activity); "
|
||||
"attempting recovery so the session can continue."
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("Failed to emit turn liveness warning", exc_info=True)
|
||||
|
||||
def _surface_committed_abort(self, snapshot: ActivitySnapshot) -> None:
|
||||
"""Publish the definitive settlement AFTER the abort has authority.
|
||||
|
||||
Runs only once ``_commit_abort`` succeeded (the interrupt was
|
||||
published) and the turn lease was deactivated: the turn IS
|
||||
force-aborted and lease renewal IS stopped, so stating that is
|
||||
now true. Separated from the pre-commit surface so a declined
|
||||
abort never reports a committed outcome (#95663 review).
|
||||
"""
|
||||
session_id = getattr(self._agent, "session_id", None) or self._session_id
|
||||
"""Publish the definitive settlement once the abort has authority."""
|
||||
logger.error(
|
||||
"Turn liveness watchdog aborted turn for session %s: "
|
||||
"no progress for %.1fs; turn interrupted and lease renewal "
|
||||
"stopped (#95548).",
|
||||
session_id,
|
||||
getattr(self._agent, "session_id", None) or self._session_id,
|
||||
snapshot.idle_seconds,
|
||||
)
|
||||
emit_warning = getattr(self._agent, "_emit_warning", None)
|
||||
if not callable(emit_warning):
|
||||
return
|
||||
try:
|
||||
emit_warning(
|
||||
"⚠️ Turn aborted by the liveness watchdog "
|
||||
f"({int(snapshot.idle_seconds)}s without activity); "
|
||||
"lease renewal stopped so the session can be reclaimed. "
|
||||
"You can retry your message."
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("Failed to emit committed-abort warning", exc_info=True)
|
||||
self._emit_warning(
|
||||
"⚠️ Turn aborted by the liveness watchdog "
|
||||
f"({int(snapshot.idle_seconds)}s without activity); "
|
||||
"lease renewal stopped so the session can be reclaimed. "
|
||||
"You can retry your message.",
|
||||
"Failed to emit committed-abort warning",
|
||||
)
|
||||
|
||||
@@ -170,7 +170,6 @@ class TestRunBoundedSync:
|
||||
result = run_bounded_sync(lambda: "ok", 5.0, label="t")
|
||||
assert result.timed_out is False
|
||||
assert result.value == "ok"
|
||||
assert result.raise_if_timed_out() == "ok"
|
||||
|
||||
def test_unbounded_when_timeout_none(self):
|
||||
result = run_bounded_sync(lambda: 7, None, label="t")
|
||||
@@ -196,9 +195,7 @@ class TestRunBoundedSync:
|
||||
assert result.timed_out is True
|
||||
assert result.value is None
|
||||
assert elapsed < 5.0 # returned near the deadline, not after 30s
|
||||
with pytest.raises(DeadlineExpired) as exc_info:
|
||||
result.raise_if_timed_out()
|
||||
assert "wedged" in str(exc_info.value)
|
||||
assert result.label == "wedged"
|
||||
release.set()
|
||||
|
||||
def test_on_timeout_callback_runs(self):
|
||||
|
||||
@@ -1,15 +1,4 @@
|
||||
"""Tests for the cross-Hermes-profile write guard in agent/file_safety.
|
||||
|
||||
The guard fires when a tool tries to write into another Hermes profile's
|
||||
skills/plugins/cron/memories directory. It's a soft guard — defense in
|
||||
depth, NOT a security boundary — but it prevents the agent from silently
|
||||
corrupting a profile that belongs to a different session.
|
||||
|
||||
Reference: May 2026 incident — a hermes-security profile session
|
||||
accidentally edited skills under both ~/.hermes/profiles/hermes-security/skills/
|
||||
AND ~/.hermes/skills/ (the default profile's skills), realizing only
|
||||
afterwards that the second path belonged to a different profile.
|
||||
"""
|
||||
"""Tests for the (retired) cross-Hermes-profile write guard in agent/file_safety."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
@@ -60,7 +49,6 @@ def fake_hermes(tmp_path, monkeypatch):
|
||||
import hermes_constants
|
||||
monkeypatch.setattr(hermes_constants, "get_default_hermes_root", lambda: root)
|
||||
|
||||
# The reloads below ensure get_cross_profile_warning/classify see the patched root.
|
||||
import agent.file_safety as fs
|
||||
monkeypatch.setattr(fs, "_hermes_root_path", lambda: root)
|
||||
|
||||
@@ -102,49 +90,6 @@ class TestResolveActiveProfileName:
|
||||
assert fs._resolve_active_profile_name() == "default"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# classify_cross_profile_target
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestClassifyCrossProfileTarget:
|
||||
|
||||
def test_security_writing_default_skill(self, fake_hermes, monkeypatch):
|
||||
"""The exact incident from May 2026."""
|
||||
_set_active_home(monkeypatch, fake_hermes["security_home"])
|
||||
from agent.file_safety import classify_cross_profile_target
|
||||
result = classify_cross_profile_target(
|
||||
str(fake_hermes["default_home"] / "skills" / "foo" / "SKILL.md")
|
||||
)
|
||||
assert result is not None
|
||||
assert result["active_profile"] == "hermes-security"
|
||||
assert result["target_profile"] == "default"
|
||||
assert result["area"] == "skills"
|
||||
|
||||
def test_default_writing_security_skill(self, fake_hermes, monkeypatch):
|
||||
"""Inverse direction — default-profile session reaching into a named profile."""
|
||||
_set_active_home(monkeypatch, fake_hermes["default_home"])
|
||||
from agent.file_safety import classify_cross_profile_target
|
||||
result = classify_cross_profile_target(
|
||||
str(fake_hermes["security_home"] / "skills" / "foo" / "SKILL.md")
|
||||
)
|
||||
assert result is not None
|
||||
assert result["active_profile"] == "default"
|
||||
assert result["target_profile"] == "hermes-security"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("area", ["skills", "plugins", "cron", "memories"])
|
||||
def test_all_profile_scoped_areas_classified(self, fake_hermes, monkeypatch, area):
|
||||
_set_active_home(monkeypatch, fake_hermes["security_home"])
|
||||
from agent.file_safety import classify_cross_profile_target
|
||||
target = fake_hermes["default_home"] / area / "foo.txt"
|
||||
result = classify_cross_profile_target(str(target))
|
||||
assert result is not None
|
||||
assert result["area"] == area
|
||||
|
||||
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# get_cross_profile_warning
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -155,9 +155,5 @@ class TestSandboxMirrorIsOrthogonalToCrossProfile:
|
||||
target.parent.mkdir(parents=True)
|
||||
target.write_text("x")
|
||||
|
||||
# cross-profile classifier: active profile == target's inner-mirror
|
||||
# profile name; on the existing detector the path's parts[2] is
|
||||
# ``sandboxes``, not a scoped area, so it returns None.
|
||||
assert fs.classify_cross_profile_target(str(target)) is None
|
||||
# sandbox-mirror classifier: fires unconditionally on the shape.
|
||||
assert fs.classify_sandbox_mirror_target(str(target)) is not None
|
||||
|
||||
@@ -291,7 +291,7 @@ def test_hatch_pet_end_to_end(monkeypatch, tmp_path):
|
||||
def fake_generate(prompt, *, n=1, reference_images=None, provider=None, prefix="pet", aspect_ratio="square"):
|
||||
# Return a synthetic row strip; frame count is inferable from the spec.
|
||||
state = prefix.replace("pet_row_", "")
|
||||
count = atlas_mod.FRAME_COUNTS.get(state, 6)
|
||||
count = dict((s, c) for s, _, c in atlas_mod.ROW_SPECS).get(state, 6)
|
||||
p = tmp_path / f"{prefix}.png"
|
||||
_strip(count).save(p)
|
||||
return [p]
|
||||
@@ -331,7 +331,7 @@ def test_hatch_pet_removes_row_strips_after_extraction(monkeypatch, tmp_path):
|
||||
|
||||
def fake_generate(prompt, *, n=1, reference_images=None, provider=None, prefix="pet", aspect_ratio="square"):
|
||||
state = prefix.replace("pet_row_", "")
|
||||
count = atlas_mod.FRAME_COUNTS.get(state, 6)
|
||||
count = dict((s, c) for s, _, c in atlas_mod.ROW_SPECS).get(state, 6)
|
||||
p = tmp_path / f"{prefix}.png"
|
||||
_strip(count).save(p)
|
||||
produced.append(p)
|
||||
@@ -359,7 +359,7 @@ def test_hatch_pet_removes_row_strips_after_failed_attempt(monkeypatch, tmp_path
|
||||
def fake_generate(prompt, *, n=1, reference_images=None, provider=None, prefix="pet", aspect_ratio="square"):
|
||||
attempts[prefix] = attempts.get(prefix, 0) + 1
|
||||
state = prefix.replace("pet_row_", "")
|
||||
count = atlas_mod.FRAME_COUNTS.get(state, 6)
|
||||
count = dict((s, c) for s, _, c in atlas_mod.ROW_SPECS).get(state, 6)
|
||||
path = tmp_path / f"{prefix}_{attempts[prefix]}.png"
|
||||
_strip(count).save(path)
|
||||
return [path]
|
||||
@@ -397,7 +397,7 @@ def test_hatch_pet_idle_fallback_when_row_fails(monkeypatch, tmp_path):
|
||||
if prefix == "pet_row_idle":
|
||||
raise GenerationError("boom")
|
||||
state = prefix.replace("pet_row_", "")
|
||||
count = atlas_mod.FRAME_COUNTS.get(state, 6)
|
||||
count = dict((s, c) for s, _, c in atlas_mod.ROW_SPECS).get(state, 6)
|
||||
p = tmp_path / f"{prefix}.png"
|
||||
_strip(count).save(p)
|
||||
return [p]
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Two guards, both notice/re-prompt-only:
|
||||
|
||||
1. Identical-call loop breaker — ``ToolCallGuardrailController.observe_identical_call``
|
||||
1. Identical-call loop breaker — ``ToolCallGuardrailController.observe_call``
|
||||
appends a compact notice to the tool RESULT on the 3rd consecutive call
|
||||
with identical (tool, canonical args) AND an identical result. It never
|
||||
blocks execution, exempts legitimately-repeatable pollers, and resets on
|
||||
@@ -29,7 +29,7 @@ def _observe_n(controller, n, tool="web_search", args=None, result="same result"
|
||||
notices = []
|
||||
for _ in range(n):
|
||||
notices.append(
|
||||
controller.observe_identical_call(tool, args or {"query": "x"}, result)
|
||||
controller.observe_call(tool, args or {"query": "x"}, result).notice
|
||||
)
|
||||
return notices
|
||||
|
||||
@@ -58,18 +58,18 @@ def test_keeps_firing_past_threshold():
|
||||
def test_does_not_fire_when_arguments_differ():
|
||||
c = ToolCallGuardrailController()
|
||||
for i in range(5):
|
||||
notice = c.observe_identical_call(
|
||||
notice = c.observe_call(
|
||||
"web_search", {"query": f"q{i}"}, "same result"
|
||||
)
|
||||
).notice
|
||||
assert notice is None
|
||||
|
||||
|
||||
def test_does_not_fire_when_results_differ():
|
||||
c = ToolCallGuardrailController()
|
||||
for i in range(5):
|
||||
notice = c.observe_identical_call(
|
||||
notice = c.observe_call(
|
||||
"terminal", {"command": "poll-status"}, f"output {i}"
|
||||
)
|
||||
).notice
|
||||
assert notice is None
|
||||
|
||||
|
||||
@@ -77,7 +77,7 @@ def test_streak_resets_when_a_different_call_intervenes():
|
||||
c = ToolCallGuardrailController()
|
||||
assert _observe_n(c, 2)[-1] is None
|
||||
# Different tool breaks the consecutive streak.
|
||||
assert c.observe_identical_call("read_file", {"path": "/a"}, "data") is None
|
||||
assert c.observe_call("read_file", {"path": "/a"}, "data").notice is None
|
||||
# Two more of the original are a fresh streak of 2 — still no notice.
|
||||
assert all(n is None for n in _observe_n(c, 2))
|
||||
|
||||
@@ -85,16 +85,16 @@ def test_streak_resets_when_a_different_call_intervenes():
|
||||
def test_arg_canonicalization_ignores_key_order():
|
||||
c = ToolCallGuardrailController()
|
||||
r = "same"
|
||||
assert c.observe_identical_call("t", {"a": 1, "b": 2}, r) is None
|
||||
assert c.observe_identical_call("t", {"b": 2, "a": 1}, r) is None
|
||||
assert c.observe_identical_call("t", {"a": 1, "b": 2}, r) is not None
|
||||
assert c.observe_call("t", {"a": 1, "b": 2}, r).notice is None
|
||||
assert c.observe_call("t", {"b": 2, "a": 1}, r).notice is None
|
||||
assert c.observe_call("t", {"a": 1, "b": 2}, r).notice is not None
|
||||
|
||||
|
||||
def test_allowlisted_pollers_never_fire():
|
||||
c = ToolCallGuardrailController()
|
||||
for tool in ("process_manage", "vendor_get_result", "job_poll"):
|
||||
for _ in range(STALL_GUARD_IDENTICAL_CALL_THRESHOLD + 2):
|
||||
assert c.observe_identical_call(tool, {"id": "j1"}, "Generating") is None
|
||||
assert c.observe_call(tool, {"id": "j1"}, "Generating").notice is None
|
||||
|
||||
|
||||
def test_allowlist_membership_contract():
|
||||
@@ -328,13 +328,6 @@ def test_multimodal_content_never_stubbed_and_breaks_streak():
|
||||
assert c.observe_call("vision", args, _BIG, tool_call_id="c3").stub is None
|
||||
|
||||
|
||||
def test_observe_identical_call_backcompat_notice_still_fires():
|
||||
c = ToolCallGuardrailController()
|
||||
for _ in range(STALL_GUARD_IDENTICAL_CALL_THRESHOLD - 1):
|
||||
assert c.observe_identical_call("web_search", {"q": 1}, "r") is None
|
||||
assert c.observe_identical_call("web_search", {"q": 1}, "r") is not None
|
||||
|
||||
|
||||
def test_extract_persisted_path_round_trip():
|
||||
# The stub's spillover reference is parsed from the <persisted-output>
|
||||
# block that maybe_persist_tool_result builds — assert the round trip.
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -92,7 +91,6 @@ def test_registered_observable_metric_names_cover_snapshot_metrics(monkeypatch):
|
||||
docs/observability/monitoring.md: an emitted-but-unregistered gauge is
|
||||
silently dropped. Regression guard for background_work / cron additions.
|
||||
"""
|
||||
import inspect
|
||||
from agent.monitoring import gateway_health_export
|
||||
|
||||
# Build a representative snapshot (gateway + cron + background_work) without
|
||||
@@ -121,9 +119,7 @@ def test_registered_observable_metric_names_cover_snapshot_metrics(monkeypatch):
|
||||
|
||||
snapshot_names = {m.name for m in gateway_health_export._read_runtime_snapshot({}).metrics}
|
||||
|
||||
# Extract the registered metric_names list literal from _start_metric_provider.
|
||||
src = inspect.getsource(gateway_health_export._start_metric_provider)
|
||||
registered = {n for n in snapshot_names if f'"{n}"' in src}
|
||||
registered = set(gateway_health_export._OBSERVABLE_METRIC_NAMES)
|
||||
|
||||
missing = snapshot_names - registered
|
||||
assert not missing, f"gauges emitted but NOT registered in metric_names (will be silently dropped): {sorted(missing)}"
|
||||
|
||||
@@ -3,10 +3,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import threading
|
||||
|
||||
from agent.monitoring.emitter import MonitoringEmitter
|
||||
from agent.monitoring.events import GatewayHealthEvent
|
||||
|
||||
|
||||
def test_emit_never_raises_when_disabled():
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
|
||||
|
||||
+2
-2
@@ -25,7 +25,7 @@ from agent import estop
|
||||
def hermes_home(tmp_path, monkeypatch):
|
||||
"""Point HERMES_HOME at a temp dir and reset estop module log state."""
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||||
estop._reset_log_state_for_tests()
|
||||
estop._logged_components.clear()
|
||||
return tmp_path
|
||||
|
||||
|
||||
@@ -389,7 +389,7 @@ def test_profile_gateway_honors_canonical_root_estop(tmp_path, monkeypatch):
|
||||
profile = root / "profiles" / "fleet-analyst"
|
||||
profile.mkdir(parents=True)
|
||||
monkeypatch.setenv("HERMES_HOME", str(profile))
|
||||
estop._reset_log_state_for_tests()
|
||||
estop._logged_components.clear()
|
||||
|
||||
assert estop.is_engaged() is False
|
||||
(root / "ESTOP").write_text("{\"reason\": \"thundering herd\"}\n", encoding="utf-8")
|
||||
|
||||
Reference in New Issue
Block a user