From 7eb8ccc3157ec9112485f06eb284e36e5e93be1a Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 10:36:07 -0700 Subject: [PATCH 1/4] =?UTF-8?q?refactor(agent/runtime):=20monitoring=20?= =?UTF-8?q?=E2=80=94=20shared=20OTLP=20plumbing=20in=20otlp=5Fexporter,=20?= =?UTF-8?q?event=20base=20class,=20EmitterStreamer,=20dedupe=20health=20ex?= =?UTF-8?q?port?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - otlp_exporter hosts SDK loading (symbol table), header/endpoint/resource helpers shared with gateway_health_export; export module imports them instead of keeping copies (_otlp_config/_resolve_headers/_install_id/_safe_resource_attributes unified). _KEEP_BY_KIND attribute allowlist reused for diagnostic log attrs. - events: _MonitoringEvent base supplies to_dict; field order (wire order) unchanged. - redaction: redact_bounded() replaces 3 inline redact+truncate try/excepts. - EmitterStreamer base owns the shared unsubscribe/flush/shutdown for OTLPStreamer and GatewayDiagnosticLogStreamer. - gateway_health: metric construction helpers, _contains_any shared with cron_health, dead _allowed_logger/redact_gateway_message removed (0 refs). - Comment/docstring compaction keeping every stated invariant. --- agent/monitoring/__init__.py | 19 +- agent/monitoring/cron_health.py | 146 +++-- agent/monitoring/emitter.py | 41 +- agent/monitoring/events.py | 42 +- agent/monitoring/gateway_health.py | 338 +++++------ agent/monitoring/gateway_health_export.py | 536 ++++++------------ agent/monitoring/otlp_exporter.py | 285 ++++++---- agent/monitoring/policy.py | 18 +- agent/monitoring/redaction.py | 46 +- tests/monitoring/test_cron_health_export.py | 6 +- tests/monitoring/test_emitter.py | 2 - .../monitoring/test_gateway_health_export.py | 2 - 12 files changed, 618 insertions(+), 863 deletions(-) diff --git a/agent/monitoring/__init__.py b/agent/monitoring/__init__.py index ee45ff0164..20b4dc40f4 100644 --- a/agent/monitoring/__init__.py +++ b/agent/monitoring/__init__.py @@ -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 diff --git a/agent/monitoring/cron_health.py b/agent/monitoring/cron_health.py index 2c4fe8d35f..04e5122f76 100644 --- a/agent/monitoring/cron_health.py +++ b/agent/monitoring/cron_health.py @@ -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=[]) diff --git a/agent/monitoring/emitter.py b/agent/monitoring/emitter.py index 18a0d4851a..d63ebb73ac 100644 --- a/agent/monitoring/emitter.py +++ b/agent/monitoring/emitter.py @@ -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", diff --git a/agent/monitoring/events.py b/agent/monitoring/events.py index a17f4a4942..ee51d7ba28 100644 --- a/agent/monitoring/events.py +++ b/agent/monitoring/events.py @@ -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__ = [ diff --git a/agent/monitoring/gateway_health.py b/agent/monitoring/gateway_health.py index 752473fe31..f3ac45f8f3 100644 --- a/agent/monitoring/gateway_health.py +++ b/agent/monitoring/gateway_health.py @@ -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", ] diff --git a/agent/monitoring/gateway_health_export.py b/agent/monitoring/gateway_health_export.py index 0a377c99ab..fa7d1daee1 100644 --- a/agent/monitoring/gateway_health_export.py +++ b/agent/monitoring/gateway_health_export.py @@ -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() diff --git a/agent/monitoring/otlp_exporter.py b/agent/monitoring/otlp_exporter.py index 17c85cb8b6..f1c12fa4dc 100644 --- a/agent/monitoring/otlp_exporter.py +++ b/agent/monitoring/otlp_exporter.py @@ -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/``; 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.`` 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 diff --git a/agent/monitoring/policy.py b/agent/monitoring/policy.py index 1a42ce195c..0939fbbc67 100644 --- a/agent/monitoring/policy.py +++ b/agent/monitoring/policy.py @@ -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 diff --git a/agent/monitoring/redaction.py b/agent/monitoring/redaction.py index 312875901e..22ae1c0904 100644 --- a/agent/monitoring/redaction.py +++ b/agent/monitoring/redaction.py @@ -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"(? 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", ] diff --git a/tests/monitoring/test_cron_health_export.py b/tests/monitoring/test_cron_health_export.py index 67200f3130..abfa396b9b 100644 --- a/tests/monitoring/test_cron_health_export.py +++ b/tests/monitoring/test_cron_health_export.py @@ -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)}" diff --git a/tests/monitoring/test_emitter.py b/tests/monitoring/test_emitter.py index 3fc621bd41..6c4883072c 100644 --- a/tests/monitoring/test_emitter.py +++ b/tests/monitoring/test_emitter.py @@ -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(): diff --git a/tests/monitoring/test_gateway_health_export.py b/tests/monitoring/test_gateway_health_export.py index 24ff1f468e..8c8190f7f1 100644 --- a/tests/monitoring/test_gateway_health_export.py +++ b/tests/monitoring/test_gateway_health_export.py @@ -1,8 +1,6 @@ from __future__ import annotations -import logging -import pytest From 2ad284b473798583f548f4436f3cadc7813a7371 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 10:36:07 -0700 Subject: [PATCH 2/4] =?UTF-8?q?refactor(agent/runtime):=20pet=20=E2=80=94?= =?UTF-8?q?=20shared=20flood/placement=20helpers=20in=20atlas,=20provider?= =?UTF-8?q?=20resolution=20loop,=20dead=20helpers=20removed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - atlas: _border_flood/_unvisited_components/_place/_clear_region/_remove_masked replace 6 hand-rolled flood + canvas-composite loops; _sever_expected_gutters uses channel ops instead of per-pixel writes; dead _color_distance, _has_slot_padding, _slot_bounds, atlas_to_webp_bytes, FRAME_COUNTS (0 refs). - render/store: dead _open_sheet/_png_bytes/_union_alpha_bbox/_thumbs_dir removed. - imagegen: _available() unifies 3 provider-availability checks; forced/preferred provider resolution collapsed into one ordered loop (same precedence). - state: derive_pet_state as a ranked table (same priority order). - Comment/docstring compaction keeping the pipeline invariants. --- agent/pet/constants.py | 8 +- agent/pet/generate/atlas.py | 932 +++++++++++------------------- agent/pet/generate/imagegen.py | 68 +-- agent/pet/generate/orchestrate.py | 285 ++++----- agent/pet/manifest.py | 12 +- agent/pet/render.py | 427 +++++--------- agent/pet/state.py | 25 +- agent/pet/store.py | 217 +++---- tests/agent/test_pet_generate.py | 8 +- 9 files changed, 701 insertions(+), 1281 deletions(-) diff --git a/agent/pet/constants.py b/agent/pet/constants.py index a7e816c401..5a3fafb291 100644 --- a/agent/pet/constants.py +++ b/agent/pet/constants.py @@ -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: diff --git a/agent/pet/generate/atlas.py b/agent/pet/generate/atlas.py index b631d79f35..7049bd6cd0 100644 --- a/agent/pet/generate/atlas.py +++ b/agent/pet/generate/atlas.py @@ -1,31 +1,20 @@ """Deterministic spritesheet assembly — generated row strips → Hermes atlas. -Image-generation models are good at *drawing* a row of poses but bad at exact -grid geometry, so the model never owns the atlas layout: it produces one loose -horizontal strip per state, and these deterministic ops slice that strip into -clean, centered, transparent ``192x208`` cells and pack them into the sheet our -renderer reads. - -The atlas follows the **petdex/Codex standard**: 8 columns x 9 rows of -``192x208`` cells (``1536x1872``), with the row order + per-row frame counts -from OpenAI's ``hatch-pet`` skill. Our renderer (:mod:`agent.pet.render`) keys -frames as ``rows = states, cols = frames`` via -:data:`agent.pet.constants.CODEX_STATE_ROWS`, and a pet built here is a valid -``petdex submit`` spritesheet. Rows shorter than 8 columns leave the trailing -cells fully transparent. - -Note ``running`` is the *working* state (in-place processing), NOT locomotion — -``running-right`` / ``running-left`` are the actual directional walk cycles. - -The frame-segmentation, fit-to-cell, and transparency-residue logic is adapted -from OpenAI's ``hatch-pet`` skill (openai/skills, Apache-2.0). +Image models draw a row of poses well but can't do exact grid geometry, so the +model never owns the layout: it emits one loose horizontal strip per state and +these ops slice it into centered transparent ``192x208`` cells packed into the +petdex/Codex atlas (8 columns x 9 rows, ``1536x1872``) that +:mod:`agent.pet.render` reads via :data:`agent.pet.constants.CODEX_STATE_ROWS`. +``running`` is the in-place *working* state; ``running-right``/``-left`` are the +directional walk cycles. Segmentation/fit/residue logic is adapted from +OpenAI's ``hatch-pet`` skill (openai/skills, Apache-2.0). """ from __future__ import annotations -import io import logging import math +from collections import deque from pathlib import Path from agent.pet.constants import FRAME_H, FRAME_W @@ -36,10 +25,8 @@ CELL_WIDTH = FRAME_W CELL_HEIGHT = FRAME_H # (state, row index, frame count). Order/row indices MUST match -# ``constants.CODEX_STATE_ROWS`` so the renderer crops the right row for each -# driven state, and the per-row frame counts mirror the petdex/Codex -# ``hatch-pet`` ``animation-rows`` spec. The renderer trims trailing blank -# columns, so rows shorter than ``COLUMNS`` (8) just leave the tail transparent. +# ``constants.CODEX_STATE_ROWS``; frame counts mirror the petdex ``hatch-pet`` +# spec. Rows shorter than 8 leave their tail transparent (renderer trims it). ROW_SPECS: list[tuple[str, int, int]] = [ ("idle", 0, 6), ("running-right", 1, 8), @@ -57,42 +44,112 @@ COLUMNS = max(count for _, _, count in ROW_SPECS) ATLAS_WIDTH = COLUMNS * CELL_WIDTH ATLAS_HEIGHT = ROWS * CELL_HEIGHT -FRAME_COUNTS: dict[str, int] = {state: count for state, _, count in ROW_SPECS} - -# Alpha at/below which a pixel is "background" for component detection. -_ALPHA_FLOOR = 16 -# Cell padding kept around a fitted sprite so poses never touch the edge. -_CELL_PAD = 10 -# Margin for the normalized pass — small, to fill the cell like real petdex pets -# (they sit ~5px from the edges); the width clamp, not the pad, prevents clipping. +_ALPHA_FLOOR = 16 # alpha at/below which a pixel is "background" +_CELL_PAD = 10 # padding kept around a fitted sprite +# Small margin for the normalized pass so cells fill like real petdex pets +# (~5px from the edges); the width clamp, not the pad, prevents clipping. _NORMALIZE_PAD = 14 -# Side-lobe cutoff for fitted frames. Adjacent-pose bleed usually appears as a -# small separated horizontal lobe beside the real subject; keep sizeable lobes so -# we don't punish a legitimate wide pose. +# Side-lobe cutoff: adjacent-pose bleed shows as a small separated lobe; keep +# sizeable lobes so a legitimate wide pose isn't punished. _SIDE_LOBE_RATIO = 0.18 +_NEIGHBOURS = ((1, 0), (-1, 0), (0, 1), (0, -1)) + + +def _median(values) -> int: + ordered = sorted(values) + return ordered[len(ordered) // 2] + + +def _blank(size=(CELL_WIDTH, CELL_HEIGHT)): + from PIL import Image + + return Image.new("RGBA", size, (0, 0, 0, 0)) + + +def _place(sprite, size: tuple[int, int], offset: tuple[int, int] = (0, 0)): + """*sprite* alpha-composited at *offset* onto a new transparent canvas of *size*.""" + canvas = _blank(size) + canvas.alpha_composite(sprite, offset) + return canvas + + +def _clear_region(image, box: tuple[int, int, int, int]) -> None: + """Make the ``(left, top, right, bottom)`` region of *image* fully transparent, in place.""" + image.paste(_blank((box[2] - box[0], box[3] - box[1])), (box[0], box[1])) + + +def _load_rgba(image): + """Open a path (or take an image) as RGBA.""" + from PIL import Image + + if isinstance(image, (str, Path)): + with Image.open(image) as opened: + return opened.convert("RGBA") + return image.convert("RGBA") + + +def _border_coords(w: int, h: int): + """Every border pixel: top/bottom rows column-wise, then left/right columns.""" + for x in range(w): + for y in (0, h - 1): + yield x, y + for y in range(h): + for x in (0, w - 1): + yield x, y + + +def _flood(w: int, h: int, visited: bytearray, seeds, accept) -> list[tuple[int, int]]: + """4-connected BFS from *seeds* over pixels passing *accept*; returns the visited pixels.""" + queue = deque(seeds) + pixels: list[tuple[int, int]] = [] + while queue: + x, y = queue.popleft() + pixels.append((x, y)) + for dx, dy in _NEIGHBOURS: + nx, ny = x + dx, y + dy + if 0 <= nx < w and 0 <= ny < h: + idx = ny * w + nx + if not visited[idx]: + visited[idx] = 1 + if accept(nx, ny): + queue.append((nx, ny)) + return pixels + + +def _border_flood(w: int, h: int, visited: bytearray, accept) -> list[tuple[int, int]]: + """Flood from every border pixel passing *accept* (edge-connected region only).""" + seeds: list[tuple[int, int]] = [] + for x, y in _border_coords(w, h): + if not visited[y * w + x] and accept(x, y): + visited[y * w + x] = 1 + seeds.append((x, y)) + return _flood(w, h, visited, seeds, accept) + + +def _unvisited_components(w: int, h: int, visited: bytearray, accept): + """Yield each 4-connected component of not-yet-visited pixels passing *accept*, in scan order.""" + for start in range(w * h): + if visited[start]: + continue + visited[start] = 1 + x, y = start % w, start // w + if accept(x, y): + yield _flood(w, h, visited, [(x, y)], accept) # ───────────────────────── background removal ───────────────────────── -def _color_distance(r: int, g: int, b: int, key: tuple[int, int, int]) -> float: - return math.sqrt((r - key[0]) ** 2 + (g - key[1]) ** 2 + (b - key[2]) ** 2) - - def _has_transparency(image) -> bool: """True if the strip already carries a real alpha background.""" - extrema = image.getchannel("A").getextrema() - # Min alpha 0 somewhere and a meaningful share of fully-transparent pixels. - if extrema[0] > _ALPHA_FLOOR: + if image.getchannel("A").getextrema()[0] > _ALPHA_FLOOR: return False - hist = image.getchannel("A").histogram() - transparent = sum(hist[: _ALPHA_FLOOR + 1]) - total = image.width * image.height - return transparent > total * 0.05 + transparent = sum(image.getchannel("A").histogram()[: _ALPHA_FLOOR + 1]) + return transparent > image.width * image.height * 0.05 def _dominant_corner_color(image) -> tuple[int, int, int]: - """Sample the four corners and return the most common opaque color.""" + """Most common opaque color among the four corners.""" from collections import Counter w, h = image.width, image.height @@ -102,17 +159,14 @@ def _dominant_corner_color(image) -> tuple[int, int, int]: r, g, b, a = px[x, y] if a > _ALPHA_FLOOR: counter[(r, g, b)] += 1 - if not counter: - return (0, 255, 0) - return counter.most_common(1)[0][0] + return counter.most_common(1)[0][0] if counter else (0, 255, 0) def _near_key_mask(image, key: tuple[int, int, int], tol: int = 48): - """An ``L`` mask, 255 where a pixel is within *tol* per-channel of *key*. + """``L`` mask, 255 where a pixel is within *tol* per-channel of *key*. - Tight on purpose: it only marks near-pure backdrop so trapped chroma pockets - seed the flood, while chroma-*tinted* character pixels stay outside it. Built - with channel point-ops (fast C), no per-pixel Python. + Tight on purpose: marks only near-pure backdrop so trapped chroma pockets + seed the flood while chroma-tinted character pixels stay outside it. """ from PIL import ImageChops @@ -127,36 +181,26 @@ def _near_key_mask(image, key: tuple[int, int, int], tol: int = 48): ) -def _defringe(rgba): - """Shave the 1px antialiased edge ring left after keying. +def _remove_masked(rgba, mask): + """Clear the pixels *mask* (``L``, 255 = remove) selects, then erode alpha by 1px (3x3 min). - Chroma keying can't catch the antialiased band where the sprite meets the - backdrop — those pixels are a key/sprite blend, too far from the key to be - removed, so they ring the cutout in magenta/green. Erode the alpha by one - pixel (a 3x3 min filter) to drop that contaminated ring; the sprite's own - thick dark outline keeps the silhouette intact. Built on a C-level filter, no - per-pixel Python. + The erosion drops the antialiased key/sprite blend ring (too far from the key to + match); the sprite's own thick outline keeps the silhouette intact. """ - from PIL import ImageFilter + from PIL import Image, ImageFilter - rgba.putalpha(rgba.getchannel("A").filter(ImageFilter.MinFilter(3))) - return rgba + out = Image.composite(_blank(rgba.size), rgba, mask) + out.putalpha(out.getchannel("A").filter(ImageFilter.MinFilter(3))) + return out def remove_background(image, *, chroma_key: tuple[int, int, int] | None = None, threshold: float = 90.0): """Return *image* (RGBA) with its flat background keyed out to transparent. - If the strip already has a transparent background we leave it alone; else we - key out *chroma_key* (or the dominant corner color when not given) via a - **border flood-fill**: only background-coloured pixels *connected to an edge* - are removed. A global color match (the old approach) punched holes in the pet - wherever an interior highlight happened to match the backdrop — e.g. a pug's - light belly against a near-white background — which then showed through as the - window behind. Flood-fill keeps those interior pixels because they aren't - reachable from the border without crossing the (non-background) pet. + Already-transparent strips are left alone (holes repaired). Otherwise key out + *chroma_key* (or the dominant corner color) via a border flood-fill: a global + color match punched holes wherever an interior highlight matched the backdrop. """ - from collections import deque - from PIL import Image, ImageChops rgba = image.convert("RGBA") @@ -169,77 +213,31 @@ def remove_background(image, *, chroma_key: tuple[int, int, int] | None = None, def _is_bg(x: int, y: int) -> bool: r, g, b, a = px[x, y] - return a > _ALPHA_FLOOR and _color_distance(r, g, b, key) <= threshold + return a > _ALPHA_FLOOR and math.sqrt((r - key[0]) ** 2 + (g - key[1]) ** 2 + (b - key[2]) ** 2) <= threshold - # Fast path for strongly-saturated chroma keys (our normal sprite prompts use - # hot magenta): remove all near-key opaque pixels with C-level channel ops. - # This clears both border-connected backdrop and enclosed triangular pockets - # between connected limbs/capes, without a Python flood over ~1.5M pixels. + # Fast path for saturated chroma keys (our prompts use hot magenta): C-level + # channel ops clear border backdrop and enclosed pockets alike, no Python flood. if max(key) - min(key) >= 120: - near = _near_key_mask(rgba, key) # L mask, 255 where near key opaque = rgba.getchannel("A").point(lambda a: 255 if a > _ALPHA_FLOOR else 0) - remove_mask = ImageChops.darker(near, opaque) - keyed = Image.composite(Image.new("RGBA", rgba.size, (0, 0, 0, 0)), rgba, remove_mask) - return _defringe(keyed) + return _remove_masked(rgba, ImageChops.darker(_near_key_mask(rgba, key), opaque)) - visited = bytearray(w * h) - # Mark removals in a flat mask and apply them in one C composite at the end — - # writing `px[x, y] = (0,0,0,0)` per pixel was ~3M PixelAccess calls (84% of - # the whole pipeline) and pegged a core in pure Python, stalling the gateway. + # Border-only flood on purpose: a desaturated near-white/gray key must never + # seed from the character's interior (that is the hole-punching case). + # Mark removals in a flat mask and composite once in C — per-pixel writes + # were ~3M PixelAccess calls and stalled the gateway. remove = bytearray(w * h) - queue: deque[tuple[int, int]] = deque() - - # Seed from every border pixel that looks like background. - for x in range(w): - for y in (0, h - 1): - if _is_bg(x, y) and not visited[y * w + x]: - visited[y * w + x] = 1 - queue.append((x, y)) - for y in range(h): - for x in (0, w - 1): - if _is_bg(x, y) and not visited[y * w + x]: - visited[y * w + x] = 1 - queue.append((x, y)) - - # Trapped pockets: background enclosed by the character (the magenta between - # an arm and the body) isn't border-reachable, so also seed the flood from - # interior near-key pixels. Gated to a *saturated* key (our magenta backdrop) - # so we never seed from a character sharing a desaturated near-white/gray key - # — that's the hole-punching the border-only flood exists to avoid. - if max(key) - min(key) >= 120: - for i, near in enumerate(_near_key_mask(rgba, key).getdata()): - if near and not visited[i]: - visited[i] = 1 - queue.append((i % w, i // w)) - - while queue: - x, y = queue.popleft() + for x, y in _border_flood(w, h, bytearray(w * h), _is_bg): remove[y * w + x] = 1 - for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)): - if 0 <= nx < w and 0 <= ny < h: - idx = ny * w + nx - if not visited[idx]: - visited[idx] = 1 - if _is_bg(nx, ny): - queue.append((nx, ny)) - - # One C-level composite instead of millions of per-pixel writes: paint the - # flooded pixels to (0,0,0,0) wherever the mask is set. - mask = Image.frombytes("L", (w, h), bytes(remove)).point(lambda v: 255 if v else 0) - return _defringe(Image.composite(Image.new("RGBA", rgba.size, (0, 0, 0, 0)), rgba, mask)) + return _remove_masked(rgba, Image.frombytes("L", (w, h), bytes(remove)).point(lambda v: 255 if v else 0)) def _repair_internal_alpha_holes(image): """Fill transparent islands fully enclosed by opaque sprite pixels. Some providers return "transparent" PNGs with swiss-cheese alpha inside the - character. Border flood-fill cannot see those because there is no opaque - backdrop to key, so repair the alpha mask itself: transparent components that - touch an image edge remain background; transparent components enclosed by - the sprite are filled with the average color of their opaque neighbours. + character. Edge-connected transparent components stay background; enclosed + ones are filled with the average color of their opaque neighbours. """ - from collections import deque - rgba = image.convert("RGBA") w, h = rgba.size px = rgba.load() @@ -248,69 +246,24 @@ def _repair_internal_alpha_holes(image): def _is_transparent(x: int, y: int) -> bool: return px[x, y][3] <= _ALPHA_FLOOR - def _mark_border_component(sx: int, sy: int) -> None: - queue: deque[tuple[int, int]] = deque([(sx, sy)]) - visited[sy * w + sx] = 1 - while queue: - x, y = queue.popleft() - for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)): - if 0 <= nx < w and 0 <= ny < h: - idx = ny * w + nx - if not visited[idx] and _is_transparent(nx, ny): - visited[idx] = 1 - queue.append((nx, ny)) - - # First mark true background: all transparent pixels reachable from the edge. - for x in range(w): - for y in (0, h - 1): - if _is_transparent(x, y) and not visited[y * w + x]: - _mark_border_component(x, y) - for y in range(h): - for x in (0, w - 1): - if _is_transparent(x, y) and not visited[y * w + x]: - _mark_border_component(x, y) - - def _collect_hole(sx: int, sy: int) -> list[tuple[int, int]]: - queue: deque[tuple[int, int]] = deque([(sx, sy)]) - visited[sy * w + sx] = 1 - pixels: list[tuple[int, int]] = [] - while queue: - x, y = queue.popleft() - pixels.append((x, y)) - for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)): - if 0 <= nx < w and 0 <= ny < h: - idx = ny * w + nx - if not visited[idx] and _is_transparent(nx, ny): - visited[idx] = 1 - queue.append((nx, ny)) - return pixels + _border_flood(w, h, visited, _is_transparent) # edge-connected transparency = background def _fill_color(hole: list[tuple[int, int]]) -> tuple[int, int, int, int]: samples: list[tuple[int, int, int]] = [] seen = set(hole) for x, y in hole: - for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)): + for dx, dy in _NEIGHBOURS: + nx, ny = x + dx, y + dy if 0 <= nx < w and 0 <= ny < h and (nx, ny) not in seen: r, g, b, a = px[nx, ny] if a > _ALPHA_FLOOR: samples.append((r, g, b)) if not samples: return (0, 0, 0, 255) - return ( - round(sum(c[0] for c in samples) / len(samples)), - round(sum(c[1] for c in samples) / len(samples)), - round(sum(c[2] for c in samples) / len(samples)), - 255, - ) + r, g, b = (round(sum(c[i] for c in samples) / len(samples)) for i in range(3)) + return (r, g, b, 255) - for start, _ in enumerate(visited): - if visited[start]: - continue - x = start % w - y = start // w - if not _is_transparent(x, y): - continue - hole = _collect_hole(x, y) + for hole in _unvisited_components(w, h, visited, _is_transparent): color = _fill_color(hole) for hx, hy in hole: px[hx, hy] = color @@ -324,128 +277,84 @@ def _fit_to_cell(image): """Crop to content, scale to fit a padded cell, and center on transparent.""" from PIL import Image - target = Image.new("RGBA", (CELL_WIDTH, CELL_HEIGHT), (0, 0, 0, 0)) image = _drop_side_bleed(image) bbox = image.getbbox() if bbox is None: - return target + return _blank() sprite = image.crop(bbox) - max_w = CELL_WIDTH - _CELL_PAD - max_h = CELL_HEIGHT - _CELL_PAD - scale = min(max_w / sprite.width, max_h / sprite.height, 1.0) + scale = min((CELL_WIDTH - _CELL_PAD) / sprite.width, (CELL_HEIGHT - _CELL_PAD) / sprite.height, 1.0) if scale != 1.0: - # NEAREST, not LANCZOS: the generated "pixel art" has hard edges, and any - # interpolating resample anti-aliases them into a blurry, washed-out - # sprite once the renderer upscales the cell. Crisp blocky downscale reads - # as real pixel art. + # NEAREST: interpolating resamples blur the hard pixel-art edges. sprite = sprite.resize( (max(1, round(sprite.width * scale)), max(1, round(sprite.height * scale))), Image.Resampling.NEAREST, ) - left = (CELL_WIDTH - sprite.width) // 2 - top = (CELL_HEIGHT - sprite.height) // 2 - target.alpha_composite(sprite, (left, top)) - return target + return _place(sprite, (CELL_WIDTH, CELL_HEIGHT), ((CELL_WIDTH - sprite.width) // 2, (CELL_HEIGHT - sprite.height) // 2)) def _drop_side_bleed(image): - """Remove tiny separated left/right lobes before fitting a frame. + """Remove tiny separated left/right lobes (neighbour-pose slivers) before fitting. - Frogger showed the failure mode: a good centered pose plus a thin vertical - sliver from the neighbouring pose. By the time it reaches a cell, that sliver - may be close enough to the subject that component extraction already grouped - it. A horizontal alpha projection still reveals it as a small side lobe with - a low mass compared to the main silhouette. Drop only those low-mass lobes; - keep large lobes so wide poses and real limbs survive. + Component extraction may already have grouped a near sliver with the subject; + a horizontal alpha projection still reveals it as a low-mass side lobe. Only + those are dropped so wide poses and real limbs survive. """ - from PIL import Image - rgba = image.convert("RGBA") w, h = rgba.size - profile = _column_profile(rgba) # mean alpha per column (fast C resize) - - runs = _content_runs(profile) + runs = _content_runs(_column_profile(rgba)) if len(runs) < 2: return rgba - masses = [sum(profile[l:r]) for l, r in runs] - keep_mass = max(masses) * _SIDE_LOBE_RATIO - keep = [run for run, m in zip(runs, masses) if m >= keep_mass] + keep_mass = max(m for _run, m in runs) * _SIDE_LOBE_RATIO + keep = [run for run, m in runs if m >= keep_mass] if len(keep) == len(runs): return rgba - # Zero every column band that isn't a kept segment (box paste, not per-pixel). rgba = rgba.copy() - cut, prev = Image.new("RGBA", (w, h), (0, 0, 0, 0)), 0 + prev = 0 for left, right in keep: if left > prev: - rgba.paste(cut.crop((prev, 0, left, h)), (prev, 0)) + _clear_region(rgba, (prev, 0, left, h)) prev = right if prev < w: - rgba.paste(cut.crop((prev, 0, w, h)), (prev, 0)) + _clear_region(rgba, (prev, 0, w, h)) return rgba def _erase_long_axis_lines(image): """Remove thin slot-spanning guide/floor/divider lines. - Gemini will sometimes satisfy "baseline" / "cell" language by drawing - literal horizontal floors or vertical panel dividers. They survive chroma - keying and connect otherwise clean poses. Drop only *thin* rows/columns that - span nearly the whole slot; thick sprite body rows are left alone. + Models sometimes draw literal floors or panel dividers; they survive keying + and connect otherwise clean poses. Only *thin* near-full-span rows/columns go. """ - from PIL import Image - rgba = image.convert("RGBA").copy() w, h = rgba.size alpha = rgba.getchannel("A") def _thin_groups(indices: list[int]) -> list[tuple[int, int]]: groups: list[tuple[int, int]] = [] - start: int | None = None - prev: int | None = None - for idx in indices: - if start is None: - start = prev = idx - continue - if prev is not None and idx == prev + 1: + start = prev = -2 + for idx in [*indices, -2]: # -2 sentinel flushes the last run + if start >= 0 and idx == prev + 1: prev = idx continue - if start is not None and prev is not None and prev - start + 1 <= 4: + if start >= 0 and prev - start + 1 <= 4: groups.append((start, prev + 1)) start = prev = idx - if start is not None and prev is not None and prev - start + 1 <= 4: - groups.append((start, prev + 1)) return groups - wide_rows = [ - y - for y in range(h) - if sum(1 for x in range(w) if alpha.getpixel((x, y)) > _ALPHA_FLOOR) >= w * 0.85 - ] - tall_cols = [ - x - for x in range(w) - if sum(1 for y in range(h) if alpha.getpixel((x, y)) > _ALPHA_FLOOR) >= h * 0.85 - ] + wide_rows = [y for y in range(h) if sum(1 for x in range(w) if alpha.getpixel((x, y)) > _ALPHA_FLOOR) >= w * 0.85] + tall_cols = [x for x in range(w) if sum(1 for y in range(h) if alpha.getpixel((x, y)) > _ALPHA_FLOOR) >= h * 0.85] - clear = Image.new("RGBA", rgba.size, (0, 0, 0, 0)) for top, bottom in _thin_groups(wide_rows): - rgba.paste(clear.crop((0, top, w, bottom)), (0, top)) + _clear_region(rgba, (0, top, w, bottom)) for left, right in _thin_groups(tall_cols): - rgba.paste(clear.crop((left, 0, right, h)), (left, 0)) + _clear_region(rgba, (left, 0, right, h)) return rgba def _component_boxes(image) -> list[tuple[tuple[int, int, int, int], int]]: - """Connected opaque components as ``[(bbox, mass)]``. - - A full ML segmenter would be overkill here: after chroma keying, "the pet" is - the dominant connected alpha component inside each known slot. Tiny detached - sparkles, tears, UI dots, and neighbour slivers are separate components. - """ - from collections import deque - + """Connected opaque components as ``[(bbox, mass)]``.""" rgba = image.convert("RGBA") bbox = rgba.getbbox() if bbox is None: @@ -453,42 +362,20 @@ def _component_boxes(image) -> list[tuple[tuple[int, int, int, int], int]]: l0, t0, r0, b0 = bbox w, h = r0 - l0, b0 - t0 alpha = rgba.getchannel("A").load() - visited = bytearray(w * h) out: list[tuple[tuple[int, int, int, int], int]] = [] - for start in range(w * h): - if visited[start]: - continue - sx, sy = start % w, start // w - ax, ay = l0 + sx, t0 + sy - visited[start] = 1 - if alpha[ax, ay] <= _ALPHA_FLOOR: - continue + def _opaque(x: int, y: int) -> bool: + return alpha[l0 + x, t0 + y] > _ALPHA_FLOOR - queue: deque[tuple[int, int]] = deque([(sx, sy)]) - left = right = sx - top = bottom = sy - mass = 0 - while queue: - x, y = queue.popleft() - mass += 1 - left, right = min(left, x), max(right, x) - top, bottom = min(top, y), max(bottom, y) - for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)): - if 0 <= nx < w and 0 <= ny < h: - idx = ny * w + nx - if not visited[idx]: - visited[idx] = 1 - if alpha[l0 + nx, t0 + ny] > _ALPHA_FLOOR: - queue.append((nx, ny)) - out.append(((l0 + left, t0 + top, l0 + right + 1, t0 + bottom + 1), mass)) + for pixels in _unvisited_components(w, h, bytearray(w * h), _opaque): + xs = [x for x, _ in pixels] + ys = [y for _, y in pixels] + out.append(((l0 + min(xs), t0 + min(ys), l0 + max(xs) + 1, t0 + max(ys) + 1), len(pixels))) return out def _isolate_slot_subject(image): """Keep the slot's real subject; drop detached effects/noise.""" - from PIL import Image - rgba = _erase_long_axis_lines(image) comps = _component_boxes(rgba) if not comps: @@ -506,42 +393,30 @@ def _isolate_slot_subject(image): overlap = max(0, min(right, mr) - max(left, ml)) center_x = (left + right) / 2 near_main = (ml - mw * 0.25) <= center_x <= (mr + mw * 0.25) - # Keep meaningful attached-looking accessories such as halos; drop - # sparkles/tears/noise that don't overlap the body column. + # Keep attached-looking accessories (halos); drop sparkles/tears/noise. if mass >= max(24, main_mass * 0.035) and (overlap >= mw * 0.3 or near_main): keep.append(box) - out = Image.new("RGBA", rgba.size, (0, 0, 0, 0)) + out = _blank(rgba.size) for box in keep: out.alpha_composite(rgba.crop(box), (box[0], box[1])) return out -def _has_slot_padding(image) -> bool: - """True when content has empty room on all four slot edges.""" - bbox = image.getbbox() - if bbox is None: - return False - w, h = image.size - left, top, right, bottom = bbox - min_x = max(4, min(12, round(w * 0.025))) - min_y = max(4, min(16, round(h * 0.02))) +def _has_margin(size: tuple[int, int], box: tuple[int, int, int, int], fx: float, fy: float) -> bool: + """True when *box* leaves empty room on all four edges of an image of *size* (≥4px, ≤12/16px).""" + w, h = size + left, top, right, bottom = box + min_x = max(4, min(12, round(w * fx))) + min_y = max(4, min(16, round(h * fy))) return left >= min_x and top >= min_y and w - right >= min_x and h - bottom >= min_y -def _slot_bounds(width: int, frame_count: int) -> list[tuple[int, int]]: - return [ - (round(i * width / frame_count), round((i + 1) * width / frame_count)) - for i in range(frame_count) - ] - - def _group_component_rows(boxes: list[tuple[int, int, int, int]]) -> list[list[tuple[int, int, int, int]]]: """Group component boxes into visual rows, then sort left→right.""" if not boxes: return [] - heights = sorted(max(1, b[3] - b[1]) for b in boxes) - row_tol = max(12, heights[len(heights) // 2] * 0.55) + row_tol = max(12, _median(max(1, b[3] - b[1]) for b in boxes) * 0.55) rows: list[list[tuple[int, int, int, int]]] = [] centers: list[float] = [] for box in sorted(boxes, key=lambda b: (b[1] + b[3]) / 2): @@ -561,12 +436,10 @@ def _group_component_rows(boxes: list[tuple[int, int, int, int]]) -> list[list[t def _merge_related_boxes(boxes: list[tuple[int, int, int, int]]) -> list[tuple[int, int, int, int]]: - """Merge disconnected parts that clearly belong to one subject. + """Merge disconnected parts of one subject (capes, tails, props) on the same row. - Capes, tails, horns, and held props sometimes key as separate components. - Merge components on the same visual row when their vertical spans overlap and - the horizontal gap is tiny compared with the component size. Do not bridge the - much larger gaps between separate poses. + Merges when vertical spans overlap and the horizontal gap is tiny relative to + the component size; never bridges the larger gaps between separate poses. """ boxes = list(boxes) changed = True @@ -599,21 +472,13 @@ def _merge_related_boxes(boxes: list[tuple[int, int, int, int]]) -> list[tuple[i def _component_crops(strip, frame_count: int, *, require_padding: bool = False) -> list | None: """Extract frame subjects as connected non-background objects. - This is the robust path for models that ignore "one horizontal row" and emit a - 2D sprite grid. We count real opaque subject components, discard tiny - detached effects, sort in reading order, and return exactly *frame_count* - frames. Slot slicing is only a fallback when object detection can't satisfy - the contract. + Robust path for models that emit a 2D grid instead of one row: count real + subject components, discard tiny effects, sort in reading order, return + exactly *frame_count* frames (or ``None`` when the contract can't be met). """ - from PIL import Image def attempt(source) -> list | None: - comps = _component_boxes(source) - if not comps: - return None - - max_mass = max(m for _box, m in comps) - subjects = _merge_related_boxes([box for box, mass in comps if mass >= max(64, max_mass * 0.12)]) + subjects = _significant_subject_boxes(source, min_mass=64) if len(subjects) < frame_count: return None @@ -622,12 +487,8 @@ def _component_crops(strip, frame_count: int, *, require_padding: bool = False) if len(ordered) < frame_count: return None - if require_padding: - min_x = max(4, min(12, round(source.width * 0.01))) - min_y = max(4, min(16, round(source.height * 0.015))) - for left, top, right, bottom in ordered: - if left < min_x or top < min_y or source.width - right < min_x or source.height - bottom < min_y: - return None + if require_padding and not all(_has_margin(source.size, box, 0.01, 0.015) for box in ordered): + return None multirow = len(rows) > 1 frames = [] @@ -644,82 +505,73 @@ def _component_crops(strip, frame_count: int, *, require_padding: bool = False) elif frame_count == 1: crop_box = (0, 0, source.width, source.height) else: - # Preserve vertical motion for true one-row strips (jumping, - # bobbing) while still narrowing X around the object. + # Keep full height for true one-row strips so vertical motion survives. crop_box = (max(0, left - pad_x), 0, min(source.width, right + pad_x), source.height) - frame = Image.new("RGBA", (crop_box[2] - crop_box[0], crop_box[3] - crop_box[1]), (0, 0, 0, 0)) - rel = (left - crop_box[0], top - crop_box[1], right - crop_box[0], bottom - crop_box[1]) - frame.alpha_composite(source.crop((left, top, right, bottom)), (rel[0], rel[1])) - # The global component pass already chose the subject box. Do not run - # another component filter here: capes/tails can be legitimate + # No second component filter here: capes/tails can be legitimate # disconnected lobes inside the chosen subject box. - frames.append(frame) + frames.append( + _place( + source.crop((left, top, right, bottom)), + (crop_box[2] - crop_box[0], crop_box[3] - crop_box[1]), + (left - crop_box[0], top - crop_box[1]), + ) + ) return frames return attempt(strip) or attempt(_erase_long_axis_lines(strip)) def _sever_expected_gutters(strip, frame_count: int): - """Cut thin vertical gutters at expected frame boundaries before labeling. + """Cut narrow transparent bands at expected frame boundaries before labeling. - Generated rows often have a shared shadow, glow, motion smear, or 1px bridge - that connects neighbouring poses. Component detection then sees one giant - blob and either fails or falls back to slot slicing. We know the requested - frame count, so cut a very narrow transparent band at each expected boundary - before connected-component labeling. If a pose truly overlaps the boundary, - losing a few pixels is better than exporting merged frames. + Shared shadows/smears/1px bridges connect neighbouring poses into one blob; + losing a few boundary pixels beats exporting merged frames. """ if frame_count <= 1: return strip out = strip.copy() - px = out.load() + alpha = out.getchannel("A") # zero alpha only; RGB is left untouched slot = out.width / frame_count half = max(3, min(18, round(slot * 0.06))) for i in range(1, frame_count): x = round(i * slot) - left = max(0, x - half) - right = min(out.width, x + half + 1) - for gx in range(left, right): - for gy in range(out.height): - r, g, b, _a = px[gx, gy] - px[gx, gy] = (r, g, b, 0) + alpha.paste(0, (max(0, x - half), 0, min(out.width, x + half + 1), out.height)) + out.putalpha(alpha) return out -def _slot_crops(strip, frame_count: int, *, require_padding: bool = False) -> list | None: - """Slice *strip* into *frame_count* uniform columns (one coordinate space). +def _clean_slot(image): + return _drop_side_bleed(_isolate_slot_subject(image)) - Equal-width columns keep every frame in a single shared coordinate frame, so - a later union-crop + shared placement (:func:`normalize_cells`) preserves the - row's real motion without the per-frame re-centering that makes a pet visibly - slide. Each slot is cleaned independently so detached effects, floors, - dividers, and neighbour slivers do not become "frames". + +def _slot_crops(strip, frame_count: int, *, require_padding: bool = False) -> list | None: + """Slice *strip* into *frame_count* uniform, independently cleaned columns. + + Equal-width columns keep every frame in one shared coordinate frame so + :func:`normalize_cells` preserves the row's real motion without sliding. """ - h = strip.height + w, h = strip.size frames = [] - for left, right in _slot_bounds(strip.width, frame_count): - slot = _drop_side_bleed(_isolate_slot_subject(strip.crop((left, 0, right, h)))) - if require_padding and not _has_slot_padding(slot): + for i in range(frame_count): + slot = _clean_slot(strip.crop((round(i * w / frame_count), 0, round((i + 1) * w / frame_count), h))) + bbox = slot.getbbox() + if require_padding and (bbox is None or not _has_margin(slot.size, bbox, 0.025, 0.02)): return None frames.append(slot) return frames -def _content_runs(profile: list[int], *, threshold: int = 2) -> list[tuple[int, int]]: - """Contiguous column spans whose alpha mass exceeds *threshold*. - - A column-projection of the alpha mask: empty (background) columns separate - one pose from the next, so the runs ARE the candidate frames. - """ - runs: list[tuple[int, int]] = [] +def _content_runs(profile: list[int], *, threshold: int = 2) -> list[tuple[tuple[int, int], int]]: + """``[((left, right), mass)]`` column spans whose alpha exceeds *threshold* (candidate frames).""" + runs: list[tuple[tuple[int, int], int]] = [] start: int | None = None for x, v in enumerate(list(profile) + [0]): if v > threshold: if start is None: start = x elif start is not None: - runs.append((start, x)) + runs.append(((start, x), sum(profile[start:x]))) start = None return runs @@ -727,55 +579,46 @@ def _content_runs(profile: list[int], *, threshold: int = 2) -> list[tuple[int, def _frame_x_ranges(strip, frame_count: int) -> list[tuple[int, int]] | None: """Per-frame ``(left, right)`` column ranges from the row's empty gutters. - The standard sprite-sheet slice — once poses are separated by real gaps - (which generation now enforces), splitting is just "find the empty columns": - - * spans == frames → one span per frame. - * spans > frames → merge across the smallest gaps. A detached halo/ear sits - a tiny gap from its body, while the inter-pose gutter is the big gap that - survives — so over-segmentation (and any over-eager gutter sever) repairs - itself by collapsing only the small internal gaps. - * spans < frames → poses are touching; not separable by gutters (the caller - raises for ``components`` or falls back to even slots for ``auto``). - - Ranges span content only; the caller crops full cell height, so tall ears / - halos are never cut. + spans == frames → one per frame; spans > frames → merge across the smallest + gaps (a detached halo sits a tiny gap from its body, the inter-pose gutter is + the big gap that survives); spans < frames → ``None`` (poses touching). + Ranges span X only; the caller crops full height so tall ears/halos survive. """ - profile = _column_profile(strip) - runs = _content_runs(profile) + runs = _content_runs(_column_profile(strip)) if not runs: return None - # Drop trivial specks so stray noise never counts as a pose. - masses = [sum(profile[l:r]) for l, r in runs] - floor = max(masses) * 0.02 - runs = [run for run, m in zip(runs, masses) if m >= floor] - if len(runs) < frame_count: + floor = max(m for _run, m in runs) * 0.02 + groups = [[l, r] for (l, r), m in runs if m >= floor] + if len(groups) < frame_count: return None - groups = [[l, r] for l, r in runs] while len(groups) > frame_count: gi = min(range(len(groups) - 1), key=lambda i: groups[i + 1][0] - groups[i][1]) groups[gi][1] = groups[gi + 1][1] del groups[gi + 1] - return [(l, r) for l, r in groups] + return [tuple(g) for g in groups] -def _significant_subject_boxes(image) -> list[tuple[int, int, int, int]]: +def _significant_subject_boxes(image, *, min_mass: int = 32) -> list[tuple[int, int, int, int]]: + """Merged boxes of components carrying meaningful mass (≥12% of the largest).""" comps = _component_boxes(image) if not comps: return [] max_mass = max(mass for _box, mass in comps) - return _merge_related_boxes([box for box, mass in comps if mass >= max(32, max_mass * 0.12)]) + return _merge_related_boxes([box for box, mass in comps if mass >= max(min_mass, max_mass * 0.12)]) + + +def _is_multi_pose_outlier(width: int, height: int, med_w: int, med_h: int) -> bool: + """A frame several times wider than the median but not proportionally taller.""" + return width > max(med_w * 3.0, med_w + 96) and height <= med_h * 1.6 def _validate_extracted_frames(frames: list, frame_count: int) -> None: """Reject rows where one "frame" is really multiple poses. - A bad provider roll can collapse a strip into tiny repeated poses. If we let - that through, normalization sees a huge motion envelope and shrinks the - entire pet to postage-stamp size. Catch the row here so hatch can regenerate - it instead of saving a technically non-empty but visually broken atlas. + A collapsed strip of tiny repeated poses would make normalization shrink the + whole pet to postage-stamp size; catching it here lets hatch regenerate. """ if len(frames) != frame_count: raise ValueError(f"expected {frame_count} frames, got {len(frames)}") @@ -785,25 +628,17 @@ def _validate_extracted_frames(frames: list, frame_count: int) -> None: bbox = frame.getbbox() if bbox is None: raise ValueError(f"frame {i} is empty") - subjects = _significant_subject_boxes(frame) - if len(subjects) >= 3: + if len(_significant_subject_boxes(frame)) >= 3: raise ValueError(f"frame {i} contains multiple separated subjects") boxes.append(bbox) if frame_count <= 1: return - widths = sorted(b[2] - b[0] for b in boxes) - heights = sorted(b[3] - b[1] for b in boxes) - med_w = max(1, widths[len(widths) // 2]) - med_h = max(1, heights[len(heights) // 2]) + med_w = max(1, _median(b[2] - b[0] for b in boxes)) + med_h = max(1, _median(b[3] - b[1] for b in boxes)) for i, (left, top, right, bottom) in enumerate(boxes): - width = right - left - height = bottom - top - # A legitimate wing/arm can be wider than the median pose. A frame that is - # several times wider while not proportionally taller is usually multiple - # mini-poses packed into one accepted frame. - if width > max(med_w * 3.0, med_w + 96) and height <= med_h * 1.6: + if _is_multi_pose_outlier(right - left, bottom - top, med_w, med_h): raise ValueError(f"frame {i} is a multi-pose width outlier") @@ -817,45 +652,21 @@ def extract_strip_frames( ) -> list: """Turn one generated row strip into *frame_count* frames. - The background is keyed out, then strict extraction treats the requested - frame count as the source of truth: slice known equal slots, isolate the real - subject in each slot, and require empty padding on X and Y. Empty chroma - gutters are only a lenient salvage fallback. - - Each frame is cropped at full cell height so tall ears / halos are never - clipped; detached effects and neighbour slivers are dropped per slot. When a - pose does not have required space around it, ``components`` raises and - ``auto`` falls back to best-effort slicing. - - *fit* (default) fits+centers each frame into a 192x208 cell — the standalone - contract for callers that don't normalize. Hatching passes ``fit=False`` to - keep raw, coordinate-aligned columns for :func:`normalize_cells`, which lays - one shared scale + baseline across the whole pet (no slide, no size pulse). + Keys out the background, then treats the frame count as source of truth: + isolate padded subjects (component pass, then equal slots). When that fails, + ``components`` raises and ``auto`` falls back to lenient salvage (gutters → + severed gutters → raw slots). *fit* centers each frame into a 192x208 cell; + hatching passes ``fit=False`` so :func:`normalize_cells` can register the + whole pet with one shared scale + baseline. """ - from PIL import Image + strip = remove_background(_load_rgba(strip), chroma_key=chroma_key) - if isinstance(strip, (str, Path)): - with Image.open(strip) as opened: - strip = opened.convert("RGBA") - else: - strip = strip.convert("RGBA") - - strip = remove_background(strip, chroma_key=chroma_key) - - # Strict path: count actual non-background subjects first. This handles both - # the intended one-row strip and model-cheated 2D grids without ever stacking - # two visual rows into one frame. frames = _component_crops(strip, frame_count, require_padding=True) if frames is None: frames = _slot_crops(strip, frame_count, require_padding=True) if frames is None: if method == "components": raise ValueError(f"could not segment {frame_count} padded sprites from strip") - - # Lenient salvage for the final attempt: prefer real gutters when they - # exist, then sever expected boundaries, then fall back to raw slots. Still - # try object extraction first, just without edge-padding enforcement, so - # cached/borderline model rolls can be inspected without stacking a 2D grid. frames = _component_crops(strip, frame_count, require_padding=False) if frames is None: source = strip @@ -870,7 +681,7 @@ def extract_strip_frames( h = source.height pad = max(2, min(16, round((source.width / max(1, frame_count)) * 0.04))) frames = [ - _drop_side_bleed(_isolate_slot_subject(source.crop((max(0, left - pad), 0, min(source.width, right + pad), h)))) + _clean_slot(source.crop((max(0, left - pad), 0, min(source.width, right + pad), h))) for left, right in ranges ] _validate_extracted_frames(frames, frame_count) @@ -878,110 +689,76 @@ def extract_strip_frames( def _column_profile(image) -> list[int]: - """Per-column alpha mass — collapse the frame to a 1px-tall strip (fast in C).""" + """Per-column alpha mass — collapse to a 1px-tall strip (fast in C).""" from PIL import Image return list(image.getchannel("A").resize((image.width, 1), Image.BILINEAR).getdata()) def _best_shift(ref: list[int], prof: list[int], window: int) -> int: - """Integer dx that best aligns *prof* onto *ref* by cross-correlation. + """Integer dx that best aligns *prof* onto *ref* (1-D cross-correlation). - This is 1-D phase correlation: the body is the dominant mass in the column - profile, so the peak overlap locks onto the body and a flipping arm/cape (a - small secondary bump) doesn't move the match. Proven on the jitter case to - cut body drift from ~9px to ~1px where a centroid/bbox anchor cannot. + The body dominates the column profile, so the peak locks onto the body and a + flipping arm/cape barely moves the match (~9px drift → ~1px). """ n = len(ref) - best_score: float | None = None - best = 0 - for d in range(-window, window + 1): - score = 0 - for x in range(max(0, d), min(n, n + d)): - score += ref[x] * prof[x - d] - if best_score is None or score > best_score: - best_score = score - best = d - return best + + def score(d: int) -> int: + return sum(ref[x] * prof[x - d] for x in range(max(0, d), min(n, n + d))) + + return max(range(-window, window + 1), key=score) # ties → smallest dx, as before def normalize_cells(frames_by_state: dict[str, list], *, pad: int = _NORMALIZE_PAD) -> dict[str, list]: """Register every frame into a 192x208 cell — the deterministic anti-jitter math. - A per-frame "crop→scale→center" pipeline jitters because a moving limb/cape - shifts the bbox (or even the centroid) and a per-frame scale pulses the size. - The rigorous fix, matching image-registration practice (phase correlation) - and AI-sprite pipelines (perfectpixel-studio / sprite-gen): - - 1. **Cross-correlate** each frame's column profile against the per-state - *median* profile to find the integer shift that locks the **body** in - place — robust to limbs/cape because the body dominates the profile. - 2. **Union-crop** through one shared state window, then scale every state by a - single global factor keyed to its median pose height, so the character is - the same on-screen size in every row while a jump's lift still fits. + Per-frame crop→scale→center jitters (bbox shifts with a limb, per-frame scale + pulses). Instead: cross-correlate each frame's column profile against the + state's median profile to lock the body, union-crop through one shared state + window, then scale every state by a single global factor keyed to its median + pose height so the character is the same size in every row. """ from PIL import Image - blank = lambda: Image.new("RGBA", (CELL_WIDTH, CELL_HEIGHT), (0, 0, 0, 0)) - med = lambda vs: sorted(vs)[len(vs) // 2] # robust center; ignores a limb/cape outlier - out: dict[str, list] = {} prepared: dict[str, tuple[list, tuple[int, int, int, int], tuple[int, int]]] = {} - # Fill the cell — real petdex pets sit ~pad from the edges; the K cap below - # keeps a tall pose (a jump's lift) from clipping. target_w = CELL_WIDTH - pad target_h = CELL_HEIGHT - pad for state, frames in frames_by_state.items(): rgba = [f.convert("RGBA") for f in frames] if not any(f.getbbox() for f in rgba): - out[state] = [blank() for _ in frames] + out[state] = [_blank() for _ in frames] continue # Pad every frame to a common canvas so column profiles are comparable. w0 = max(f.width for f in rgba) h0 = max(f.height for f in rgba) - canvas = [] - for f in rgba: - if f.size != (w0, h0): - c = Image.new("RGBA", (w0, h0), (0, 0, 0, 0)) - c.alpha_composite(f, (0, 0)) - f = c - canvas.append(f) + canvas = [f if f.size == (w0, h0) else _place(f, (w0, h0)) for f in rgba] - # Register horizontally: shift each frame to lock the body (xcorr). profiles = [_column_profile(f) for f in canvas] - ref = [sorted(p[x] for p in profiles)[len(profiles) // 2] for x in range(w0)] + ref = [_median(p[x] for p in profiles) for x in range(w0)] window = max(8, w0 // 5) margin = window - aligned = [] - for f, prof in zip(canvas, profiles): - shifted = Image.new("RGBA", (w0 + 2 * margin, h0), (0, 0, 0, 0)) - shifted.alpha_composite(f, (margin + _best_shift(ref, prof, window), 0)) - aligned.append(shifted) + aligned = [ + _place(f, (w0 + 2 * margin, h0), (margin + _best_shift(ref, prof, window), 0)) + for f, prof in zip(canvas, profiles) + ] - # Shared window over the registered set; scale is resolved against a - # common apparent-character target below. boxes = [b for b in (a.getbbox() for a in aligned) if b] - left = min(b[0] for b in boxes) - top = min(b[1] for b in boxes) - right = max(b[2] for b in boxes) - bottom = max(b[3] for b in boxes) prepared[state] = ( aligned, - (left, top, right, bottom), - (med([b[2] - b[0] for b in boxes]), med([b[3] - b[1] for b in boxes])), + (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)), + (_median(b[2] - b[0] for b in boxes), _median(b[3] - b[1] for b in boxes)), ) if not prepared: return out - # Uniform apparent size: scale each state by K / pose_h, so a row the model - # drew small renders as big as one it drew large. K is the one global cap that - # keeps the tallest/widest motion envelope (a jump's lift) inside the cell — - # for a still row union ≈ pose so its term ≈ target_h (full fill). + # K is the one global cap keeping the tallest/widest motion envelope (a + # jump's lift) inside the cell; a still row's union ≈ pose so it fills fully. K = target_h - for (_aligned, (left, top, right, bottom), (_pose_w, pose_h)) in prepared.values(): + for _aligned, (left, top, right, bottom), (_pose_w, pose_h) in prepared.values(): uw, uh = right - left, bottom - top K = min(K, target_h * pose_h / max(1, uh), target_w * pose_h / max(1, uw)) @@ -995,11 +772,8 @@ def normalize_cells(frames_by_state: dict[str, list], *, pad: int = _NORMALIZE_P for a in aligned: crop = a.crop((left, top, right, bottom)) if crop.size != (sw, sh): - # NEAREST keeps the pixel-art edges crisp; LANCZOS blurred them. - crop = crop.resize((sw, sh), Image.Resampling.NEAREST) - cell = blank() - cell.alpha_composite(crop, (px, py)) - cells.append(cell) + crop = crop.resize((sw, sh), Image.Resampling.NEAREST) # keep pixel edges crisp + cells.append(_place(crop, (CELL_WIDTH, CELL_HEIGHT), (px, py))) out[state] = cells return out @@ -1008,18 +782,12 @@ def normalize_cells(frames_by_state: dict[str, list], *, pad: int = _NORMALIZE_P def single_frame(image, *, fit: bool = True): - """One frame from a standalone image (e.g. the base look). + """One frame from a standalone image (idle fallback so a pet always renders). - Used as an idle fallback so a pet always renders even if the idle row - generation failed. *fit* yields a finished 192x208 cell; ``fit=False`` yields - the raw keyed sprite for :func:`normalize_cells` to place with the rest. + *fit* yields a finished cell; ``fit=False`` the raw keyed sprite for + :func:`normalize_cells`. """ - from PIL import Image - - if isinstance(image, (str, Path)): - with Image.open(image) as opened: - image = opened.convert("RGBA") - keyed = remove_background(image) + keyed = remove_background(_load_rgba(image)) return _fit_to_cell(keyed) if fit else _drop_side_bleed(keyed) @@ -1036,12 +804,9 @@ def _clear_transparent_rgb(image): def mirror_frames(frames: list) -> list: - """Horizontally flip each frame *in place* (RGBA-safe). + """Flip each frame horizontally (per-frame, so order/timing is preserved). - Used to derive ``running-left`` from an approved ``running-right`` row. The - flip is per-frame so the leftward loop preserves the rightward loop's frame - order and timing — this is NOT a whole-strip reverse (which would play the - animation backwards), matching the petdex/Codex mirror rule. + Derives ``running-left`` from ``running-right``; NOT a strip reverse. """ from PIL import Image @@ -1050,14 +815,8 @@ def mirror_frames(frames: list) -> list: def compose_atlas(frames_by_state: dict[str, list]): - """Pack per-state frame lists into the Hermes atlas (RGBA, residue-cleared). - - Missing/short states leave their trailing cells transparent; extra frames - beyond a state's spec are dropped. - """ - from PIL import Image - - atlas = Image.new("RGBA", (ATLAS_WIDTH, ATLAS_HEIGHT), (0, 0, 0, 0)) + """Pack per-state frame lists into the atlas; short states leave trailing cells transparent.""" + atlas = _blank((ATLAS_WIDTH, ATLAS_HEIGHT)) for state, row, count in ROW_SPECS: frames = frames_by_state.get(state) or [] for col, frame in enumerate(frames[:count]): @@ -1068,46 +827,42 @@ def compose_atlas(frames_by_state: dict[str, list]): return _clear_transparent_rgb(atlas) -def atlas_to_webp_bytes(atlas) -> bytes: - """Encode an atlas image to lossless WebP bytes (the on-disk pet format).""" - buf = io.BytesIO() - atlas.save(buf, format="WEBP", lossless=True, quality=100, method=6, exact=True) - return buf.getvalue() - - def validate_atlas(atlas) -> dict: """Check geometry, per-cell occupancy, and transparency invariants. - Returns ``{ok, width, height, errors, warnings, filled_states}``. Errors are - blockers (wrong size, empty used cell, opaque/dirty transparency); warnings - are soft (a whole state row blank — generation likely dropped a row). + Returns ``{ok, width, height, errors, warnings, filled_states}``; errors are + blockers, warnings soft (a whole state row blank). """ - from PIL import Image - - if isinstance(atlas, (str, Path)): - with Image.open(atlas) as opened: - atlas = opened.convert("RGBA") + atlas = _load_rgba(atlas) + if atlas.size != (ATLAS_WIDTH, ATLAS_HEIGHT): + errors: list[str] = [f"expected {ATLAS_WIDTH}x{ATLAS_HEIGHT}, got {atlas.width}x{atlas.height}"] + warnings: list[str] = [] + filled_states: list[str] = [] else: - atlas = atlas.convert("RGBA") + errors, warnings, filled_states = _check_atlas_cells(atlas) + return { + "ok": not errors, + "width": atlas.width, + "height": atlas.height, + "errors": errors, + "warnings": warnings, + "filled_states": filled_states, + } + +def _check_atlas_cells(atlas) -> tuple[list[str], list[str], list[str]]: + """Occupancy/collapse/residue checks for a correctly-sized atlas → ``(errors, warnings, filled_states)``.""" errors: list[str] = [] warnings: list[str] = [] - - if atlas.size != (ATLAS_WIDTH, ATLAS_HEIGHT): - errors.append(f"expected {ATLAS_WIDTH}x{ATLAS_HEIGHT}, got {atlas.width}x{atlas.height}") - return {"ok": False, "width": atlas.width, "height": atlas.height, "errors": errors, "warnings": warnings, "filled_states": []} - filled_states: list[str] = [] cell_boxes_by_state: dict[str, list[tuple[int, int, int, int]]] = {} for state, row, count in ROW_SPECS: row_pixels = 0 boxes: list[tuple[int, int, int, int]] = [] for col in range(count): - left = col * CELL_WIDTH - top = row * CELL_HEIGHT + left, top = col * CELL_WIDTH, row * CELL_HEIGHT cell = atlas.crop((left, top, left + CELL_WIDTH, top + CELL_HEIGHT)) - nonblank = sum(cell.getchannel("A").histogram()[1:]) - row_pixels += nonblank + row_pixels += sum(cell.getchannel("A").histogram()[1:]) bbox = cell.getbbox() if bbox is not None: boxes.append(bbox) @@ -1120,64 +875,35 @@ def validate_atlas(atlas) -> dict: if not filled_states: errors.append("atlas is empty — no state produced any frames") - # A visually valid pet must occupy the cell. A single bad row can otherwise - # poison global normalization and shrink every state to a tiny postage stamp - # while still passing the old "non-empty cells" check. - all_widths = sorted( - right - left - for boxes in cell_boxes_by_state.values() - for left, _top, right, _bottom in boxes - ) - all_heights = sorted( - bottom - top - for boxes in cell_boxes_by_state.values() - for _left, top, _right, bottom in boxes - ) - global_med_w = 0 - global_med_h = 0 - if all_widths and all_heights: - global_med_w = all_widths[len(all_widths) // 2] - median_h = all_heights[len(all_heights) // 2] - global_med_h = median_h - min_h = max(56, round(CELL_HEIGHT * 0.28)) - if median_h < min_h: - errors.append(f"atlas sprites are too small after normalization (median frame height {median_h}px)") + # A valid pet must occupy the cell: one bad row can poison global + # normalization and shrink every state while still passing "non-empty". + all_boxes = [b for boxes in cell_boxes_by_state.values() for b in boxes] + global_med_w = global_med_h = 0 + if all_boxes: + global_med_w = _median(r - l for l, _t, r, _b in all_boxes) + global_med_h = _median(b - t for _l, t, _r, b in all_boxes) + if global_med_h < max(56, round(CELL_HEIGHT * 0.28)): + errors.append(f"atlas sprites are too small after normalization (median frame height {global_med_h}px)") for state, boxes in cell_boxes_by_state.items(): if len(boxes) <= 1: continue - widths = sorted(right - left for left, _top, right, _bottom in boxes) - heights = sorted(bottom - top for _left, top, _right, bottom in boxes) - med_w = max(1, widths[len(widths) // 2]) - med_h = max(1, heights[len(heights) // 2]) - max_w = widths[-1] - max_h = heights[-1] - if max_w > max(med_w * 3.0, med_w + 96) and max_h <= med_h * 1.6: + widths = [right - left for left, _top, right, _bottom in boxes] + heights = [bottom - top for _left, top, _right, bottom in boxes] + med_w, med_h = max(1, _median(widths)), max(1, _median(heights)) + if _is_multi_pose_outlier(max(widths), max(heights), med_w, med_h): errors.append(f"state '{state}' contains a multi-pose frame outlier") - # Per-state collapse guard: one malformed row (tiny slivers / chopped - # fragments) should not pass because other rows are healthy. - if global_med_w and global_med_h: - min_state_w = max(32, round(global_med_w * 0.42)) - min_state_h = max(40, round(global_med_h * 0.50)) - if med_w < min_state_w or med_h < min_state_h: - errors.append( - f"state '{state}' appears collapsed (median {med_w}x{med_h}px, global median {global_med_w}x{global_med_h}px)" - ) + # Per-state collapse guard: one malformed row must not pass on the + # strength of the healthy ones. + if (global_med_w and global_med_h) and ( + med_w < max(32, round(global_med_w * 0.42)) or med_h < max(40, round(global_med_h * 0.50)) + ): + errors.append( + f"state '{state}' appears collapsed (median {med_w}x{med_h}px, global median {global_med_w}x{global_med_h}px)" + ) - # Transparent pixels must carry zero RGB (no halo residue). data = atlas.tobytes() - residue = 0 - for i in range(0, len(data), 4): - if data[i + 3] == 0 and (data[i] or data[i + 1] or data[i + 2]): - residue += 1 + residue = sum(1 for i in range(0, len(data), 4) if data[i + 3] == 0 and (data[i] or data[i + 1] or data[i + 2])) if residue: errors.append(f"{residue} transparent pixels retain RGB residue") - - return { - "ok": not errors, - "width": atlas.width, - "height": atlas.height, - "errors": errors, - "warnings": warnings, - "filled_states": filled_states, - } + return errors, warnings, filled_states diff --git a/agent/pet/generate/imagegen.py b/agent/pet/generate/imagegen.py index 4f5000fd70..65c4630e8e 100644 --- a/agent/pet/generate/imagegen.py +++ b/agent/pet/generate/imagegen.py @@ -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=` (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=`` 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: diff --git a/agent/pet/generate/orchestrate.py b/agent/pet/generate/orchestrate.py index 1b267a4de2..344cb9b897 100644 --- a/agent/pet/generate/orchestrate.py +++ b/agent/pet/generate/orchestrate.py @@ -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", ""). 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"]: diff --git a/agent/pet/manifest.py b/agent/pet/manifest.py index 98a0e4a3f7..9d23a28de6 100644 --- a/agent/pet/manifest.py +++ b/agent/pet/manifest.py @@ -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 diff --git a/agent/pet/render.py b/agent/pet/render.py index 6e3ec74fd7..3eb958ff7a 100644 --- a/agent/pet/render.py +++ b/agent/pet/render.py @@ -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) diff --git a/agent/pet/state.py b/agent/pet/state.py index a9ad5afd80..3385098a0e 100644 --- a/agent/pet/state.py +++ b/agent/pet/state.py @@ -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) diff --git a/agent/pet/store.py b/agent/pet/store.py index 42627c1ac8..fd1891ecc8 100644 --- a/agent/pet/store.py +++ b/agent/pet/store.py @@ -1,17 +1,10 @@ """On-disk pet store — install / list / resolve pets. -Pets live under ``get_hermes_home()/pets//`` 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// - 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//`` (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()//`` 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()//`` 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 ``) 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 ```` 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/.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 {} diff --git a/tests/agent/test_pet_generate.py b/tests/agent/test_pet_generate.py index 84d303281c..34cbe20ea2 100644 --- a/tests/agent/test_pet_generate.py +++ b/tests/agent/test_pet_generate.py @@ -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] From 4bfc55fbf05c2db988088dd90fcf3c2f5886b2a5 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 10:36:07 -0700 Subject: [PATCH 3/4] =?UTF-8?q?refactor(agent/runtime):=20hooks/guardrails?= =?UTF-8?q?/dispatch=20=E2=80=94=20unify=20shell-hook=20and=20webhook=20pl?= =?UTF-8?q?umbing,=20table-driven=20guardrail=20thresholds?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - shell_hooks is the shared home: _ToolMatcherMixin (matcher compile + matches_tool), _payload_fields, _forget_home_registrations, _home_key, _utc_now_iso now serve outbound_webhooks too (copies deleted; every log string byte-identical). - shell_hooks: response parsing is a per-event dispatch table; _spawn diagnostic dict + _evaluate_result shared by the live callback and run_once; _locked_update_approvals POSIX/non-POSIX bodies merged via ExitStack. - tool_guardrails: ToolCallGuardrailConfig thresholds from a _THRESHOLD_SOURCES table (nested-wins-over-flat preserved); _int_at_least replaces _positive_int/_non_negative_int; observe_identical_call (0 refs) folded into observe_call; _halt helper for hard-stop decisions. - tool_dispatch_helpers: _plan_tool_batch_segments split into _batch_admission + close/extend helpers with the post-hoc normalization merged in. - Comment/docstring compaction keeping every stated rule. --- agent/outbound_webhooks.py | 304 +++------- agent/shell_hooks.py | 974 ++++++++++--------------------- agent/tool_dispatch_helpers.py | 662 +++++++-------------- agent/tool_guardrails.py | 779 ++++++++---------------- tests/agent/test_stall_guards.py | 29 +- 5 files changed, 847 insertions(+), 1901 deletions(-) diff --git a/agent/outbound_webhooks.py b/agent/outbound_webhooks.py index cd600832cb..7fcef908f1 100644 --- a/agent/outbound_webhooks.py +++ b/agent/outbound_webhooks.py @@ -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=`` 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=`` 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: - X-Hermes-Delivery: - X-Hermes-Signature-256: sha256= # 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( diff --git a/agent/shell_hooks.py b/agent/shell_hooks.py index 49dfa9301e..93667be8c8 100644 --- a/agent/shell_hooks.py +++ b/agent/shell_hooks.py @@ -1,135 +1,23 @@ -""" -Shell-script hooks bridge. +"""Shell-script hooks bridge. -Reads the ``hooks:`` block from ``cli-config.yaml``, prompts the user for -consent on first use of each ``(event, command)`` pair, and registers -callbacks on the existing plugin hook manager so every existing -``invoke_hook()`` site dispatches to the configured shell scripts — with -zero changes to call sites. +Reads the ``hooks:`` block from config, prompts for first-use consent per +``(event, command)`` pair, and registers callbacks on the plugin hook manager +so every existing ``invoke_hook()`` site dispatches to the configured scripts. -Design notes ------------- -* Python plugins and shell hooks compose naturally: both flow through - :func:`hermes_cli.plugins.invoke_hook` and its aggregators. Python - plugins are registered first (via ``discover_and_load()``) so their - block decisions win ties over shell-hook blocks. -* Subprocess execution uses ``shlex.split(os.path.expanduser(command))`` - with ``shell=False`` — no shell injection footguns. Users that need - pipes/redirection wrap their logic in a script. -* First-use consent is gated by the allowlist under - ``~/.hermes/shell-hooks-allowlist.json``. Non-TTY callers must pass - ``accept_hooks=True`` (resolved from ``--accept-hooks``, - ``HERMES_ACCEPT_HOOKS``, or ``hooks_auto_accept: true`` in config) - for registration to succeed without a prompt. -* Registration is idempotent — safe to invoke from both the CLI entry - point (``hermes_cli/main.py``) and the gateway entry point - (``gateway/run.py``). +Wire protocol — stdin JSON:: -Wire protocol -------------- -**stdin** (JSON, piped to the script):: + {"hook_event_name": ..., "tool_name": ..., "tool_input": {...}, + "session_id": ..., "cwd": ..., "extra": {...event-specific kwargs}} - { - "hook_event_name": "pre_tool_call", - "tool_name": "terminal", - "tool_input": {"command": "rm -rf /"}, - "session_id": "sess_abc123", - "cwd": "/home/user/project", - "extra": {...} # event-specific kwargs - } - -**stdout** (JSON, optional — anything else is ignored):: - - # Block a pre_tool_call (either shape accepted; normalised internally): - {"decision": "block", "reason": "Forbidden command"} # Claude-Code-style - {"action": "block", "message": "Forbidden command"} # Hermes-canonical - - # Inject context for pre_llm_call: - {"context": "Today is Friday"} - - # Modify tool input for pre_tool_call (Hermes-canonical): - {"action": "modify", "args": {"new_string": "fixed content"}} - - # Modify tool input for pre_tool_call (Claude-Code-style): - {"decision": "modify", "tool_input": {"new_string": "fixed content"}} - - # Silent no-op: - - -**exit codes** - -Exit code 2 from a ``pre_tool_call`` hook blocks the tool call even when -stdout carries no block JSON (Claude-Code / Cursor compatible). The block -message is taken from the stdout block JSON when present, then the first -400 characters of stderr, then a generic default. For events whose block -directive is not honored, exit 2 is logged at warning like any other -non-zero exit. All other non-zero exits log a warning and stdout is still -parsed normally. - -**failure semantics** - -Hooks fail *open* by default: a spawn error, timeout, or unparseable -stdout logs a warning and contributes nothing. A ``pre_tool_call`` entry -can opt into fail-*closed* semantics with ``fail_closed: true`` -(``failClosed`` also accepted for Cursor/Claude-Code config compat) — -spawn errors, timeouts, and malformed stdout then BLOCK the tool call -with ``hook failed closed: ``. Use this for -security-gating hooks (secret scanners, policy checks) where a crashed -hook must not silently allow the action. On non-blocking events -``fail_closed`` is ignored with a warning. - -Per-event ``extra`` keys -~~~~~~~~~~~~~~~~~~~~~~~~ - -The ``extra`` object contains every kwarg that is **not** one of the -top-level payload keys (``tool_name``, ``args``, ``session_id``, -``parent_session_id``). The tables below list the ``extra`` keys -emitted by each built-in hook site. - -``post_tool_call`` (emitted from ``model_tools.py``):: - - result – tool return value (serialised string) - status – "ok" | "error" | "blocked" - error_type – error category (e.g. "ValueError"), or None - error_message – human-readable error text, or None - duration_ms – wall-clock time in milliseconds - task_id – current task id (empty string if none) - tool_call_id – provider tool-call id - turn_id – current turn id - api_request_id – current API request id - middleware_trace – list of dicts from tool middleware chain - -``pre_tool_call`` (emitted from ``model_tools.py``):: - - task_id – current task id (empty string if none) - tool_call_id – provider tool-call id - turn_id – current turn id - api_request_id – current API request id - middleware_trace – list of dicts from tool middleware chain - -``on_session_start`` (emitted from ``agent/conversation_loop.py``):: - - model – model name (e.g. "claude-sonnet-4-20250514") - platform – platform identifier (e.g. "cli", "whatsapp") - -``on_session_end`` (emitted from ``agent/turn_finalizer.py``):: - - task_id – current task id - turn_id – current turn id - completed – bool, True when the turn produced a final response - interrupted – bool, True when the user interrupted - model – model name - platform – platform identifier - -``subagent_stop`` (emitted from ``tools/delegate_tool.py``):: - - parent_turn_id – parent agent's current turn id - child_session_id – child (subagent) session id - child_role – role string of the child agent - child_summary – summary of the child's work - child_status – exit status string (e.g. "success", "error") - tool_call_history – redacted tool name/input summary/byte counts/status list - duration_ms – wall-clock time of the child run in milliseconds +stdout JSON (optional): ``{"decision"|"action": "block", "reason"|"message": ...}`` +blocks a ``pre_tool_call``; ``{"action": "modify", "args": {...}}`` / +``{"decision": "modify", "tool_input": {...}}`` rewrites tool args; +``{"context": "..."}`` injects context for ``pre_llm_call``; ``pre_verify`` +accepts ``continue``/``block`` with a message. Exit code 2 blocks a +``pre_tool_call`` even without block JSON (Claude-Code / Cursor compatible). +Hooks fail open unless ``fail_closed: true`` (``failClosed`` accepted) on a +blocking-capable event, in which case spawn errors, timeouts and unparseable +stdout block with ``hook failed closed: ``. """ from __future__ import annotations @@ -139,13 +27,12 @@ import json import logging import os import re -import shlex import subprocess import sys import tempfile import threading import time -from contextlib import contextmanager +from contextlib import ExitStack, contextmanager from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path @@ -167,68 +54,95 @@ DEFAULT_TIMEOUT_SECONDS = 60 MAX_TIMEOUT_SECONDS = 300 ALLOWLIST_FILENAME = "shell-hooks-allowlist.json" _DEFAULT_BLOCK_MESSAGE = "Blocked by shell hook." - -# Exit code that signals "block this action" from a hook script, independent -# of stdout content. Claude Code / Cursor compatible. +# Exit code that signals "block this action" independent of stdout (Claude Code / Cursor). BLOCK_EXIT_CODE = 2 - -# Events whose block directive is actually honored downstream (see -# hermes_cli.plugins.get_pre_tool_call_block_message / _get_pre_tool_call_ -# directive_details). Exit-code-2 blocking and ``fail_closed`` only make -# sense for these. +# Events whose block directive is honored downstream; exit-2 blocking and fail_closed only apply here. _BLOCKING_EVENTS = frozenset({"pre_tool_call"}) - -# Cap on stderr excerpt reused as a block message. +_TOOL_EVENTS = frozenset({"pre_tool_call", "post_tool_call"}) _STDERR_MESSAGE_LIMIT = 400 +_TRUTHY = {"1", "true", "yes", "on"} +# kwargs promoted to top-level payload keys; everything else lands under ``extra``. +_TOP_LEVEL_PAYLOAD_KEYS = {"tool_name", "args", "session_id", "parent_session_id"} - -# (home, event, matcher, command) tuples that have been wired to the plugin -# manager in the current process. Matcher is part of the key because -# the same script can legitimately register for different matchers under -# the same event (e.g. one entry per tool the user wants to gate). 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 hook triples without the first profile's registration -# silently shadowing the rest. -# Second registration attempts for the exact same tuple become no-ops -# so the CLI and gateway can both call register_from_config() safely. +# (home, event, matcher, command) tuples wired to the plugin manager in this process. +# Matcher is in the key: one script may legitimately register per-tool under one event. +# Home is part of the key so multiplexed-gateway profiles (each with their own +# plugin manager) can register identical triples without shadowing each other. _registered: Set[Tuple[str, str, Optional[str], str]] = set() _registered_lock = threading.Lock() - -# Intra-process lock for allowlist read-modify-write on platforms that -# lack ``fcntl`` (non-POSIX). Kept separate from ``_registered_lock`` -# because ``register_from_config`` already holds ``_registered_lock`` when -# it triggers ``_record_approval`` — reusing it here would self-deadlock -# (``threading.Lock`` is non-reentrant). POSIX callers use the sibling -# ``.lock`` file via ``fcntl.flock`` and bypass this. +# Non-POSIX fallback for allowlist read-modify-write. Separate from +# _registered_lock, which register_from_config already holds when it triggers +# _record_approval (threading.Lock is non-reentrant). _allowlist_write_lock = threading.Lock() -@dataclass -class ShellHookSpec: - """Parsed and validated representation of a single ``hooks:`` entry.""" +def _home_key() -> str: + return str(get_hermes_home().expanduser().resolve()) - event: str - command: str - matcher: Optional[str] = None - timeout: int = DEFAULT_TIMEOUT_SECONDS - fail_closed: bool = False - compiled_matcher: Optional[re.Pattern] = field(default=None, repr=False) + +def _forget_home_registrations(registry: Set[tuple], lock: threading.Lock) -> None: + """Drop the current home's idempotence keys only (shared with outbound webhooks). + + A force-reload in profile A must never drop profile B's live registration. + """ + home_key = _home_key() + with lock: + registry.difference_update({k for k in registry if k[0] == home_key}) + + +def _split(command: str) -> List[str]: + # Windows-safe: plain shlex.split eats backslashes in paths. + from hermes_cli._subprocess_compat import split_command_line + + return split_command_line(command) + + +def _entry_matches(e: Any, event: Optional[str], command: str) -> bool: + return ( + isinstance(e, dict) + and (event is None or e.get("event") == event) + and e.get("command") == command + ) + + +def _utc_now_iso() -> str: + return datetime.now(tz=timezone.utc).isoformat().replace("+00:00", "Z") + + +def _payload_fields(kwargs: Dict[str, Any]) -> Dict[str, Any]: + """Common stdin/POST payload fields (shared with outbound webhooks); key order is wire order.""" + 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 = "" + return { + "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, + } + + +class _ToolMatcherMixin: + """``matcher`` regex handling shared by shell-hook specs and outbound webhook targets.""" + + _MATCHER_KIND = "shell hook" + matcher: Optional[str] + compiled_matcher: Optional[re.Pattern] def __post_init__(self) -> None: - # Strip whitespace introduced by YAML quirks (e.g. multi-line string - # folding) — a matcher of " terminal" would otherwise silently fail - # to match "terminal" without any diagnostic. + # Strip YAML folding whitespace — " terminal" would silently never match. if isinstance(self.matcher, str): - stripped = self.matcher.strip() - self.matcher = stripped if stripped else None + self.matcher = self.matcher.strip() or None if self.matcher: try: self.compiled_matcher = re.compile(self.matcher) except re.error as exc: logger.warning( - "shell hook matcher %r is invalid (%s) — treating as " - "literal equality", self.matcher, exc, + "%s matcher %r is invalid (%s) — treating as " + "literal equality", self._MATCHER_KIND, self.matcher, exc, ) self.compiled_matcher = None @@ -239,42 +153,37 @@ class ShellHookSpec: return False if self.compiled_matcher is not None: return self.compiled_matcher.fullmatch(tool_name) is not None - # compiled_matcher is None only when the regex failed to compile, - # in which case we already warned and fall back to literal equality. - return tool_name == self.matcher + return tool_name == self.matcher # regex failed to compile: literal fallback -# --------------------------------------------------------------------------- -# Public API -# --------------------------------------------------------------------------- +@dataclass +class ShellHookSpec(_ToolMatcherMixin): + """Parsed and validated representation of a single ``hooks:`` entry.""" + + event: str + command: str + matcher: Optional[str] = None + timeout: int = DEFAULT_TIMEOUT_SECONDS + fail_closed: bool = False + compiled_matcher: Optional[re.Pattern] = field(default=None, repr=False) + + +# --- Public API --- def register_from_config( cfg: Optional[Dict[str, Any]], *, accept_hooks: bool = False, ) -> List[ShellHookSpec]: - """Register every configured shell hook on the plugin manager. + """Register every configured shell hook on the plugin manager; idempotent. - ``cfg`` is the full parsed config dict (``hermes_cli.config.load_config`` - output). The ``hooks:`` key is read out of it. Missing, empty, or - non-dict ``hooks`` is treated as zero configured hooks. - - ``accept_hooks=True`` skips the TTY consent prompt — the caller is - promising that the user has opted in via a flag, env var, or config - setting. ``HERMES_ACCEPT_HOOKS=1`` and ``hooks_auto_accept: true`` are - also honored inside this function so either CLI or gateway call sites - pick them up. - - Returns the list of :class:`ShellHookSpec` entries that ended up wired - up on the plugin manager. Skipped entries (unknown events, malformed, - not allowlisted, already registered) are logged but not returned. + Returns the specs that were newly wired up. Skipped entries (unknown + events, malformed, not allowlisted, already registered) are logged only. """ if not isinstance(cfg, dict): return [] - # Safe mode (--safe-mode / HERMES_SAFE_MODE=1): shell hooks are user - # customizations too — skip registration entirely so a troubleshooting - # run fires zero user-configured code (plugins, MCP, AND hooks). + # Safe mode: hooks are user customizations too — fire zero user-configured code. from utils import env_var_enabled if env_var_enabled("HERMES_SAFE_MODE"): @@ -282,23 +191,18 @@ def register_from_config( return [] effective_accept = _resolve_effective_accept(cfg, accept_hooks) - specs = _parse_hooks_block(cfg.get("hooks")) if not specs: return [] registered: List[ShellHookSpec] = [] - - # Import lazily — avoids circular imports at module-load time. - from hermes_cli.plugins import get_plugin_manager + from hermes_cli.plugins import get_plugin_manager # lazy: avoids import cycle manager = get_plugin_manager() - home_key = str(get_hermes_home().expanduser().resolve()) + home_key = _home_key() - # Idempotence + allowlist read happen under the lock; the TTY - # prompt runs outside so other threads aren't parked on a blocking - # input(). Mutation re-takes the lock with a defensive idempotence - # re-check in case two callers ever race through the prompt. + # Idempotence + allowlist read happen under the lock; the TTY prompt runs + # outside it; mutation re-takes the lock and re-checks in case two callers raced. for spec in specs: key = (home_key, spec.event, spec.matcher, spec.command) with _registered_lock: @@ -306,18 +210,17 @@ def register_from_config( continue already_allowlisted = _is_allowlisted(spec.event, spec.command) - if not already_allowlisted: - if not _prompt_and_record( - spec.event, spec.command, accept_hooks=effective_accept, - ): - logger.warning( - "shell hook for %s (%s) not allowlisted — skipped. " - "Use --accept-hooks / HERMES_ACCEPT_HOOKS=1 / " - "hooks_auto_accept: true, or approve at the TTY " - "prompt next run.", - spec.event, spec.command, - ) - continue + if not already_allowlisted and not _prompt_and_record( + spec.event, spec.command, accept_hooks=effective_accept, + ): + logger.warning( + "shell hook for %s (%s) not allowlisted — skipped. " + "Use --accept-hooks / HERMES_ACCEPT_HOOKS=1 / " + "hooks_auto_accept: true, or approve at the TTY " + "prompt next run.", + spec.event, spec.command, + ) + continue with _registered_lock: if key in _registered: @@ -336,38 +239,20 @@ def register_from_config( def iter_configured_hooks(cfg: Optional[Dict[str, Any]]) -> List[ShellHookSpec]: - """Return the parsed ``ShellHookSpec`` entries from config without - registering anything. Used by ``hermes hooks list`` and ``doctor``.""" + """Parse config hooks without registering (``hermes hooks list`` / doctor).""" if not isinstance(cfg, dict): return [] return _parse_hooks_block(cfg.get("hooks")) def re_register_config_hooks() -> None: - """Re-register shell hooks from config after a plugin force-reload. + """Re-register config hooks after a plugin force-reload cleared the manager's hooks. - ``PluginManager.discover_and_load(force=True)`` unloads via the ownership - ledger and clears the manager's ``_hooks`` dict, which silently drops - shell hooks that were registered from ``config.yaml`` at startup (they - are config-owned, not plugin-owned, so the ledger cannot restore them). - Clear the idempotence set and re-run ``register_from_config()`` so hooks - are wired again (#60036 / PR #60267; tracking #64178 — salvaged from - PR #64188). - - Only the idempotence keys for the *current* Hermes home are cleared — - ``discover_and_load(force=True)`` only unloads the manager scoped to - that one home, so clearing every home's keys would make a force-reload - in profile A drop profile B's still-live registration from the ledger - and duplicate it on B's next registration call (#92682 review). - - Commands already allowlisted stay allowlisted, so this never re-prompts - at a TTY for hooks the user previously approved. + Only the current home's idempotence keys are cleared so a force-reload in + profile A never drops profile B's live registration. Allowlisted commands + stay allowlisted, so this never re-prompts. """ - 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) from hermes_cli.config import load_config register_from_config(load_config()) @@ -379,34 +264,22 @@ def reset_for_tests() -> None: _registered.clear() -# --------------------------------------------------------------------------- -# Config parsing -# --------------------------------------------------------------------------- +# --- Config parsing --- def _parse_hooks_block(hooks_cfg: Any) -> List[ShellHookSpec]: - """Normalise the ``hooks:`` dict into a flat list of ``ShellHookSpec``. - - Malformed entries warn-and-skip — we never raise from config parsing - because a broken hook must not crash the agent. - """ + """Normalise ``hooks:`` into specs; malformed entries warn-and-skip, never raise.""" from hermes_cli.plugins import SHELL_UNSUPPORTED_HOOKS, VALID_HOOKS if not isinstance(hooks_cfg, dict): return [] specs: List[ShellHookSpec] = [] - for event_name, entries in hooks_cfg.items(): - # Reserved sub-keys that aren't event names — skip silently. These - # are config sub-sections nested under `hooks:` for related - # functionality (e.g. output-spill budgets, outbound webhooks — - # the latter parsed by agent/outbound_webhooks.py). + # Reserved non-event sub-sections nested under `hooks:`. if event_name in ("output_spill", "outbound"): continue if event_name in SHELL_UNSUPPORTED_HOOKS: - # Registering would "succeed" while the hook's return value is - # silently dropped (_parse_response has no channel for these - # events' directives) — refuse loudly instead. + # _parse_response has no channel for these directives — refuse loudly. logger.warning( "hook event %r is Python-plugin-only: shell hooks cannot " "return its directive, so this registration is refused " @@ -415,31 +288,20 @@ def _parse_hooks_block(hooks_cfg: Any) -> List[ShellHookSpec]: ) continue if event_name not in VALID_HOOKS: - suggestion = difflib.get_close_matches( - str(event_name), VALID_HOOKS, n=1, cutoff=0.6, - ) + suggestion = difflib.get_close_matches(str(event_name), VALID_HOOKS, n=1, cutoff=0.6) if suggestion: - logger.warning( - "unknown hook event %r in hooks: config — did you mean %r?", - event_name, suggestion[0], - ) + logger.warning("unknown hook event %r in hooks: config — did you mean %r?", event_name, suggestion[0]) else: - logger.warning( - "unknown hook event %r in hooks: config (valid: %s)", - event_name, ", ".join(sorted(VALID_HOOKS)), - ) + logger.warning("unknown hook event %r in hooks: config (valid: %s)", event_name, ", ".join(sorted(VALID_HOOKS))) continue - if entries is None: continue - if not isinstance(entries, list): logger.warning( "hooks.%s must be a list of hook definitions; got %s", event_name, type(entries).__name__, ) continue - for i, raw in enumerate(entries): spec = _parse_single_entry(event_name, i, raw) if spec is not None: @@ -448,38 +310,29 @@ def _parse_hooks_block(hooks_cfg: Any) -> List[ShellHookSpec]: return specs -def _parse_single_entry( - event: str, index: int, raw: Any, -) -> Optional[ShellHookSpec]: +def _parse_single_entry(event: str, index: int, raw: Any) -> Optional[ShellHookSpec]: + def warn(msg: str, *args: Any) -> None: + logger.warning("hooks.%s[%d]" + msg, event, index, *args) + if not isinstance(raw, dict): - logger.warning( - "hooks.%s[%d] must be a mapping with a 'command' key; got %s", - event, index, type(raw).__name__, - ) + warn(" must be a mapping with a 'command' key; got %s", type(raw).__name__) return None command = raw.get("command") if not isinstance(command, str) or not command.strip(): - logger.warning( - "hooks.%s[%d] is missing a non-empty 'command' field", - event, index, - ) + warn(" is missing a non-empty 'command' field") return None matcher = raw.get("matcher") if matcher is not None and not isinstance(matcher, str): - logger.warning( - "hooks.%s[%d].matcher must be a string regex; ignoring", - event, index, - ) + warn(".matcher must be a string regex; ignoring") matcher = None - - if matcher is not None and event not in {"pre_tool_call", "post_tool_call"}: - logger.warning( - "hooks.%s[%d].matcher=%r will be ignored at runtime — the " + if matcher is not None and event not in _TOOL_EVENTS: + warn( + ".matcher=%r will be ignored at runtime — the " "matcher field is only honored for pre_tool_call / " "post_tool_call. The hook will fire on every %s event.", - event, index, matcher, event, + matcher, event, ) matcher = None @@ -487,86 +340,48 @@ def _parse_single_entry( try: timeout = int(timeout_raw) except (TypeError, ValueError): - logger.warning( - "hooks.%s[%d].timeout must be an int (got %r); using default %ds", - event, 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 - if timeout < 1: - logger.warning( - "hooks.%s[%d].timeout must be >=1; using default %ds", - event, index, DEFAULT_TIMEOUT_SECONDS, - ) + warn(".timeout must be >=1; using default %ds", DEFAULT_TIMEOUT_SECONDS) timeout = DEFAULT_TIMEOUT_SECONDS - if timeout > MAX_TIMEOUT_SECONDS: - logger.warning( - "hooks.%s[%d].timeout=%ds exceeds max %ds; clamping", - event, index, timeout, MAX_TIMEOUT_SECONDS, - ) + warn(".timeout=%ds exceeds max %ds; clamping", timeout, MAX_TIMEOUT_SECONDS) timeout = MAX_TIMEOUT_SECONDS - # ``fail_closed`` (canonical) / ``failClosed`` (Cursor/Claude-Code - # config compat). Canonical spelling wins when both are present. - fail_closed_raw = raw.get("fail_closed", raw.get("failClosed", False)) - if not isinstance(fail_closed_raw, bool): - logger.warning( - "hooks.%s[%d].fail_closed must be a boolean (got %r); " - "using default false (fail open)", - event, index, fail_closed_raw, - ) - fail_closed_raw = False - fail_closed = fail_closed_raw - + # ``fail_closed`` (canonical) wins over ``failClosed`` (Cursor/Claude-Code compat). + fail_closed = raw.get("fail_closed", raw.get("failClosed", False)) + if not isinstance(fail_closed, bool): + warn(".fail_closed must be a boolean (got %r); using default false (fail open)", fail_closed) + fail_closed = False if fail_closed and event not in _BLOCKING_EVENTS: - logger.warning( - "hooks.%s[%d].fail_closed=true will be ignored at runtime — " + warn( + ".fail_closed=true will be ignored at runtime — " "fail_closed only applies to blocking-capable events (%s). " "The hook will fail open on %s like any other hook.", - event, index, ", ".join(sorted(_BLOCKING_EVENTS)), event, + ", ".join(sorted(_BLOCKING_EVENTS)), event, ) fail_closed = False return ShellHookSpec( - event=event, - command=command.strip(), - matcher=matcher, - timeout=timeout, - fail_closed=fail_closed, + event=event, command=command.strip(), matcher=matcher, + timeout=timeout, fail_closed=fail_closed, ) -# --------------------------------------------------------------------------- -# Subprocess callback -# --------------------------------------------------------------------------- - -_TOP_LEVEL_PAYLOAD_KEYS = {"tool_name", "args", "session_id", "parent_session_id"} - +# --- Subprocess callback --- def _spawn(spec: ShellHookSpec, stdin_json: str) -> Dict[str, Any]: - """Run ``spec.command`` as a subprocess with ``stdin_json`` on stdin. + """Run ``spec.command`` with ``stdin_json`` on stdin; the single subprocess site. - Returns a diagnostic dict with the same keys for every outcome - (``returncode``, ``stdout``, ``stderr``, ``timed_out``, - ``elapsed_seconds``, ``error``). This is the single place the - subprocess is actually invoked — both the live callback path - (:func:`_make_callback`) and the CLI test helper (:func:`run_once`) - go through it. + Returns a diagnostic dict with the same keys for every outcome. """ result: Dict[str, Any] = { - "returncode": None, - "stdout": "", - "stderr": "", - "timed_out": False, - "elapsed_seconds": 0.0, - "error": None, + "returncode": None, "stdout": "", "stderr": "", + "timed_out": False, "elapsed_seconds": 0.0, "error": None, } try: - # Windows-safe: plain shlex.split eats backslashes in paths (#78293). - from hermes_cli._subprocess_compat import split_command_line - - argv = split_command_line(os.path.expanduser(spec.command)) + argv = _split(os.path.expanduser(spec.command)) except ValueError as exc: result["error"] = f"command {spec.command!r} cannot be parsed: {exc}" return result @@ -575,25 +390,18 @@ def _spawn(spec: ShellHookSpec, stdin_json: str) -> Dict[str, Any]: return result t0 = time.monotonic() - # Spawn the hook in its own process group on POSIX (``process_group=0``, - # Python ≥3.11) so a timed-out hook's descendants can be reaped with the - # hook itself. Windows keeps the hidden-window flags; tree cleanup there - # goes through ``taskkill /T`` in ``kill_process_tree``. Hooks that - # complete in time keep their descendants — an intentionally detached - # helper (``some-daemon &``) survives a successful run. Ported from - # openai/codex#37527 ("Terminate timed-out hook process trees"). - _popen_kwargs: Dict[str, Any] = ( + # Own process group on POSIX so a timed-out hook's descendants are reaped + # with it; Windows tree cleanup goes through kill_process_tree (taskkill /T). + # Hooks that finish in time keep detached helpers alive. + popen_kwargs: Dict[str, Any] = ( {"creationflags": windows_hide_flags()} if IS_WINDOWS else {"process_group": 0} ) try: proc = subprocess.Popen( argv, - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, encoding='utf-8', errors='replace', - shell=False, - **_popen_kwargs, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, encoding='utf-8', errors='replace', shell=False, + **popen_kwargs, ) except FileNotFoundError: result["error"] = "command not found" @@ -607,25 +415,18 @@ def _spawn(spec: ShellHookSpec, stdin_json: str) -> Dict[str, Any]: try: stdout, stderr = proc.communicate(input=stdin_json, timeout=spec.timeout) - except subprocess.TimeoutExpired: - # Take down the whole process tree, not just the direct child — - # otherwise a hook that forked helpers leaves them running (and, - # holding the pipe write ends, they'd stall the drain below). + except Exception as exc: + # Kill the whole tree — forked helpers holding the pipes would stall the drain. kill_process_tree(proc) try: proc.communicate(timeout=1) except Exception: pass - result["timed_out"] = True - result["elapsed_seconds"] = round(time.monotonic() - t0, 3) - return result - except Exception as exc: # pragma: no cover — defensive - kill_process_tree(proc) - try: - proc.communicate(timeout=1) - except Exception: - pass - result["error"] = str(exc) + if isinstance(exc, subprocess.TimeoutExpired): + result["timed_out"] = True + result["elapsed_seconds"] = round(time.monotonic() - t0, 3) + else: # pragma: no cover — defensive + result["error"] = str(exc) return result result["returncode"] = proc.returncode @@ -639,13 +440,9 @@ def _make_callback(spec: ShellHookSpec) -> Callable[..., Optional[Dict[str, Any] """Build the closure that ``invoke_hook()`` will call per firing.""" def _callback(**kwargs: Any) -> Optional[Dict[str, Any]]: - # Matcher gate — only meaningful for tool-scoped events. - if spec.event in {"pre_tool_call", "post_tool_call"}: - if not spec.matches_tool(kwargs.get("tool_name")): - return None - - r = _spawn(spec, _serialize_payload(spec.event, kwargs)) - return _evaluate_result(spec, r) + if spec.event in _TOOL_EVENTS and not spec.matches_tool(kwargs.get("tool_name")): + return None + return _evaluate_result(spec, _spawn(spec, _serialize_payload(spec.event, kwargs))) _callback.__name__ = f"shell_hook[{spec.event}:{spec.command}]" _callback.__qualname__ = _callback.__name__ @@ -653,33 +450,17 @@ def _make_callback(spec: ShellHookSpec) -> Callable[..., Optional[Dict[str, Any] def _fail_closed_block(spec: ShellHookSpec, reason: str) -> Dict[str, Any]: - """Canonical block shape for a ``fail_closed`` hook that failed.""" - return { - "action": "block", - "message": f"hook {spec.command} failed closed: {reason}", - } + return {"action": "block", "message": f"hook {spec.command} failed closed: {reason}"} -def _evaluate_result( - spec: ShellHookSpec, r: Dict[str, Any], -) -> Optional[Dict[str, Any]]: - """Turn a :func:`_spawn` diagnostic dict into the hook's contribution. +def _evaluate_result(spec: ShellHookSpec, r: Dict[str, Any]) -> Optional[Dict[str, Any]]: + """Turn a ``_spawn`` diagnostic dict into the hook's contribution. - Single place that encodes the failure semantics: - - * spawn error / timeout — fail open (log + ``None``) unless the spec - is ``fail_closed`` on a blocking-capable event, in which case a - canonical block shape is returned; - * exit code 2 on a blocking-capable event — block, with the message - taken from stdout block JSON, then stderr, then a default - (Claude-Code / Cursor compatible); - * other non-zero exits — warn, then parse stdout normally; - * non-JSON / unparseable stdout on a ``fail_closed`` blocking hook — - block instead of silently contributing nothing. - - Shared by the live callback path (:func:`_make_callback`) and the CLI - test helper (:func:`run_once`) so ``hermes hooks test`` reflects - production behaviour exactly. + Encodes the failure semantics once (shared by the live callback and + ``run_once``): spawn error/timeout fail open unless fail_closed; exit 2 on + a blocking event blocks (message from stdout JSON, then stderr, then + default); other non-zero exits warn then parse stdout; unparseable stdout + on a fail_closed hook blocks. """ blocking_event = spec.event in _BLOCKING_EVENTS fail_closed = spec.fail_closed and blocking_event @@ -689,19 +470,13 @@ def _evaluate_result( "shell hook failed (event=%s command=%s): %s", spec.event, spec.command, r["error"], ) - if fail_closed: - return _fail_closed_block(spec, r["error"]) - return None + return _fail_closed_block(spec, r["error"]) if fail_closed else None if r["timed_out"]: logger.warning( "shell hook timed out after %.2fs (event=%s command=%s)", r["elapsed_seconds"], spec.event, spec.command, ) - if fail_closed: - return _fail_closed_block( - spec, f"timed out after {spec.timeout}s", - ) - return None + return _fail_closed_block(spec, f"timed out after {spec.timeout}s") if fail_closed else None stderr = r["stderr"].strip() if stderr: @@ -710,9 +485,6 @@ def _evaluate_result( spec.event, spec.command, stderr[:_STDERR_MESSAGE_LIMIT], ) - # Exit code 2 = block (Claude-Code / Cursor compatible), for events - # whose block directive is honored downstream. stdout block JSON - # still wins for the message; otherwise stderr, then a default. if r["returncode"] == BLOCK_EXIT_CODE and blocking_event: parsed = _parse_response(spec.event, r["stdout"]) if isinstance(parsed, dict) and parsed.get("action") == "block": @@ -724,8 +496,7 @@ def _evaluate_result( ) return {"action": "block", "message": message} - # Other non-zero exits: log but still parse stdout so scripts that - # signal failure via exit code can also return a block directive. + # Other non-zero exits: still parse stdout so exit-code failures can carry a block directive. if r["returncode"] != 0: logger.warning( "shell hook exited %d (event=%s command=%s); stderr=%s", @@ -737,127 +508,82 @@ def _evaluate_result( parsed = _parse_response(spec.event, stdout) if parsed is None and fail_closed and stdout: - # The hook produced output we could not turn into a directive. - # A fail-closed gate must not silently allow the action on - # garbage output (e.g. a stack trace on stdout). + # A fail-closed gate must not silently allow on garbage stdout (e.g. a stack trace). try: - data = json.loads(stdout) - valid_json = isinstance(data, dict) + valid_json = isinstance(json.loads(stdout), dict) except json.JSONDecodeError: valid_json = False if not valid_json: - return _fail_closed_block( - spec, "unparseable stdout (expected a JSON object)", - ) + return _fail_closed_block(spec, "unparseable stdout (expected a JSON object)") return parsed def _serialize_payload(event: str, kwargs: Dict[str, Any]) -> str: - """Render the stdin JSON payload. Unserialisable values are - stringified via ``default=str`` rather than dropped.""" - 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 = "" - payload = { - "hook_event_name": event, - "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, - } + """Render the stdin JSON payload; unserialisable values are stringified.""" + payload = {"hook_event_name": event, **_payload_fields(kwargs)} return json.dumps(payload, ensure_ascii=False, default=str) def _block_message(primary: Any, secondary: Any) -> str: - """Return a validated string block message, falling back to the default. - - Accepts two candidate fields (primary wins over secondary) so callers - can express field-priority differences between the two hook wire formats - without duplicating the type-check logic. - """ + """Validated string block message (primary wins), falling back to the default.""" raw = primary or secondary return raw if isinstance(raw, str) and raw else _DEFAULT_BLOCK_MESSAGE -def _parse_response(event: str, stdout: str) -> Optional[Dict[str, Any]]: - """Translate stdout JSON into a Hermes wire-shape dict. - - For ``pre_tool_call`` the Claude-Code-style ``{"decision": "block", - "reason": "..."}`` payload is translated into the canonical Hermes - ``{"action": "block", "message": "..."}`` shape expected by - :func:`hermes_cli.plugins.get_pre_tool_call_block_message`. This is - the single most important correctness invariant in this module — - skipping the translation silently breaks every ``pre_tool_call`` - block directive. - - For ``pre_tool_call`` the ``modify`` action (canonical: ``{"action": - "modify", "args": {...}}``, Claude-Code-style: ``{"decision": - "modify", "tool_input": {...}}``) is translated to - ``{"action": "modify", "args": {...}}`` so callers can merge the - returned fields into the tool's ``args`` before dispatch. - - For ``pre_llm_call``, ``{"context": "..."}`` is passed through - unchanged to match the existing plugin-hook contract. - - Anything else returns ``None``. - """ - stdout = (stdout or "").strip() - if not stdout: - return None - - try: - data = json.loads(stdout) - except json.JSONDecodeError: - logger.warning( - "shell hook stdout was not valid JSON (event=%s): %s", - event, stdout[:200], - ) - return None - - if not isinstance(data, dict): - return None - - if event == "pre_tool_call": - if data.get("action") == "block": - return {"action": "block", "message": _block_message(data.get("message"), data.get("reason"))} - if data.get("decision") == "block": - return {"action": "block", "message": _block_message(data.get("reason"), data.get("message"))} - # "modify" action — transform tool_input before dispatch - if data.get("action") == "modify": - new_args = data.get("args") - if isinstance(new_args, dict): - return {"action": "modify", "args": new_args} - if data.get("decision") == "modify": - new_args = data.get("tool_input") - if isinstance(new_args, dict): - return {"action": "modify", "args": new_args} - return None - - if event == "pre_verify": - # "continue" (Hermes) / "block" (Claude-Code Stop: block the stop) both - # mean keep going; the message/reason is the follow-up for the model. A - # continue with no message is a no-op — let the turn finish. - action = str(data.get("action") or data.get("decision") or "").strip().lower() - if action in {"continue", "block"}: - message = data.get("message") or data.get("reason") - if isinstance(message, str) and message.strip(): - return {"action": "continue", "message": message.strip()} - return None - - context = data.get("context") - if isinstance(context, str) and context.strip(): - return {"context": context} - +def _parse_pre_tool_call(data: Dict[str, Any]) -> Optional[Dict[str, Any]]: + # Claude-Code-style {"decision": ..., "reason"/"tool_input": ...} is translated to + # the canonical Hermes shape expected by get_pre_tool_call_block_message — + # skipping this silently breaks every pre_tool_call block directive. + if data.get("action") == "block": + return {"action": "block", "message": _block_message(data.get("message"), data.get("reason"))} + if data.get("decision") == "block": + return {"action": "block", "message": _block_message(data.get("reason"), data.get("message"))} + if data.get("action") == "modify" and isinstance(data.get("args"), dict): + return {"action": "modify", "args": data["args"]} + if data.get("decision") == "modify" and isinstance(data.get("tool_input"), dict): + return {"action": "modify", "args": data["tool_input"]} return None -# --------------------------------------------------------------------------- -# Allowlist / consent -# --------------------------------------------------------------------------- +def _parse_pre_verify(data: Dict[str, Any]) -> Optional[Dict[str, Any]]: + # "continue" (Hermes) / "block" (Claude-Code Stop) both mean keep going; + # a continue with no message is a no-op. + action = str(data.get("action") or data.get("decision") or "").strip().lower() + if action in {"continue", "block"}: + message = data.get("message") or data.get("reason") + if isinstance(message, str) and message.strip(): + return {"action": "continue", "message": message.strip()} + return None + + +def _parse_context(data: Dict[str, Any]) -> Optional[Dict[str, Any]]: + context = data.get("context") + if isinstance(context, str) and context.strip(): + return {"context": context} + return None + + +_RESPONSE_PARSERS: Dict[str, Callable[[Dict[str, Any]], Optional[Dict[str, Any]]]] = { + "pre_tool_call": _parse_pre_tool_call, + "pre_verify": _parse_pre_verify, +} + + +def _parse_response(event: str, stdout: str) -> Optional[Dict[str, Any]]: + """Translate stdout JSON into a Hermes wire-shape dict, or ``None``.""" + stdout = (stdout or "").strip() + if not stdout: + return None + try: + data = json.loads(stdout) + except json.JSONDecodeError: + logger.warning("shell hook stdout was not valid JSON (event=%s): %s", event, stdout[:200]) + return None + return _RESPONSE_PARSERS.get(event, _parse_context)(data) if isinstance(data, dict) else None + + +# --- Allowlist / consent --- def allowlist_path() -> Path: """Path to the per-user shell-hook allowlist file.""" @@ -869,27 +595,20 @@ def load_allowlist() -> Dict[str, Any]: try: raw = json.loads(allowlist_path().read_text(encoding="utf-8")) except (FileNotFoundError, json.JSONDecodeError, OSError): - return {"approvals": []} + raw = None if not isinstance(raw, dict): return {"approvals": []} - approvals = raw.get("approvals") - if not isinstance(approvals, list): + if not isinstance(raw.get("approvals"), list): raw["approvals"] = [] return raw def save_allowlist(data: Dict[str, Any]) -> None: - """Atomically persist the allowlist via per-process ``mkstemp`` + - ``os.replace``. Cross-process read-modify-write races are handled - by :func:`_locked_update_approvals` (``fcntl.flock``). On OSError - the failure is logged; the in-process hook still registers but - the approval won't survive across runs.""" + """Atomically persist the allowlist; on OSError log and keep the in-process approval.""" p = allowlist_path() try: p.parent.mkdir(parents=True, exist_ok=True) - fd, tmp_path = tempfile.mkstemp( - prefix=f"{p.name}.", suffix=".tmp", dir=str(p.parent), - ) + fd, tmp_path = tempfile.mkstemp(prefix=f"{p.name}.", suffix=".tmp", dir=str(p.parent)) try: with os.fdopen(fd, "w", encoding="utf-8") as fh: fh.write(json.dumps(data, indent=2, sort_keys=True)) @@ -911,55 +630,35 @@ def save_allowlist(data: Dict[str, Any]) -> None: def _is_allowlisted(event: str, command: str) -> bool: - data = load_allowlist() - return any( - isinstance(e, dict) - and e.get("event") == event - and e.get("command") == command - for e in data.get("approvals", []) - ) + return any(_entry_matches(e, event, command) for e in load_allowlist().get("approvals", [])) @contextmanager def _locked_update_approvals() -> Iterator[Dict[str, Any]]: - """Serialise read-modify-write on the allowlist across processes. - - Holds an exclusive ``flock`` on a sibling lock file for the duration - of the update so concurrent ``_record_approval``/``revoke`` callers - cannot clobber each other's changes (the race Codex reproduced with - 20–50 simultaneous writers). Falls back to an in-process lock on - platforms without ``fcntl``. - """ + """Serialise allowlist read-modify-write across processes via a sibling flock file.""" p = allowlist_path() p.parent.mkdir(parents=True, exist_ok=True) - lock_path = p.with_suffix(p.suffix + ".lock") - - if fcntl is None: # pragma: no cover — non-POSIX fallback - with _allowlist_write_lock: - data = load_allowlist() - yield data - save_allowlist(data) - return - - with open(lock_path, "a+", encoding="utf-8") as lock_fh: - fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX) - try: - data = load_allowlist() - yield data - save_allowlist(data) - finally: - try: - fcntl.flock(lock_fh.fileno(), fcntl.LOCK_UN) - except (OSError, IOError): - pass + with ExitStack() as stack: + if fcntl is None: # pragma: no cover — non-POSIX fallback + stack.enter_context(_allowlist_write_lock) + else: + lock_fh = stack.enter_context(open(p.with_suffix(p.suffix + ".lock"), "a+", encoding="utf-8")) + fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX) + stack.callback(_flock_unlock, lock_fh) + data = load_allowlist() + yield data + save_allowlist(data) -def _prompt_and_record( - event: str, command: str, *, accept_hooks: bool, -) -> bool: - """Decide whether to approve an unseen ``(event, command)`` pair. - Returns ``True`` iff the approval was granted and recorded. - """ +def _flock_unlock(lock_fh: Any) -> None: + try: + fcntl.flock(lock_fh.fileno(), fcntl.LOCK_UN) + except (OSError, IOError): + pass + + +def _prompt_and_record(event: str, command: str, *, accept_hooks: bool) -> bool: + """Approve an unseen ``(event, command)`` pair; True iff granted and recorded.""" if accept_hooks: _record_approval(event, command) logger.info( @@ -988,7 +687,6 @@ def _prompt_and_record( if answer in {"y", "yes"}: _record_approval(event, command) return True - return False @@ -1001,31 +699,19 @@ def _record_approval(event: str, command: str) -> None: } with _locked_update_approvals() as data: data["approvals"] = [ - e for e in data.get("approvals", []) - if not ( - isinstance(e, dict) - and e.get("event") == event - and e.get("command") == command - ) + e for e in data.get("approvals", []) if not _entry_matches(e, event, command) ] + [entry] -def _utc_now_iso() -> str: - return datetime.now(tz=timezone.utc).isoformat().replace("+00:00", "Z") - - def revoke(command: str) -> int: - """Remove every allowlist entry matching ``command``. + """Remove every allowlist entry matching ``command``; returns the count removed. - Returns the number of entries removed. Does not unregister any - callbacks that are already live on the plugin manager in the current - process — restart the CLI / gateway to drop them. + Live callbacks in the current process stay registered until restart. """ with _locked_update_approvals() as data: before = len(data.get("approvals", [])) data["approvals"] = [ - e for e in data.get("approvals", []) - if not (isinstance(e, dict) and e.get("command") == command) + e for e in data.get("approvals", []) if not _entry_matches(e, None, command) ] after = len(data["approvals"]) return before - after @@ -1040,96 +726,56 @@ _SCRIPT_EXTENSIONS: Tuple[str, ...] = ( def _command_script_path(command: str) -> str: - """Return the script path from ``command`` for doctor / drift checks. - - Prefers a token ending in a known script extension, then a token - containing ``/`` or leading ``~``, then the first token. Handles - ``python3 /path/hook.py``, ``/usr/bin/env bash hook.sh``, and the - common bare-path form. - """ + """Script path from ``command``: first token with a script extension, then a + path-like token, then the first token (``python3 /p/hook.py``, ``/usr/bin/env bash x.sh``).""" try: - from hermes_cli._subprocess_compat import split_command_line - - parts = split_command_line(command) + parts = _split(command) except ValueError: return command if not parts: return command - for part in parts: - if part.lower().endswith(_SCRIPT_EXTENSIONS): - return part - for part in parts: - if "/" in part or part.startswith("~"): - return part - return parts[0] + return ( + next((p for p in parts if p.lower().endswith(_SCRIPT_EXTENSIONS)), None) + or next((p for p in parts if "/" in p or p.startswith("~")), None) + or parts[0] + ) -# --------------------------------------------------------------------------- -# Helpers for accept-hooks resolution -# --------------------------------------------------------------------------- - -def _resolve_effective_accept( - cfg: Dict[str, Any], accept_hooks_arg: bool, -) -> bool: - """Combine all three opt-in channels into a single boolean. - - Precedence (any truthy source flips us on): - 1. ``--accept-hooks`` flag (CLI) / explicit argument - 2. ``HERMES_ACCEPT_HOOKS`` env var - 3. ``hooks_auto_accept: true`` in ``cli-config.yaml`` - """ - if accept_hooks_arg: - return True - env = os.environ.get("HERMES_ACCEPT_HOOKS", "").strip().lower() - if env in {"1", "true", "yes", "on"}: +def _resolve_effective_accept(cfg: Dict[str, Any], accept_hooks_arg: bool) -> bool: + """Any truthy opt-in channel wins: explicit arg, HERMES_ACCEPT_HOOKS, hooks_auto_accept.""" + if accept_hooks_arg or os.environ.get("HERMES_ACCEPT_HOOKS", "").strip().lower() in _TRUTHY: return True cfg_val = cfg.get("hooks_auto_accept", False) if isinstance(cfg_val, bool): return cfg_val if isinstance(cfg_val, str): - return cfg_val.strip().lower() in {"1", "true", "yes", "on"} + return cfg_val.strip().lower() in _TRUTHY return False -# --------------------------------------------------------------------------- -# Introspection (used by `hermes hooks` CLI) -# --------------------------------------------------------------------------- +# --- Introspection (used by `hermes hooks` CLI) --- def allowlist_entry_for(event: str, command: str) -> Optional[Dict[str, Any]]: """Return the allowlist record for this pair, if any.""" - for e in load_allowlist().get("approvals", []): - if ( - isinstance(e, dict) - and e.get("event") == event - and e.get("command") == command - ): - return e - return None + return next((e for e in load_allowlist().get("approvals", []) if _entry_matches(e, event, command)), None) def script_mtime_iso(command: str) -> Optional[str]: - """ISO-8601 mtime of the resolved script path, or ``None`` if the - script is missing.""" + """ISO-8601 mtime of the resolved script path, or ``None`` if missing.""" path = _command_script_path(command) if not path: return None try: - expanded = os.path.expanduser(path) return datetime.fromtimestamp( - os.path.getmtime(expanded), tz=timezone.utc, + os.path.getmtime(os.path.expanduser(path)), tz=timezone.utc, ).isoformat().replace("+00:00", "Z") except OSError: return None def script_is_executable(command: str) -> bool: - """Return ``True`` iff ``command`` is runnable as configured. - - For a bare invocation (``/path/hook.sh``) the script itself must be - executable. For interpreter-prefixed commands (``python3 - /path/hook.py``, ``/usr/bin/env bash hook.sh``) the script just has - to be readable — the interpreter doesn't care about the ``X_OK`` - bit. Mirrors what ``_spawn`` would actually do at runtime.""" + """True iff ``command`` is runnable as configured: a bare script needs X_OK, + an interpreter-prefixed one only R_OK (mirrors what ``_spawn`` does).""" path = _command_script_path(command) if not path: return False @@ -1137,33 +783,19 @@ def script_is_executable(command: str) -> bool: if not os.path.isfile(expanded): return False try: - from hermes_cli._subprocess_compat import split_command_line - - argv = split_command_line(command) + argv = _split(command) except ValueError: return False is_bare_invocation = bool(argv) and argv[0] == path - required = os.X_OK if is_bare_invocation else os.R_OK - return os.access(expanded, required) + return os.access(expanded, os.X_OK if is_bare_invocation else os.R_OK) -def run_once( - spec: ShellHookSpec, kwargs: Dict[str, Any], -) -> Dict[str, Any]: - """Fire a single shell-hook invocation with a synthetic payload. - Used by ``hermes hooks test`` and ``hermes hooks doctor``. +def run_once(spec: ShellHookSpec, kwargs: Dict[str, Any]) -> Dict[str, Any]: + """Fire one hook with a synthetic payload (``hermes hooks test`` / doctor). - ``kwargs`` is the same dict that :func:`hermes_cli.plugins.invoke_hook` - would pass at runtime. It is routed through :func:`_serialize_payload` - so the synthetic stdin exactly matches what a real hook firing would - produce — otherwise scripts tested via ``hermes hooks test`` could - diverge silently from production behaviour. - - Returns the :func:`_spawn` diagnostic dict plus a ``parsed`` field - holding the canonical Hermes-wire-shape response — including exit-code-2 - blocking and ``fail_closed`` semantics, so what ``hermes hooks test`` - prints is exactly what the dispatcher would receive.""" - stdin_json = _serialize_payload(spec.event, kwargs) - result = _spawn(spec, stdin_json) + Routes through ``_serialize_payload`` and ``_evaluate_result`` so the + result (``_spawn`` dict + ``parsed``) matches production exactly. + """ + result = _spawn(spec, _serialize_payload(spec.event, kwargs)) result["parsed"] = _evaluate_result(spec, result) return result diff --git a/agent/tool_dispatch_helpers.py b/agent/tool_dispatch_helpers.py index 41dc4066b9..54bedab1ae 100644 --- a/agent/tool_dispatch_helpers.py +++ b/agent/tool_dispatch_helpers.py @@ -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 ```` 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. ````). +# 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 ```` 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 diff --git a/agent/tool_guardrails.py b/agent/tool_guardrails.py index b432c21d9f..6ec3b289ae 100644 --- a/agent/tool_guardrails.py +++ b/agent/tool_guardrails.py @@ -1,9 +1,8 @@ """Pure tool-call loop guardrail primitives. -The controller in this module is intentionally side-effect free: it tracks -per-turn tool-call observations and returns decisions. Runtime code owns whether -those decisions become warning guidance, synthetic tool results, or controlled -turn halts. +The controller is side-effect free: it tracks per-turn tool-call observations +and returns decisions. Runtime code decides whether a decision becomes warning +guidance, a synthetic tool result, or a controlled turn halt. """ from __future__ import annotations @@ -17,147 +16,69 @@ from utils import safe_json_loads from agent.tool_result_classification import file_mutation_result_landed -IDEMPOTENT_TOOL_NAMES = frozenset( - { - "read_file", - "search_files", - "web_search", - "web_extract", - "session_search", - "skill_view", - "skills_list", - "browser_snapshot", - "browser_console", - "browser_get_images", - "mcp_filesystem_read_file", - "mcp_filesystem_read_text_file", - "mcp_filesystem_read_multiple_files", - "mcp_filesystem_list_directory", - "mcp_filesystem_list_directory_with_sizes", - "mcp_filesystem_directory_tree", - "mcp_filesystem_get_file_info", - "mcp_filesystem_search_files", - } -) +IDEMPOTENT_TOOL_NAMES = frozenset({ + "read_file", "search_files", "web_search", "web_extract", "session_search", "skill_view", + "skills_list", "browser_snapshot", "browser_console", "browser_get_images", + "mcp_filesystem_read_file", "mcp_filesystem_read_text_file", + "mcp_filesystem_read_multiple_files", "mcp_filesystem_list_directory", + "mcp_filesystem_list_directory_with_sizes", "mcp_filesystem_directory_tree", + "mcp_filesystem_get_file_info", "mcp_filesystem_search_files", +}) -MUTATING_TOOL_NAMES = frozenset( - { - "terminal", - "execute_code", - "write_file", - "patch", - "todo_list", - "memory", - "skill_manage", - "browser_click", - "browser_type", - "browser_press", - "browser_scroll", - "browser_navigate", - "send_message", - "cronjob_manage", - "delegate_task", - "process_manage", - } -) +MUTATING_TOOL_NAMES = frozenset({ + "terminal", "execute_code", "write_file", "patch", "todo_list", "memory", "skill_manage", + "browser_click", "browser_type", "browser_press", "browser_scroll", "browser_navigate", + "send_message", "cronjob_manage", "delegate_task", "process_manage", +}) -# Tools that are legitimately re-invoked with identical arguments and may -# legitimately return an unchanged result while waiting on external progress — -# background-process management and job pollers. The identical-call loop -# notice (agent.stall_guards) never fires for these, so polling patterns like -# ``process(action="poll")`` or repeatedly checking a generation job stay -# unannotated. -STALL_GUARD_REPEATABLE_TOOLS = frozenset( - { - "process_manage", - } -) +# Tools legitimately re-invoked with identical args while waiting on external +# progress (pollers). The identical-call NOTICE never fires for these. +STALL_GUARD_REPEATABLE_TOOLS = frozenset({"process_manage"}) +# Poller naming conventions on generated / MCP surfaces (``_get_result``). +_STALL_GUARD_REPEATABLE_SUFFIXES = ("_get_result", "_poll") -# Poller naming conventions (e.g. ``_get_result``) used by generated / -# MCP tool surfaces. Matched as suffixes so vendor-prefixed pollers are exempt -# without enumerating every vendor. -_STALL_GUARD_REPEATABLE_SUFFIXES = ( - "_get_result", - "_poll", -) - -# The notice fires on the Nth consecutive identical call (same tool, same -# canonical args, same result). 3 tolerates one legitimate double-check while -# catching the observed re-issue loops (3x/4x identical calls in eval traces). +# Notice fires on the Nth consecutive identical (tool, args, result) call; 3 +# tolerates one legitimate double-check while catching observed re-issue loops. STALL_GUARD_IDENTICAL_CALL_THRESHOLD = 3 -# Result-reference stubbing (agent.stall_guards): from the 2nd consecutive -# identical call whose FRESH result is byte-identical to the previous one, -# the duplicate payload is replaced in context by a short reference stub. -# Results under this size aren't worth stubbing (the stub itself plus the -# lost locality outweigh the savings), and error results are never stubbed -# (the model must see every fresh error verbatim). +# Result-reference stubbing: from the 2nd consecutive identical call whose fresh +# result is byte-identical, the duplicate payload is replaced by a reference +# stub. Results under this size aren't worth stubbing; errors are never stubbed. IDENTICAL_RESULT_STUB_MIN_CHARS = 512 - -# How much of the canonical args JSON the stub carries so the model still -# knows WHAT the referenced call was even if context compression later -# evicts the referenced result (cheap dangling-reference mitigation). +# Canonical-args preview kept in the stub so the model still knows WHAT the call +# was if compression later evicts the referenced result. _RESULT_STUB_ARGS_PREVIEW_CHARS = 120 +# Tools whose "failure" is normal work output (red test run, empty grep, page +# timeout). same_tool_failure (DIFFERENT commands) never halts these; only an +# exact-args replay with no intervening change, or an identical-result streak, can. +FAILURE_TOLERANT_TOOL_NAMES = frozenset({ + "terminal", "execute_code", "process_manage", "process", "browser_navigate", "web_extract", +}) -# Tools whose "failure" is a normal, informative outcome of legitimate work: -# a red test run, a grep with no matches, a failing build during a fix loop, a -# page that times out. Hard stops never fire on these from failure counts of -# DIFFERENT commands (same_tool_failure) — only an exact-args replay with NO -# intervening change, or an identical-result streak, can halt them. -FAILURE_TOLERANT_TOOL_NAMES = frozenset( - { - "terminal", - "execute_code", - "process_manage", - "process", - "browser_navigate", - "web_extract", - } -) - -# A landed mutation between two attempts means the retry is a NEW experiment -# (edit -> re-run) rather than a replay. A successful call to one of these -# marks progress for every failing signature still being counted this turn. -PROGRESS_RESET_TOOL_NAMES = frozenset( - { - "write_file", - "patch", - "terminal", - "execute_code", - "browser_click", - "browser_type", - "browser_press", - "browser_navigate", - "process_manage", - "process", - "delegate_task", - "send_message", - "cronjob", - "cronjob_manage", - "todo", - "todo_list", - "memory", - "skill_manage", - } -) +# A successful call to one of these marks progress for every failing signature +# still counted this turn: the next retry is a new experiment (edit -> re-run), not a replay. +PROGRESS_RESET_TOOL_NAMES = frozenset({ + "write_file", "patch", "terminal", "execute_code", "browser_click", "browser_type", + "browser_press", "browser_navigate", "process_manage", "process", "delegate_task", + "send_message", "cronjob", "cronjob_manage", "todo", "todo_list", "memory", "skill_manage", +}) def is_stall_guard_repeatable(tool_name: str) -> bool: """Whether a tool is exempt from the identical-call loop notice.""" - if tool_name in STALL_GUARD_REPEATABLE_TOOLS: - return True - return tool_name.endswith(_STALL_GUARD_REPEATABLE_SUFFIXES) + return tool_name in STALL_GUARD_REPEATABLE_TOOLS or tool_name.endswith( + _STALL_GUARD_REPEATABLE_SUFFIXES + ) @dataclass(frozen=True) class ToolCallGuardrailConfig: """Thresholds for per-turn tool-call loop detection. - Warnings are enabled by default and never prevent tool execution. Hard stops - stay opt-in for interactive CLI/TUI/Desktop/ACP sessions, but default on for - non-interactive gateway/cron platforms where nobody is present to interrupt - a model that ignores loop warnings. + Warnings never prevent execution. Hard stops are opt-in for interactive + platforms but default on for unattended gateway/cron platforms where nobody + can interrupt a model that ignores loop warnings. """ warnings_enabled: bool = True @@ -180,84 +101,63 @@ class ToolCallGuardrailConfig: *, platform: str | None = None, ) -> "ToolCallGuardrailConfig": - """Build config from the `tool_loop_guardrails` config.yaml section.""" + """Build config from the `tool_loop_guardrails` config.yaml section. + + Nested ``warn_after`` / ``hard_stop_after`` keys win over the flat legacy keys. + """ if not isinstance(data, Mapping): data = {} - - warn_after = data.get("warn_after") - if not isinstance(warn_after, Mapping): - warn_after = {} - hard_stop_after = data.get("hard_stop_after") - if not isinstance(hard_stop_after, Mapping): - hard_stop_after = {} - - defaults = cls() - hard_stop_enabled = _as_bool(data.get("hard_stop_enabled"), defaults.hard_stop_enabled) + d = cls() + hard_stop_enabled = _as_bool(data.get("hard_stop_enabled"), d.hard_stop_enabled) non_interactive_hard_stop_enabled = _as_bool( - data.get("non_interactive_hard_stop_enabled"), - defaults.non_interactive_hard_stop_enabled, + data.get("non_interactive_hard_stop_enabled"), d.non_interactive_hard_stop_enabled, ) if _is_non_interactive_platform(platform) and non_interactive_hard_stop_enabled: hard_stop_enabled = True + thresholds: dict[str, int] = {} + for field_name, (section_name, key) in _THRESHOLD_SOURCES.items(): + section = data.get(section_name) + if not isinstance(section, Mapping): + section = {} + thresholds[field_name] = _int_at_least( + section.get(key, data.get(field_name)), getattr(d, field_name), 1, + ) + return cls( - warnings_enabled=_as_bool(data.get("warnings_enabled"), defaults.warnings_enabled), + warnings_enabled=_as_bool(data.get("warnings_enabled"), d.warnings_enabled), hard_stop_enabled=hard_stop_enabled, non_interactive_hard_stop_enabled=non_interactive_hard_stop_enabled, - exact_failure_warn_after=_positive_int( - warn_after.get("exact_failure", data.get("exact_failure_warn_after")), - defaults.exact_failure_warn_after, - ), - same_tool_failure_warn_after=_positive_int( - warn_after.get("same_tool_failure", data.get("same_tool_failure_warn_after")), - defaults.same_tool_failure_warn_after, - ), - no_progress_warn_after=_positive_int( - warn_after.get("idempotent_no_progress", data.get("no_progress_warn_after")), - defaults.no_progress_warn_after, - ), - exact_failure_block_after=_positive_int( - hard_stop_after.get("exact_failure", data.get("exact_failure_block_after")), - defaults.exact_failure_block_after, - ), - same_tool_failure_halt_after=_positive_int( - hard_stop_after.get("same_tool_failure", data.get("same_tool_failure_halt_after")), - defaults.same_tool_failure_halt_after, - ), - no_progress_block_after=_positive_int( - hard_stop_after.get("idempotent_no_progress", data.get("no_progress_block_after")), - defaults.no_progress_block_after, - ), loop_caps=LoopCapConfig.from_mapping(data.get("loop_caps")), + **thresholds, ) -# Default session-wide caps, matching Claude Code's v2.1.212 runaway-loop -# Per-turn (per-agent-loop) caps on runaway-prone tool calls. Counts reset at -# the start of every agent loop (reset_for_turn), so the limit is "within a -# single turn" rather than cumulative over the whole session. A single loop -# issuing dozens of web searches or spawning dozens of subagents is already -# pathological, so the defaults are deliberately low. +# Threshold field -> (nested section, nested key). The flat legacy key is the field name itself. +_THRESHOLD_SOURCES: dict[str, tuple[str, str]] = { + "exact_failure_warn_after": ("warn_after", "exact_failure"), + "same_tool_failure_warn_after": ("warn_after", "same_tool_failure"), + "no_progress_warn_after": ("warn_after", "idempotent_no_progress"), + "exact_failure_block_after": ("hard_stop_after", "exact_failure"), + "same_tool_failure_halt_after": ("hard_stop_after", "same_tool_failure"), + "no_progress_block_after": ("hard_stop_after", "idempotent_no_progress"), +} + + +# Per-turn caps on runaway-prone tools; counters reset in reset_for_turn at the +# start of every agent loop, so the limit is per turn, not per session. Dozens +# of searches / subagent spawns in one loop is already pathological. _DEFAULT_MAX_WEB_SEARCHES_PER_TURN = 50 _DEFAULT_MAX_SUBAGENTS_PER_TURN = 50 @dataclass(frozen=True) class LoopCapConfig: - """Per-turn caps on runaway-prone tool calls. + """Per-turn hard ceilings on web_search calls / subagent spawns. - Inspired by Claude Code v2.1.212 (Week 29, July 2026), which added caps on - WebSearch calls and subagent spawns to stop runaway search / delegation - loops. Here the caps count *within a single agent loop* (one turn): the - counters reset in ``reset_for_turn`` at the start of every - ``run_conversation``, so a legitimate multi-turn session is never starved, - but a single turn that spirals into an unbounded search / delegation loop - is stopped. - - Semantics differ from the per-turn loop *detector* above (which keys on - repeated identical/failing calls): these caps are a hard ceiling on the - total count of a tool within the turn and fire regardless of - ``hard_stop_enabled``. A value of ``0`` disables the cap (unlimited). + Unlike the loop detector (keyed on repeated identical/failing calls) these + count total calls within the turn and fire regardless of + ``hard_stop_enabled``. ``0`` disables a cap. """ max_web_searches: int = _DEFAULT_MAX_WEB_SEARCHES_PER_TURN @@ -270,44 +170,30 @@ class LoopCapConfig: return cls() defaults = cls() return cls( - max_web_searches=_non_negative_int( - data.get("max_web_searches"), defaults.max_web_searches - ), - max_subagents=_non_negative_int( - data.get("max_subagents"), defaults.max_subagents - ), + max_web_searches=_int_at_least(data.get("max_web_searches"), defaults.max_web_searches, 0), + max_subagents=_int_at_least(data.get("max_subagents"), defaults.max_subagents, 0), ) _INTERACTIVE_PLATFORMS = frozenset({"cli", "tui", "desktop", "acp"}) - -# Platforms that are not chat gateways but whose work is a bounded, supervised -# task loop: a subagent inherits its parent's budget and is stopped by the -# parent; api_server runs have a live client holding the request. Both do -# real edit -> re-run work, so they keep the interactive (warn-only) default. +# Not chat gateways, but bounded supervised task loops (a subagent is stopped by +# its parent; api_server has a live client). Both do real edit -> re-run work, +# so they keep the interactive warn-only default. _SUPERVISED_TASK_PLATFORMS = frozenset({"subagent", "api_server"}) def _is_non_interactive_platform(platform: str | None) -> bool: - """Return true for gateway/cron sessions where tool loops are unattended.""" + """True for gateway/cron sessions where tool loops are unattended.""" if not isinstance(platform, str) or not platform.strip(): return False key = platform.strip().lower() - if key in _INTERACTIVE_PLATFORMS or key in _SUPERVISED_TASK_PLATFORMS: - return False - return True + return key not in _INTERACTIVE_PLATFORMS and key not in _SUPERVISED_TASK_PLATFORMS @dataclass(frozen=True) class IdenticalCallObservation: - """Outcome of observing one completed tool call for the stall guards. - - ``notice`` is the identical-call loop-breaker notice (appended after the - result). ``stub`` is the result-reference replacement for a byte-identical - duplicate result (replaces the result content). Both may be set on the - same call (3rd+ identical call): the stub replaces the payload and the - notice is appended after it. - """ + """Outcome of observing one completed call: ``notice`` is appended after the + result, ``stub`` replaces a byte-identical duplicate result. Both may be set.""" notice: str | None = None stub: str | None = None @@ -322,8 +208,7 @@ class ToolCallSignature: @classmethod def from_call(cls, tool_name: str, args: Mapping[str, Any] | None) -> "ToolCallSignature": - canonical = canonical_tool_args(args or {}) - return cls(tool_name=tool_name, args_hash=_sha256(canonical)) + return cls(tool_name=tool_name, args_hash=_sha256(canonical_tool_args(args or {}))) def to_metadata(self) -> dict[str, str]: """Return public metadata without raw argument values.""" @@ -362,31 +247,24 @@ class ToolGuardrailDecision: return data +def _canonical_json(value: Any) -> str: + return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), default=str) + + def canonical_tool_args(args: Mapping[str, Any]) -> str: """Return sorted compact JSON for parsed tool arguments.""" if not isinstance(args, Mapping): raise TypeError(f"tool args must be a mapping, got {type(args).__name__}") - return json.dumps( - args, - ensure_ascii=False, - sort_keys=True, - separators=(",", ":"), - default=str, - ) + return _canonical_json(args) def classify_tool_failure(tool_name: str, result: str | None) -> tuple[bool, str]: - """Safety-fallback classifier used only when callers don't pass ``failed``. + """Fallback classifier used only when callers don't pass ``failed``. Mirrors ``agent.display._detect_tool_failure`` exactly so the guardrail - never disagrees with the CLI's user-visible ``[error]`` tag. Production - callers in ``run_agent.py`` always pass an explicit ``failed=`` derived - from ``_detect_tool_failure``; this function exists so standalone callers - (tests, tooling) still get consistent behavior. + never disagrees with the CLI's user-visible ``[error]`` tag. """ - if result is None: - return False, "" - if file_mutation_result_landed(tool_name, result): + if result is None or file_mutation_result_landed(tool_name, result): return False, "" if tool_name == "terminal": @@ -399,9 +277,8 @@ def classify_tool_failure(tool_name: str, result: str | None) -> tuple[bool, str if tool_name == "memory": data = safe_json_loads(result) - if isinstance(data, dict): - if data.get("success") is False and "exceed the limit" in data.get("error", ""): - return True, " [full]" + if isinstance(data, dict) and data.get("success") is False and "exceed the limit" in data.get("error", ""): + return True, " [full]" lower = result[:500].lower() if '"error"' in lower or '"failed"' in lower or result.startswith("Error"): @@ -424,29 +301,17 @@ class ToolCallGuardrailController: self._progress_since_failure: dict[ToolCallSignature, bool] = {} self._no_progress: dict[ToolCallSignature, tuple[str, int]] = {} self._halt_decision: ToolGuardrailDecision | None = None - # Identical-call loop-breaker state (agent.stall_guards): tracks the - # CONSECUTIVE streak of identical (tool, canonical args) calls whose - # results were also identical. Any different call — or a different - # result — resets the streak, so legitimate re-reads after edits and - # varied polling are never flagged. Per-turn, like everything else here. - # NOTE: open PR #85352 (patrykkopycinski) tracks no-progress loops - # ACROSS turns via a detection window — a different mechanism from - # this per-turn consecutive streak. Coordinate future work there. + # Identical-call streak: CONSECUTIVE identical (tool, args) calls with + # identical results. Any different call or result resets it, so re-reads + # after edits and varied polling are never flagged. self._identical_streak_sig: ToolCallSignature | None = None self._identical_streak_result_hash: str = "" self._identical_streak_count: int = 0 - # tool_call_id of the FIRST call in the current streak, so a - # result-reference stub can point at the message that carries the - # full payload. + # tool_call_id of the streak's FIRST call, so a stub can point at the full payload. self._identical_streak_first_call_id: str = "" - # tool_call_id -> spillover file path for results that were persisted - # out of context (persisted-output preview). Lets a reference stub - # carry the file path so the reference can't dangle when the first - # occurrence entered context as a preview. + # tool_call_id -> spillover path, so a stub referencing a result that + # entered context only as a persisted-output preview can't dangle. self._persisted_result_paths: dict[str, str] = {} - # Per-turn runaway-loop cap counters. Reset every turn (this method - # runs at the start of each run_conversation), so the caps bound a - # single agent loop rather than accumulating across the session. self._turn_web_search_count = 0 self._turn_subagent_count = 0 @@ -454,21 +319,29 @@ class ToolCallGuardrailController: def halt_decision(self) -> ToolGuardrailDecision | None: return self._halt_decision - def before_call(self, tool_name: str, args: Mapping[str, Any] | None) -> ToolGuardrailDecision: - signature = ToolCallSignature.from_call(tool_name, _coerce_args(args)) + def _halt( + self, action: str, code: str, message: str, + tool_name: str, count: int, signature: ToolCallSignature, + ) -> ToolGuardrailDecision: + """Build a block/halt decision and record it as the turn's halt decision.""" + self._halt_decision = ToolGuardrailDecision( + action=action, code=code, message=message, + tool_name=tool_name, count=count, signature=signature, + ) + return self._halt_decision - # ── Per-turn runaway-loop caps ────────────────────────────────── - # These are hard ceilings on how many times a runaway-prone tool may - # be called within a single agent loop (turn). They apply regardless - # of hard_stop_enabled (which only governs the per-turn loop detector). - # We block BEFORE the call runs once the count is already at the cap, - # then increment for an allowed call so the (cap+1)-th is refused. - cap_block = self._check_loop_cap(tool_name, _coerce_args(args), signature) + def before_call(self, tool_name: str, args: Mapping[str, Any] | None) -> ToolGuardrailDecision: + args = _coerce_args(args) + signature = ToolCallSignature.from_call(tool_name, args) + allow = ToolGuardrailDecision(tool_name=tool_name, signature=signature) + + # Loop caps apply regardless of hard_stop_enabled (which only governs the detector). + cap_block = self._check_loop_cap(tool_name, args, signature) if cap_block is not None: return cap_block if not self.config.hard_stop_enabled: - return ToolGuardrailDecision(tool_name=tool_name, signature=signature) + return allow exact_count = self._exact_failure_counts.get(signature, 0) if self._progress_since_failure.get(signature): @@ -476,42 +349,27 @@ class ToolCallGuardrailController: # streak restarts in after_call if it fails again. exact_count = 0 if exact_count >= self.config.exact_failure_block_after: - decision = ToolGuardrailDecision( - action="block", - code="repeated_exact_failure_block", - message=( - f"Blocked {tool_name}: the same tool call failed {exact_count} " - "times with identical arguments. Stop retrying it unchanged; " - "change strategy or explain the blocker." - ), - tool_name=tool_name, - count=exact_count, - signature=signature, + return self._halt( + "block", "repeated_exact_failure_block", + f"Blocked {tool_name}: the same tool call failed {exact_count} " + "times with identical arguments. Stop retrying it unchanged; " + "change strategy or explain the blocker.", + tool_name, exact_count, signature, ) - self._halt_decision = decision - return decision if self._is_idempotent(tool_name): record = self._no_progress.get(signature) - if record is not None: - _result_hash, repeat_count = record - if repeat_count >= self.config.no_progress_block_after: - decision = ToolGuardrailDecision( - action="block", - code="idempotent_no_progress_block", - message=( - f"Blocked {tool_name}: this read-only call returned the same " - f"result {repeat_count} times. Stop repeating it unchanged; " - "use the result already provided or try a different query." - ), - tool_name=tool_name, - count=repeat_count, - signature=signature, - ) - self._halt_decision = decision - return decision + if record is not None and record[1] >= self.config.no_progress_block_after: + repeat_count = record[1] + return self._halt( + "block", "idempotent_no_progress_block", + f"Blocked {tool_name}: this read-only call returned the same " + f"result {repeat_count} times. Stop repeating it unchanged; " + "use the result already provided or try a different query.", + tool_name, repeat_count, signature, + ) - return ToolGuardrailDecision(tool_name=tool_name, signature=signature) + return allow def after_call( self, @@ -526,11 +384,16 @@ class ToolCallGuardrailController: if failed is None: failed, _ = classify_tool_failure(tool_name, result) + def warn(code: str, message: str, count: int) -> ToolGuardrailDecision: + return ToolGuardrailDecision( + action="warn", code=code, message=message, + tool_name=tool_name, count=count, signature=signature, + ) + if failed: # An identical failing call is only a REPLAY if nothing landed in - # between. If any mutating call succeeded since the previous - # identical failure (edit -> re-run pytest, click -> re-snapshot), - # the retry is a new experiment: restart the exact-args streak. + # between; a mutation since the last identical failure makes the + # retry a new experiment, so the exact-args streak restarts. if self._progress_since_failure.pop(signature, False): self._exact_failure_counts.pop(signature, None) exact_count = self._exact_failure_counts.get(signature, 0) + 1 @@ -540,53 +403,35 @@ class ToolCallGuardrailController: same_count = self._same_tool_failure_counts.get(tool_name, 0) + 1 self._same_tool_failure_counts[tool_name] = same_count - # same_tool_failure counts DIFFERENT args on one tool. For tools - # whose non-zero exit is ordinary work output (terminal, - # execute_code, pollers) a run of distinct red commands is - # diagnosis, not a loop — warn, never halt. The exact-args replay - # path still applies to them. - same_tool_halt_eligible = tool_name not in FAILURE_TOLERANT_TOOL_NAMES + # same_tool_failure counts DIFFERENT args on one tool; for + # failure-tolerant tools a run of distinct red commands is diagnosis, + # not a loop — warn, never halt (exact-args replay still applies). if ( self.config.hard_stop_enabled - and same_tool_halt_eligible + and tool_name not in FAILURE_TOLERANT_TOOL_NAMES and same_count >= self.config.same_tool_failure_halt_after ): - decision = ToolGuardrailDecision( - action="halt", - code="same_tool_failure_halt", - message=( - f"Stopped {tool_name}: it failed {same_count} times this turn. " - "Stop retrying the same failing tool path and choose a different approach." - ), - tool_name=tool_name, - count=same_count, - signature=signature, + return self._halt( + "halt", "same_tool_failure_halt", + f"Stopped {tool_name}: it failed {same_count} times this turn. " + "Stop retrying the same failing tool path and choose a different approach.", + tool_name, same_count, signature, ) - self._halt_decision = decision - return decision if self.config.warnings_enabled and exact_count >= self.config.exact_failure_warn_after: - return ToolGuardrailDecision( - action="warn", - code="repeated_exact_failure_warning", - message=( - f"{tool_name} has failed {exact_count} times with identical arguments. " - "This looks like a loop; inspect the error and change strategy " - "instead of retrying it unchanged." - ), - tool_name=tool_name, - count=exact_count, - signature=signature, + return warn( + "repeated_exact_failure_warning", + f"{tool_name} has failed {exact_count} times with identical arguments. " + "This looks like a loop; inspect the error and change strategy " + "instead of retrying it unchanged.", + exact_count, ) if self.config.warnings_enabled and same_count >= self.config.same_tool_failure_warn_after: - return ToolGuardrailDecision( - action="warn", - code="same_tool_failure_warning", - message=_tool_failure_recovery_hint(tool_name, same_count), - tool_name=tool_name, - count=same_count, - signature=signature, + return warn( + "same_tool_failure_warning", + _tool_failure_recovery_hint(tool_name, same_count), + same_count, ) return ToolGuardrailDecision(tool_name=tool_name, count=exact_count, signature=signature) @@ -595,10 +440,8 @@ class ToolCallGuardrailController: self._same_tool_failure_counts.pop(tool_name, None) # A successful mutation is progress for every failing signature still - # being counted this turn: the next identical retry runs against - # changed state, so it is a fresh attempt rather than a replay. Pure - # loops never mutate anything between attempts, so the replay detector - # keeps its teeth. + # counted this turn (next identical retry runs against changed state). + # Pure loops never mutate between attempts, so the replay detector keeps its teeth. if tool_name in PROGRESS_RESET_TOOL_NAMES or file_mutation_result_landed(tool_name, result): for sig in list(self._exact_failure_counts): self._progress_since_failure[sig] = True @@ -610,44 +453,22 @@ class ToolCallGuardrailController: result_hash = _result_hash(result) previous = self._no_progress.get(signature) - repeat_count = 1 - if previous is not None and previous[0] == result_hash: - repeat_count = previous[1] + 1 + repeat_count = previous[1] + 1 if previous is not None and previous[0] == result_hash else 1 self._no_progress[signature] = (result_hash, repeat_count) if self.config.warnings_enabled and repeat_count >= self.config.no_progress_warn_after: - return ToolGuardrailDecision( - action="warn", - code="idempotent_no_progress_warning", - message=( - f"{tool_name} returned the same result {repeat_count} times. " - "Use the result already provided or change the query instead of " - "repeating it unchanged." - ), - tool_name=tool_name, - count=repeat_count, - signature=signature, + return warn( + "idempotent_no_progress_warning", + f"{tool_name} returned the same result {repeat_count} times. " + "Use the result already provided or change the query instead of " + "repeating it unchanged.", + repeat_count, ) return ToolGuardrailDecision(tool_name=tool_name, count=repeat_count, signature=signature) def _is_idempotent(self, tool_name: str) -> bool: - if tool_name in self.config.mutating_tools: - return False - return tool_name in self.config.idempotent_tools - - def observe_identical_call( - self, - tool_name: str, - args: Mapping[str, Any] | None, - result: str | None, - ) -> str | None: - """Track consecutive identical calls; return a loop-breaker notice or None. - - Back-compat wrapper around :meth:`observe_call` for callers that only - care about the loop-breaker notice. - """ - return self.observe_call(tool_name, args, result).notice + return tool_name not in self.config.mutating_tools and tool_name in self.config.idempotent_tools def observe_call( self, @@ -660,29 +481,15 @@ class ToolCallGuardrailController: ) -> "IdenticalCallObservation": """Track consecutive identical calls; return notice + dedupe stub info. - Two independent outputs from the same consecutive-streak tracker: - - - ``notice``: the compact loop-breaker notice, fired when the SAME - tool is called with identical canonical arguments AND returns an - identical result for the ``STALL_GUARD_IDENTICAL_CALL_THRESHOLD``-th - (and every subsequent) consecutive time within the turn. Purely - observational — never blocks the call. Allowlisted pollers - (``is_stall_guard_repeatable``) are exempt from the NOTICE. - - ``stub``: a short reference replacement for the CURRENT result, - produced from the 2nd consecutive identical call whose fresh result - is byte-identical to the previous one. The tool still executed — - only the context representation is deduplicated, so polling - semantics are preserved (a changed result flows through whole and - resets the streak). Pollers are NOT exempt from stubbing: for a - poller, an identical result means nothing changed, which is exactly - when the stub saves the most context and loses nothing. Results - under ``IDENTICAL_RESULT_STUB_MIN_CHARS`` and failed/error results - are never stubbed, and only plain-string results are considered. - - Any intervening different call or changed result resets the streak. - Callers substitute/append at tool RESULT construction time, which is - cache-safe: tool results are append-only and never mutate - already-sent context. + ``notice`` fires from the ``STALL_GUARD_IDENTICAL_CALL_THRESHOLD``-th + consecutive identical (tool, args, result) call; purely observational, + pollers exempt. ``stub`` replaces the CURRENT result from the 2nd + byte-identical repeat — the tool still executed, only the context + representation is deduplicated, so polling semantics survive (a changed + result flows through whole and resets the streak). Pollers are NOT + exempt from stubbing: an unchanged poll is exactly when the stub saves + the most. Short results, failed results and non-string results are never + stubbed. Callers substitute at result construction time, which is cache-safe. """ is_plain_str = isinstance(result, str) signature = ToolCallSignature.from_call(tool_name, _coerce_args(args)) @@ -695,8 +502,7 @@ class ToolCallGuardrailController: ): self._identical_streak_count += 1 else: - # New streak (or non-string result, which never forms a streak — - # multimodal content lists pass through untouched). + # New streak; non-string (multimodal) results never form one. self._identical_streak_sig = signature if is_plain_str else None self._identical_streak_result_hash = result_hash self._identical_streak_count = 1 if is_plain_str else 0 @@ -705,10 +511,7 @@ class ToolCallGuardrailController: count = self._identical_streak_count notice = None - if ( - not is_stall_guard_repeatable(tool_name) - and count >= STALL_GUARD_IDENTICAL_CALL_THRESHOLD - ): + if not is_stall_guard_repeatable(tool_name) and count >= STALL_GUARD_IDENTICAL_CALL_THRESHOLD: ordinal = f"{count}{'th' if 11 <= count % 100 <= 13 else {1: 'st', 2: 'nd', 3: 'rd'}.get(count % 10, 'th')}" notice = ( f"[hermes note: this is the {ordinal} consecutive identical call to " @@ -716,62 +519,36 @@ class ToolCallGuardrailController: "Do not repeat it — change arguments, use a different tool, or " "proceed with what you have.]" ) - # Hard-stop widening (#89069 / #100849 bundle): the per-turn - # no-progress BLOCK above only covers tools in idempotent_tools, so - # a model replaying the same successful `terminal`/`skill_view` - # call with a byte-identical result ran until the iteration budget. - # The consecutive-identical streak is tool-agnostic; when hard - # stops are enabled, halt at the same idempotent_no_progress - # threshold. Pollers stay exempt (an unchanged poll is progress). + # The no-progress BLOCK in before_call only covers idempotent_tools; this + # streak is tool-agnostic, so with hard stops on, halt at the same threshold + # (a model replaying a successful `terminal` call otherwise runs to the budget). if ( self.config.hard_stop_enabled and count >= self.config.no_progress_block_after and self._halt_decision is None ): - self._halt_decision = ToolGuardrailDecision( - action="halt", - code="identical_call_streak_halt", - message=( - f"Stopped {tool_name}: the same call with identical arguments " - f"returned the same result {count} times in a row. Stop " - "repeating it unchanged; use the result already provided or " - "change strategy." - ), - tool_name=tool_name, - count=count, - signature=signature, + self._halt( + "halt", "identical_call_streak_halt", + f"Stopped {tool_name}: the same call with identical arguments " + f"returned the same result {count} times in a row. Stop " + "repeating it unchanged; use the result already provided or " + "change strategy.", + tool_name, count, signature, ) stub = None - if ( - is_plain_str - and count >= 2 - and not failed - and len(result) >= IDENTICAL_RESULT_STUB_MIN_CHARS - ): + if is_plain_str and count >= 2 and not failed and len(result) >= IDENTICAL_RESULT_STUB_MIN_CHARS: stub = self._build_result_reference_stub(tool_name, args) return IdenticalCallObservation(notice=notice, stub=stub) def record_persisted_result(self, tool_call_id: str, file_path: str) -> None: - """Remember the spillover path a persisted result was saved to. - - When the first occurrence of a result entered context as a - persisted-output preview, a later reference stub must carry the - spillover file path so the reference can't dangle. - """ + """Remember the spillover path a persisted result was saved to.""" if tool_call_id and file_path: self._persisted_result_paths[tool_call_id] = file_path - def _build_result_reference_stub( - self, tool_name: str, args: Mapping[str, Any] | None - ) -> str: - """Build the reference stub replacing a byte-identical duplicate result. - - Carries the tool name + a canonical-args preview so that even if - context compression later evicts the referenced result, the model - still knows WHAT the call was (cheap dangling-reference mitigation). - """ + def _build_result_reference_stub(self, tool_name: str, args: Mapping[str, Any] | None) -> str: + """Reference stub for a byte-identical duplicate result (tool + args preview).""" try: args_preview = canonical_tool_args(_coerce_args(args)) except TypeError: @@ -799,75 +576,48 @@ class ToolCallGuardrailController: args: Mapping[str, Any], signature: ToolCallSignature, ) -> ToolGuardrailDecision | None: - """Enforce and advance the per-turn runaway-loop counters. + """Block once a per-turn cap is reached, else advance the counter and return None. - Returns a ``block`` decision when the cap is already reached, otherwise - increments the relevant counter for the allowed call and returns - ``None``. A cap of 0 disables that limit entirely. Counters reset each - turn via ``reset_for_turn``. + A cap of 0 disables that limit. Blocking happens BEFORE the call when + the count is already at the cap, so the (cap+1)-th call is refused. """ caps = self.config.loop_caps - if tool_name == "web_search": - cap = caps.max_web_searches - if cap and self._turn_web_search_count >= cap: - decision = ToolGuardrailDecision( - action="block", - code="loop_web_search_cap", - message=( - f"Blocked web_search: this turn has already made {cap} " - "web searches, the per-turn limit. This looks like a " - "runaway search loop. Work with the results you already " - "have and give the user your answer." - ), - tool_name=tool_name, - count=self._turn_web_search_count, - signature=signature, - ) - self._halt_decision = decision - return decision - self._turn_web_search_count += 1 - return None - - if tool_name == "delegate_task": - cap = caps.max_subagents - if not cap: - return None - spawn_count = _subagent_spawn_count(args) - if spawn_count == 0: - # Control action (list/steer/stop) — spawns nothing. Never - # block: once the spawn cap is hit, steering/stopping the - # existing children is exactly what should still work. - return None - if self._turn_subagent_count >= cap: - decision = ToolGuardrailDecision( - action="block", - code="loop_subagent_cap", - message=( - f"Blocked delegate_task: this turn has already spawned " - f"{self._turn_subagent_count} subagents (limit {cap}). " - "This looks like a runaway delegation loop. Finish the " - "work with the results you have and answer the user." - ), - tool_name=tool_name, - count=self._turn_subagent_count, - signature=signature, - ) - self._halt_decision = decision - return decision - self._turn_subagent_count += spawn_count + cap, count, increment = caps.max_web_searches, self._turn_web_search_count, 1 + code, message = "loop_web_search_cap", ( + f"Blocked web_search: this turn has already made {cap} " + "web searches, the per-turn limit. This looks like a " + "runaway search loop. Work with the results you already " + "have and give the user your answer." + ) + elif tool_name == "delegate_task": + cap, count = caps.max_subagents, self._turn_subagent_count + # Control actions (list/steer/stop) spawn nothing and must keep working after the cap is hit. + increment = _subagent_spawn_count(args) if cap else 0 + if increment == 0: + return None + code, message = "loop_subagent_cap", ( + f"Blocked delegate_task: this turn has already spawned " + f"{count} subagents (limit {cap}). " + "This looks like a runaway delegation loop. Finish the " + "work with the results you have and answer the user." + ) + else: return None + if cap and count >= cap: + return self._halt("block", code, message, tool_name, count, signature) + if tool_name == "web_search": + self._turn_web_search_count += increment + else: + self._turn_subagent_count += increment return None def toolguard_synthetic_result(decision: ToolGuardrailDecision) -> str: """Build a synthetic role=tool content string for a blocked tool call.""" return json.dumps( - { - "error": decision.message, - "guardrail": decision.to_metadata(), - }, + {"error": decision.message, "guardrail": decision.to_metadata()}, ensure_ascii=False, ) @@ -877,11 +627,7 @@ def append_toolguard_guidance(result: str, decision: ToolGuardrailDecision) -> s if decision.action not in {"warn", "halt"} or not decision.message: return result label = "Tool loop hard stop" if decision.action == "halt" else "Tool loop warning" - suffix = ( - f"\n\n[{label}: " - f"{decision.code}; count={decision.count}; {decision.message}]" - ) - return (result or "") + suffix + return (result or "") + f"\n\n[{label}: {decision.code}; count={decision.count}; {decision.message}]" def _tool_failure_recovery_hint(tool_name: str, count: int) -> str: @@ -912,13 +658,7 @@ def _result_hash(result: str | None) -> str: parsed = safe_json_loads(result or "") if parsed is not None: try: - canonical = json.dumps( - parsed, - ensure_ascii=False, - sort_keys=True, - separators=(",", ":"), - default=str, - ) + canonical = _canonical_json(parsed) except TypeError: canonical = str(parsed) else: @@ -942,50 +682,27 @@ def _as_bool(value: Any, default: bool) -> bool: return default -def _positive_int(value: Any, default: int) -> int: +def _int_at_least(value: Any, default: int, minimum: int) -> int: + """Int parser: junk/None/below-minimum fall back to default (caps use minimum 0 so 0 = disabled).""" if value is None: return default try: parsed = int(value) except (TypeError, ValueError): return default - return parsed if parsed >= 1 else default - - -def _non_negative_int(value: Any, default: int) -> int: - """Parse a session-cap value. 0 is a valid (disable) value; negatives and - junk fall back to the default.""" - if value is None: - return default - try: - parsed = int(value) - except (TypeError, ValueError): - return default - return parsed if parsed >= 0 else default + return parsed if parsed >= minimum else default def _subagent_spawn_count(args: Mapping[str, Any]) -> int: - """How many subagents a single delegate_task call spawns. - - delegate_task runs in one of two modes: a batch (``tasks`` is a non-empty - list, one child per item) or a single task (``goal``). Count the batch size - when present, otherwise 1, so the session subagent cap reflects real spawns - rather than delegate_task invocations. Control actions (list/steer/stop) - spawn nothing and must not consume the cap. - """ - if isinstance(args, Mapping): - action = str(args.get("action") or "").strip().lower() - if action in ("list", "steer", "stop"): - return 0 - tasks = args.get("tasks") if isinstance(args, Mapping) else None - if isinstance(tasks, list) and tasks: - return len(tasks) - return 1 + """Subagents one delegate_task call spawns: batch size when ``tasks`` is a + non-empty list, else 1; control actions (list/steer/stop) spawn 0.""" + if str(args.get("action") or "").strip().lower() in ("list", "steer", "stop"): + return 0 + tasks = args.get("tasks") + return len(tasks) if isinstance(tasks, list) and tasks else 1 def _sha256(value: str) -> str: - # surrogatepass: tool results scraped from the web can carry unpaired - # UTF-16 surrogates (e.g. half of a mathematical-bold pair); a strict - # encode raises and takes down the whole conversation loop. The hash only - # needs deterministic bytes, not valid UTF-8. + # surrogatepass: web-scraped results can carry unpaired UTF-16 surrogates; a + # strict encode would raise and take down the conversation loop. return hashlib.sha256(value.encode("utf-8", "surrogatepass")).hexdigest() diff --git a/tests/agent/test_stall_guards.py b/tests/agent/test_stall_guards.py index 013f8b83f8..a0909dffb6 100644 --- a/tests/agent/test_stall_guards.py +++ b/tests/agent/test_stall_guards.py @@ -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 # block that maybe_persist_tool_result builds — assert the round trip. From 624a752e79f6057b46381aaedece8ed96f0ca081 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 10:36:07 -0700 Subject: [PATCH 4/4] =?UTF-8?q?refactor(agent/runtime):=20deadline/file=5F?= =?UTF-8?q?safety/estop/lifecycle=20leaf=20modules=20=E2=80=94=20dedupe=20?= =?UTF-8?q?result=20plumbing,=20drop=20dead=20guard=20code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - deadline: _result()/_abandon() replace 7 BoundedResult constructions and 2 cancel+callback sites; timers handled as a list; dead raise_if_timed_out removed. - file_safety: retired classify_cross_profile_target (0 refs; get_cross_profile_warning stub kept for external callers), _home_and_resolved/_mirror_warning shared by the sandbox/container mirror guards; _find_sandbox_mirror_segments inlined. - estop: _hermes_home/_canonical_root now the file_safety helpers; _reset_log_state_for_tests inlined into its only test. - subagent_lifecycle: _validate_request driven by _UNSUPPORTED_REQUEST_FIELDS table. - turn_liveness: dead start()/_abort_message removed, _emit_warning shared. - process_bootstrap: _enable_happy_eyeballs reused by the client variant. - Comment/docstring compaction across the remaining leaf modules. --- agent/__init__.py | 7 +- agent/battery.py | 53 +- agent/deadline.py | 440 +++-------- agent/delegation_context.py | 126 +-- agent/errors.py | 3 - agent/estop.py | 122 +-- agent/file_safety.py | 725 ++++++------------ agent/kanban_stop.py | 47 +- agent/oneshot.py | 52 +- agent/process_bootstrap.py | 206 ++--- agent/reactions.py | 28 +- agent/session_activity.py | 56 +- agent/subagent_lifecycle.py | 282 +++---- agent/thread_scoped_output.py | 59 +- agent/turn_liveness.py | 278 ++----- tests/agent/test_deadline.py | 5 +- tests/agent/test_file_safety_cross_profile.py | 57 +- .../agent/test_file_safety_sandbox_mirror.py | 4 - tests/test_estop.py | 4 +- 19 files changed, 706 insertions(+), 1848 deletions(-) diff --git a/agent/__init__.py b/agent/__init__.py index 41136f9b63..77f1cad846 100644 --- a/agent/__init__.py +++ b/agent/__init__.py @@ -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 diff --git a/agent/battery.py b/agent/battery.py index a1c0f32fa4..9343c69d27 100644 --- a/agent/battery.py +++ b/agent/battery.py @@ -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 diff --git a/agent/deadline.py b/agent/deadline.py index e3357f8a24..ecd9bfc306 100644 --- a/agent/deadline.py +++ b/agent/deadline.py @@ -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.`` > ``env_var`` > ``default``. - Precedence (established by the ``providers.*.request_timeout_seconds`` - pattern — config wins over the legacy env var): - - 1. ``timeouts.`` 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 diff --git a/agent/delegation_context.py b/agent/delegation_context.py index 9b8bce9759..5ff3eb8e8c 100644 --- a/agent/delegation_context.py +++ b/agent/delegation_context.py @@ -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) diff --git a/agent/errors.py b/agent/errors.py index 8b3db5a358..66d1c1329a 100644 --- a/agent/errors.py +++ b/agent/errors.py @@ -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.""" diff --git a/agent/estop.py b/agent/estop.py index b62fc378d6..59cb0ffbc4 100644 --- a/agent/estop.py +++ b/agent/estop.py @@ -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/. - ``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/) 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() diff --git a/agent/file_safety.py b/agent/file_safety.py index 42ccda3332..c878c087d4 100644 --- a/agent/file_safety.py +++ b/agent/file_safety.py @@ -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.()`` (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 /... stay guarded when + running under a profile (HERMES_HOME = /profiles/). + """ + 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 / . 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 / : (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 /auth.json etc. are also - # blocked when running under a profile (HERMES_HOME points at - # /profiles/ 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 . - 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 -# ``/profiles//``. 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 / / /profiles// -# 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: - # ``//...`` → default profile. - target_profile = "default" - area = parts[0] - elif ( - parts[0] == "profiles" - and len(parts) >= 3 - and parts[2] in PROFILE_SCOPED_AREAS - ): - # ``/profiles///...`` → 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: # /profiles//sandboxes///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///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///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 / / / home / .hermes / - 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///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 / / / home / .hermes / ; 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///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", ) diff --git a/agent/kanban_stop.py b/agent/kanban_stop.py index e7c2eae828..4cedc78687 100644 --- a/agent/kanban_stop.py +++ b/agent/kanban_stop.py @@ -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" diff --git a/agent/oneshot.py b/agent/oneshot.py index 9ab92cf150..a375f5cc89 100644 --- a/agent/oneshot.py +++ b/agent/oneshot.py @@ -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) diff --git a/agent/process_bootstrap.py b/agent/process_bootstrap.py index 341126c919..6baaa59efb 100644 --- a/agent/process_bootstrap.py +++ b/agent/process_bootstrap.py @@ -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() diff --git a/agent/reactions.py b/agent/reactions.py index 375366ff70..e6c565db7f 100644 --- a/agent/reactions.py +++ b/agent/reactions.py @@ -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 `` 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 diff --git a/agent/session_activity.py b/agent/session_activity.py index 719a58a9ee..ccf9c8b69a 100644 --- a/agent/session_activity.py +++ b/agent/session_activity.py @@ -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)) diff --git a/agent/subagent_lifecycle.py b/agent/subagent_lifecycle.py index 319e85a784..e76101c051 100644 --- a/agent/subagent_lifecycle.py +++ b/agent/subagent_lifecycle.py @@ -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.") diff --git a/agent/thread_scoped_output.py b/agent/thread_scoped_output.py index 3c4a7be891..bbbb24f3ae 100644 --- a/agent/thread_scoped_output.py +++ b/agent/thread_scoped_output.py @@ -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) diff --git a/agent/turn_liveness.py b/agent/turn_liveness.py index 939fc9b917..04e381df1f 100644 --- a/agent/turn_liveness.py +++ b/agent/turn_liveness.py @@ -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", + ) diff --git a/tests/agent/test_deadline.py b/tests/agent/test_deadline.py index 5122b0f26a..97b288d969 100644 --- a/tests/agent/test_deadline.py +++ b/tests/agent/test_deadline.py @@ -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): diff --git a/tests/agent/test_file_safety_cross_profile.py b/tests/agent/test_file_safety_cross_profile.py index d3a68b6fb5..3be8ea8791 100644 --- a/tests/agent/test_file_safety_cross_profile.py +++ b/tests/agent/test_file_safety_cross_profile.py @@ -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 # --------------------------------------------------------------------------- diff --git a/tests/agent/test_file_safety_sandbox_mirror.py b/tests/agent/test_file_safety_sandbox_mirror.py index bb59c1ecfb..27e120088f 100644 --- a/tests/agent/test_file_safety_sandbox_mirror.py +++ b/tests/agent/test_file_safety_sandbox_mirror.py @@ -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 diff --git a/tests/test_estop.py b/tests/test_estop.py index e6917c7d6d..85abbfaaab 100644 --- a/tests/test_estop.py +++ b/tests/test_estop.py @@ -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")