Skip to content

The agent that grows with you

refactor(gateway): simplify session, status, stream_consumer, kanban_watchers, relay adapter, hosted-room driver/discussion/replicas, shutdown/lifecycle, pairing, channel_directory, control_socket and small modules

Teknium659c6b9fff43
diff --git a/gateway/agent_cache_pressure.py b/gateway/agent_cache_pressure.py
index 91fa999b64d..1fc62dbadb5 100644
--- a/gateway/agent_cache_pressure.py
+++ b/gateway/agent_cache_pressure.py
@@ -1,27 +1,15 @@
"""Memory-pressure bounds for the gateway's per-session AIAgent cache.
-The gateway caches one ``AIAgent`` per session so a long-lived conversation
-reuses its prompt prefix instead of rebuilding the system prompt every turn.
-Each cached agent also pins ``_session_messages`` — the full live transcript,
-tool outputs included, which is tens of MB on a tool-heavy session.
-
-``gateway/run.py`` bounds that cache two ways, and both are blind to how much
-memory it actually holds:
-
-* the LRU cap counts *entries*, not bytes, and 128 warm transcripts is
- several GB;
-* the idle TTL only sheds agents that went quiet for an hour, and it
- deliberately defers eviction for a finalizable session that has not expired
- yet, so a busy gateway hoards every transcript all day.
-
-This module supplies the missing signal: the process's own anonymous RSS,
-compared against a budget derived from the cgroup limit the gateway actually
-runs under. ``GatewayRunner._sweep_agent_cache_under_pressure`` uses it to
-shed LRU transcripts through the existing soft-eviction path, which rebuilds
-from the persisted session on the next turn (#80764).
-
-Everything here is pure or read-only so it can be tested without a gateway.
-Config lives under ``agent.agent_cache`` in ``config.yaml``.
+Each cached ``AIAgent`` pins ``_session_messages`` (the full live transcript,
+tool outputs included — tens of MB on a tool-heavy session). The cache's LRU
+cap counts entries, not bytes, and the idle TTL defers eviction for busy
+sessions, so neither sees actual memory use. This module supplies that signal:
+the process's own anonymous RSS against a budget derived from the cgroup limit.
+``GatewayRunner._sweep_agent_cache_under_pressure`` uses it to shed LRU
+transcripts via the soft-eviction path (rebuilt from the persisted session on
+the next turn).
+
+Everything here is pure or read-only. Config lives under ``agent.agent_cache``.
"""
from __future__ import annotations
@@ -32,20 +20,16 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Iterable, List, Optional, Tuple
-# Fraction of the resolved memory limit at which we start shedding
-# transcripts. Deliberately well under the limit: on the reported incident
-# the gateway hit cgroup ``memory.high`` throttling with swap full, and a
-# SIGTERM flush from there could not finish inside systemd's stop timeout.
-# Eviction has to happen while the process still has room to breathe.
+# Shed well under the limit: once cgroup ``memory.high`` throttling kicks in
+# (swap full), a SIGTERM flush cannot finish inside systemd's stop timeout.
_AUTO_BUDGET_FRACTION = 0.65
-# Below this a "budget" is noise — small containers would evict on every pass
-# and never keep a warm prefix.
+# Below this a budget is noise — small containers would evict every pass and
+# never keep a warm prefix.
_AUTO_BUDGET_FLOOR_MB = 512
_DEFAULT_MAX_EVICTIONS_PER_PASS = 16
-# Never let a pressure pass touch the hottest sessions: they are the ones
-# whose prompt cache is worth the most, and shedding them just moves the cost
-# to the next turn instead of removing it.
+# Never shed the hottest sessions: their prompt cache is worth the most, and
+# evicting them just moves the cost to the next turn.
_DEFAULT_PROTECT_RECENT = 8
_BYTES_PER_MB = 1024 * 1024
@@ -55,9 +39,9 @@ _BYTES_PER_MB = 1024 * 1024
class AgentCacheBounds:
"""Operator-facing bounds for the per-session agent cache.
- ``max_size`` and ``idle_ttl_secs`` are ``None`` when the operator did not
- set them, so ``gateway/run.py`` keeps using its module-level defaults.
- ``memory_high_mb`` is ``None`` when pressure eviction is switched off.
+ ``max_size`` / ``idle_ttl_secs`` are ``None`` when unset so ``gateway/run.py``
+ keeps its module defaults; ``memory_high_mb`` is ``None`` when pressure
+ eviction is off.
"""
max_size: Optional[int] = None
@@ -67,37 +51,33 @@ class AgentCacheBounds:
protect_recent: int = _DEFAULT_PROTECT_RECENT
-def _positive_int(value: Any) -> Optional[int]:
+def _positive(value: Any, cast: Callable[[Any], Any]) -> Any:
+ """``cast(value)`` if it is a positive number (bools rejected), else None."""
if isinstance(value, bool) or value is None:
return None
try:
- parsed = int(value)
+ parsed = cast(value)
except (TypeError, ValueError):
return None
return parsed if parsed > 0 else None
+def _positive_int(value: Any) -> Optional[int]:
+ return _positive(value, int)
+
+
def _positive_float(value: Any) -> Optional[float]:
- if isinstance(value, bool) or value is None:
- return None
- try:
- parsed = float(value)
- except (TypeError, ValueError):
- return None
- return parsed if parsed > 0 else None
+ return _positive(value, float)
def _cgroup_limit_bytes() -> Optional[int]:
- """Return the memory limit this process runs under, if it is cgroup-capped.
-
- Prefers cgroup v2 ``memory.high`` (the throttling point — passing it is
- what stalled the reported shutdown) over ``memory.max``, and falls back to
- cgroup v1. ``max`` / absurd sentinel values mean "unlimited".
+ """Return the memory limit this process runs under, if cgroup-capped.
- Checks the process's *own* cgroup first (where a systemd unit's
- ``MemoryHigh=``/``MemoryMax=`` actually lands — the root files read
- ``max`` on those deployments), then walks up to the root for
- container-style limits.
+ Prefers cgroup v2 ``memory.high`` (the throttling point) over ``memory.max``,
+ then cgroup v1. Checks the process's *own* cgroup first (where a systemd
+ unit's ``MemoryHigh=``/``MemoryMax=`` lands — the root files read ``max``
+ there), then the root for container-style limits. ``max`` and the v1
+ near-2^63 sentinel mean unlimited.
"""
if sys.platform != "linux":
return None
@@ -109,19 +89,12 @@ def _cgroup_limit_bytes() -> Optional[int]:
except Exception:
own = None
if own and own != "/":
- candidates.extend(
- (
- f"/sys/fs/cgroup{own}/memory.high",
- f"/sys/fs/cgroup{own}/memory.max",
- )
- )
- candidates.extend(
- (
- "/sys/fs/cgroup/memory.high",
- "/sys/fs/cgroup/memory.max",
- "/sys/fs/cgroup/memory/memory.limit_in_bytes",
- )
- )
+ candidates += [f"/sys/fs/cgroup{own}/memory.high", f"/sys/fs/cgroup{own}/memory.max"]
+ candidates += [
+ "/sys/fs/cgroup/memory.high",
+ "/sys/fs/cgroup/memory.max",
+ "/sys/fs/cgroup/memory/memory.limit_in_bytes",
+ ]
for candidate in candidates:
try:
raw = Path(candidate).read_text(encoding="utf-8").strip()
@@ -133,7 +106,6 @@ def _cgroup_limit_bytes() -> Optional[int]:
limit = int(raw)
except ValueError:
continue
- # cgroup v1 reports "unlimited" as a near-2^63 sentinel.
if limit <= 0 or limit >= (1 << 62):
continue
return limit
@@ -154,12 +126,10 @@ def _total_memory_bytes() -> Optional[int]:
def resolve_memory_high_mb(setting: Any) -> Optional[int]:
- """Resolve the ``memory_high_mb`` setting into an absolute MB budget.
+ """Resolve ``memory_high_mb`` into an absolute MB budget.
- ``"auto"`` derives a budget from the cgroup limit the gateway runs under
- (or total RAM when uncapped), which is what makes this fix work out of the
- box on the containerised/systemd deployments where the leak bites. A
- positive number is taken literally; anything falsy disables the pass.
+ ``"auto"`` derives it from the cgroup limit (or total RAM when uncapped);
+ a positive number is literal; anything falsy/off disables the pass.
"""
if isinstance(setting, str):
normalized = setting.strip().lower()
@@ -183,11 +153,10 @@ def resolve_memory_high_mb(setting: Any) -> Optional[int]:
def resolve_agent_cache_bounds(config: Any) -> AgentCacheBounds:
- """Read ``agent.agent_cache`` out of a raw config mapping.
+ """Read ``agent.agent_cache`` out of the *raw* config mapping.
- Reads the *raw* user config (the gateway's loader does not deep-merge
- ``DEFAULT_CONFIG``), so an absent key stays absent and the caller can tell
- "operator chose 128" from "operator said nothing".
+ The gateway's loader does not deep-merge ``DEFAULT_CONFIG``, so an absent
+ key stays absent and callers can tell "operator chose 128" from "unset".
"""
section: Any = None
if isinstance(config, dict):
@@ -200,15 +169,15 @@ def resolve_agent_cache_bounds(config: Any) -> AgentCacheBounds:
max_evictions = _positive_int(section.get("max_evictions_per_pass"))
protect_recent = section.get("protect_recent")
protect_parsed = _positive_int(protect_recent)
+ # 0 means "shed anything" — distinct from unset. The bool guard keeps
+ # `protect_recent: false` (False == 0) on the default instead of silently
+ # disabling MRU protection.
if (
protect_parsed is None
and isinstance(protect_recent, int)
and not isinstance(protect_recent, bool)
and protect_recent == 0
):
- # 0 means "shed anything" — distinct from unset. The isinstance
- # guards keep `protect_recent: false` (a YAML-typo bool, False == 0)
- # on the default instead of silently disabling MRU protection.
protect_parsed = 0
return AgentCacheBounds(
@@ -227,22 +196,18 @@ def resolve_agent_cache_bounds(config: Any) -> AgentCacheBounds:
def read_anon_rss_mb() -> Optional[int]:
"""Return the process's anonymous resident memory in MB, or None.
- Anonymous pages are the ones cached transcripts live in — the reported
- incident measured 11.0 GB of anon out of 11.0 GB total, so file-backed
- pages are noise here. ``collect_memory_snapshot`` already reads
- ``/proc/self/status`` without a dependency; psutil covers everything else,
- where only total RSS is available.
+ Anonymous pages are where cached transcripts live; file-backed pages are
+ noise. ``collect_memory_snapshot`` reads ``/proc/self/status`` without a
+ dependency; psutil covers other platforms (total RSS only).
"""
try:
from hermes_cli.mem_trim import collect_memory_snapshot
snapshot = collect_memory_snapshot()
- anon_kib = snapshot.get("rss_anon_kib")
- if isinstance(anon_kib, int) and anon_kib > 0:
- return anon_kib // 1024
- rss_kib = snapshot.get("rss_kib")
- if isinstance(rss_kib, int) and rss_kib > 0:
- return rss_kib // 1024
+ for key in ("rss_anon_kib", "rss_kib"):
+ kib = snapshot.get(key)
+ if isinstance(kib, int) and kib > 0:
+ return kib // 1024
except Exception:
pass
@@ -257,14 +222,11 @@ def read_anon_rss_mb() -> Optional[int]:
def transcript_persistence_caught_up(agent: Any) -> bool:
"""True when the agent's live transcript is fully on disk.
- Soft eviction drops ``_session_messages`` and rebuilds it from the
- persisted session next turn, so it is only safe once persistence has
- caught up. ``_last_flushed_db_idx`` is advanced to ``len(messages)`` by
- ``AIAgent._flush_messages_to_session_db`` and only on a fully successful
- write — the same divergence the FTS write-corruption guard reacts to when
- it preserves live history over a lagging transcript. Unknown shapes are
- treated as *not* caught up: a skipped eviction costs memory, a wrong one
- costs the user their conversation.
+ Soft eviction drops ``_session_messages`` and rebuilds from the persisted
+ session, so it is only safe once ``_last_flushed_db_idx`` (advanced to
+ ``len(messages)`` by ``AIAgent._flush_messages_to_session_db`` only on a
+ fully successful write) has caught up. Unknown shapes are *not* caught up:
+ a skipped eviction costs memory, a wrong one costs the conversation.
"""
messages = getattr(agent, "_session_messages", None)
if not isinstance(messages, list):
@@ -284,15 +246,11 @@ def plan_pressure_evictions(
) -> List[Tuple[str, Any]]:
"""Choose which cached sessions to shed, least-recently-used first.
- ``ordered_entries`` must be in LRU→MRU order (the cache is an
- ``OrderedDict`` kept in that order by ``move_to_end`` on every hit). The
- batch is capped so one pass cannot stall the gateway tearing down clients.
-
- ``protect_recent`` is an upper bound, clamped to half the cache: a handful
- of sessions can be big enough to exhaust the budget on their own (a single
- tool-heavy transcript runs to hundreds of MB), and a fixed guard would
- then protect the entire cache and leave the gateway climbing toward the
- OOM killer with nothing it is willing to shed.
+ ``ordered_entries`` must be LRU→MRU (the cache OrderedDict is kept that way
+ by ``move_to_end`` on every hit). The batch is capped so one pass cannot
+ stall the gateway. ``protect_recent`` is clamped to half the cache: a few
+ huge transcripts can exhaust the budget alone, and a fixed guard would then
+ protect the whole cache with nothing left to shed.
"""
entries = list(ordered_entries)
if max_evictions <= 0 or not entries:
diff --git a/gateway/browser_control_artifacts.py b/gateway/browser_control_artifacts.py
index 433091549ff..7b31875d07a 100644
--- a/gateway/browser_control_artifacts.py
+++ b/gateway/browser_control_artifacts.py
@@ -1,55 +1,31 @@
"""One-shot artifact transport for browser control (Gateway side).
-Phase 8 Task 29: authenticated one-shot HTTPS upload/download of bounded
-browser-control artifacts (screenshots, PDFs, uploads) with SHA-256
-validation, exact MIME/size caps, a controlled artifact root, and TTL
-cleanup. This module is the transport-neutral store core: it knows nothing
-about aiohttp or the API server — the routes in
-:mod:`gateway.platforms.api_server` authenticate callers and enforce rate
-limits, then hand bytes to this store.
-
-Why a store at all: the controller WebSocket is a command channel, not a
-file pipe. A controller action that needs bytes (a screenshot upload, a
-downloaded PDF) references an artifact by its server-minted id; the agent
-side later retrieves it over HTTPS. Base64 screenshots or files in
-controller WebSocket frames are therefore structurally impossible: the
-frame carries only ``artifact_id`` strings, and the bytes live on disk
+Transport-neutral store core for bounded browser-control artifacts
+(screenshots, PDFs, uploads). It knows nothing about aiohttp: the routes in
+:mod:`gateway.platforms.api_server` authenticate callers and rate-limit, then
+hand bytes here. The controller WebSocket is a command channel, not a file
+pipe — frames carry only ``artifact_id`` strings and the bytes live on disk
under a controlled root for a short TTL.
-Contract (exercised by tests/gateway/test_browser_control_artifacts.py):
+Contract (tests/gateway/test_browser_control_artifacts.py):
-- **Server-minted ids, no traversal.** ``store`` assigns a fresh random hex
- id; ``_artifact_path`` accepts only ``[0-9a-f]{N}`` ids and resolves them
- strictly inside the root. Client-supplied filenames are metadata only
- and never become filesystem paths.
+- Server-minted ``[0-9a-f]{32}`` ids resolved strictly inside the root;
+ client filenames are metadata only, never paths.
+- Exact size and MIME caps enforced before any disk write.
+- SHA-256 recorded in the receipt and re-verified by ``load``/``validate``.
+- ``load`` requires the exact scope key and consumes atomically;
+ ``validate`` checks existence/TTL/scope without consuming.
+- No overwrite: an id collision is retried with a fresh id.
+- ``prune_expired`` removes expired entries; the API server sweeps on demand.
-- **Exact size and MIME caps.** ``store`` rejects bytes above
- ``max_bytes`` and any content type outside the configured allowlist
- before anything touches the disk.
-
-- **SHA-256 provenance.** Every artifact is stored with its ``sha256``,
- returned in the receipt, and re-verified by ``load``/``validate`` so a
- corrupted or tampered file can never be handed to a caller.
-
-- **One-shot, scope-bound downloads.** ``load`` requires the exact scope
- key the artifact was stored under and deletes the artifact atomically on
- success. ``validate`` (used by the broker for "approved artifact id
- only" gating) checks existence, TTL, and scope without consuming.
-
-- **No overwrite.** Ids are random and ``store`` refuses to overwrite an
- existing id (a collision is retried with a fresh id).
-
-- **TTL cleanup.** ``prune_expired`` removes expired entries; the API
- server sweeps on demand. Nothing in the store is allowed to outlive its
- TTL by more than the sweep interval.
-
-Thread-safety: the in-memory index is guarded by a lock; files are written
-to a temp name and atomically renamed into place so a concurrent ``load``
-never observes a partially written artifact.
+Thread-safety: the in-memory index is lock-guarded; files are written to a
+temp name and atomically renamed so a concurrent ``load`` never sees a
+partial artifact.
"""
from __future__ import annotations
+import contextlib
import hashlib
import logging
import os
@@ -60,28 +36,16 @@ import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Optional
-import contextlib
logger = logging.getLogger(__name__)
-#: Default lifetime of a stored artifact, in clock seconds.
DEFAULT_ARTIFACT_TTL_SECONDS = 300.0
-#: Default per-artifact byte cap (10 MiB).
DEFAULT_MAX_ARTIFACT_BYTES = 10 * 1024 * 1024
-#: Default exact MIME allowlist. Unknown or parameterized variants are
-#: rejected; clients must send the canonical registered type.
-DEFAULT_ALLOWED_MIME_TYPES = frozenset(
- {
- "application/json",
- "application/pdf",
- "image/gif",
- "image/jpeg",
- "image/png",
- "image/webp",
- "text/plain",
- }
-)
-#: Length in hex chars of a minted artifact id.
+#: Exact allowlist — parameterized/unknown variants are rejected.
+DEFAULT_ALLOWED_MIME_TYPES = frozenset({
+ "application/json", "application/pdf", "image/gif", "image/jpeg",
+ "image/png", "image/webp", "text/plain",
+})
_ARTIFACT_ID_HEX = 32
_ARTIFACT_ID_RE = re.compile(r"^[0-9a-f]{32}$")
_TEMP_SUFFIX = ".tmp"
@@ -119,10 +83,6 @@ class ArtifactTraversal(ArtifactError):
"""A caller-supplied id is not a valid minted artifact id."""
-class ArtifactOverwrite(ArtifactError):
- """An artifact id already exists and the store refuses to overwrite it."""
-
-
@dataclass(frozen=True)
class ArtifactReceipt:
"""Provenance record returned to the caller of ``store``."""
@@ -158,18 +118,13 @@ class ArtifactReceipt:
def artifact_scope_key(scope: Any) -> str:
"""Derive the stable scope key an artifact is bound to.
- Only server-derived identity fields participate: principal (mandatory)
- plus transport family. ``session_id`` is deliberately EXCLUDED: the HTTP
- artifact routes authenticate by API key and can never resolve a server
- session, while broker dispatch always carries a session-bearing
- ControllerScope — including the session would make the two halves of the
- intended journey (HTTP upload → broker artifact dispatch) hash to
- different keys and never compose. Artifacts are therefore
- principal/transport-family owned; ids are unguessable server-minted
- 32-hex and downloads are one-shot, so cross-session reuse within one
- authenticated principal is by design. Capabilities and optional ids are
- likewise excluded so a reconnect that refreshes the same controller
- keeps its artifacts.
+ Only principal (mandatory) + transport family participate. ``session_id``
+ is deliberately EXCLUDED: HTTP artifact routes authenticate by API key and
+ can't resolve a session, while broker dispatch always carries one — hashing
+ it would make upload and dispatch never compose. Ids are unguessable and
+ downloads one-shot, so cross-session reuse within one principal is by
+ design. Capabilities/optional ids are excluded so a reconnect keeps its
+ artifacts.
"""
principal = ""
family = ""
@@ -179,8 +134,7 @@ def artifact_scope_key(scope: Any) -> str:
except Exception:
pass
if not principal:
- # Fail closed: an artifact can only be minted for an authenticated
- # principal.
+ # Fail closed: only an authenticated principal may mint artifacts.
raise ArtifactError("artifact scope must carry a resolved principal")
material = f"{principal}\x00{family}".encode("utf-8")
return hashlib.sha256(material).hexdigest()
@@ -200,9 +154,7 @@ class ArtifactStore:
"""Thread-safe, TTL-bounded, scope-bound one-shot artifact store."""
def __init__(
- self,
- root: Path,
- *,
+ self, root: Path, *,
ttl_seconds: float = DEFAULT_ARTIFACT_TTL_SECONDS,
max_bytes: int = DEFAULT_MAX_ARTIFACT_BYTES,
allowed_mime_types: frozenset = DEFAULT_ALLOWED_MIME_TYPES,
@@ -216,44 +168,31 @@ class ArtifactStore:
self._clock = clock if clock is not None else time.time
self._lock = threading.RLock()
self._entries: dict[str, _ArtifactEntry] = {}
- # Restart-safe retention: receipts live only in memory, so files
- # left behind by a previous process are unreachable but would
- # otherwise persist forever. Sweep every artifact-id-shaped file
- # (plus stale temps) that has no index entry — at construction the
- # index is empty, so anything on disk is an orphan from a dead
- # process and past its advertised TTL by definition.
+ # Receipts live only in memory, so files left by a previous process
+ # are unreachable orphans past their TTL by definition — sweep them.
self._sweep_orphan_files()
- def _sweep_orphan_files(self) -> int:
- """Delete on-disk artifact files with no live index entry.
+ def _sweep_orphan_files(self) -> None:
+ """Delete on-disk files with no live index entry.
- Called at construction (empty index ⇒ everything on disk is an
- orphan from a previous process). Only files whose names match the
- server-minted 32-hex id shape or the ``*.tmp`` staging suffix are
- touched; anything else in the directory is left alone.
+ Only names matching the minted 32-hex id shape or the ``*.tmp``
+ staging suffix are touched; anything else in the directory is left.
"""
- removed = 0
try:
candidates = list(self._root.iterdir())
except OSError:
- return 0
+ return
with self._lock:
live = set(self._entries)
for path in candidates:
- if not path.is_file():
- continue
name = path.name
- is_temp = name.endswith(".tmp")
- if not is_temp and not _ARTIFACT_ID_RE.fullmatch(name):
+ is_temp = name.endswith(_TEMP_SUFFIX)
+ if not path.is_file() or not (is_temp or _ARTIFACT_ID_RE.fullmatch(name)):
continue
if not is_temp and name in live:
continue
- try:
+ with contextlib.suppress(OSError):
path.unlink(missing_ok=True)
- removed += 1
- except OSError:
- continue
- return removed
# ------------------------------------------------------------------
# Public API
@@ -264,10 +203,6 @@ class ArtifactStore:
"""Controlled artifact root (never exposed to callers by default)."""
return self._root
- @property
- def ttl_seconds(self) -> float:
- return self._ttl_seconds
-
@property
def max_bytes(self) -> int:
return self._max_bytes
@@ -276,30 +211,18 @@ class ArtifactStore:
def allowed_mime_types(self) -> frozenset:
return self._allowed_mime_types
- def store(
- self,
- data: bytes,
- *,
- filename: str,
- content_type: str,
- scope: Any,
- ) -> ArtifactReceipt:
+ def store(self, data: bytes, *, filename: str, content_type: str, scope: Any) -> ArtifactReceipt:
"""Validate and store one artifact, returning its provenance receipt.
Raises :class:`ArtifactTooLarge` / :class:`ArtifactMimeRejected`
- before any disk write; :class:`ArtifactError` if the scope is not a
- fully resolved browser-control scope.
+ before any disk write; :class:`ArtifactError` on an unresolved scope.
"""
size = len(data)
if size > self._max_bytes:
- raise ArtifactTooLarge(
- f"artifact is {size} bytes; cap is {self._max_bytes}"
- )
+ raise ArtifactTooLarge(f"artifact is {size} bytes; cap is {self._max_bytes}")
normalized_type = _normalize_content_type(content_type)
if normalized_type not in self._allowed_mime_types:
- raise ArtifactMimeRejected(
- f"content type {content_type!r} is outside the exact allowlist"
- )
+ raise ArtifactMimeRejected(f"content type {content_type!r} is outside the exact allowlist")
scope_key = artifact_scope_key(scope)
now = self._clock()
@@ -308,27 +231,18 @@ class ArtifactStore:
artifact_id = secrets.token_hex(_ARTIFACT_ID_HEX // 2)
target = self._artifact_path(artifact_id)
with self._lock:
- if artifact_id in self._entries:
- continue
- if target.exists():
+ if artifact_id in self._entries or target.exists():
continue
receipt = ArtifactReceipt(
- artifact_id=artifact_id,
- sha256=_sha256(data),
- size_bytes=size,
- content_type=normalized_type,
- filename=_bounded_filename(filename),
- created_at=now,
- expires_at=now + self._ttl_seconds,
- ttl_seconds=self._ttl_seconds,
- scope_key=scope_key,
+ artifact_id=artifact_id, sha256=_sha256(data), size_bytes=size,
+ content_type=normalized_type, filename=_bounded_filename(filename),
+ created_at=now, expires_at=now + self._ttl_seconds,
+ ttl_seconds=self._ttl_seconds, scope_key=scope_key,
)
- entry = _ArtifactEntry(receipt=receipt, path=target)
- self._entries[artifact_id] = entry
+ self._entries[artifact_id] = _ArtifactEntry(receipt=receipt, path=target)
break
- # Write via temp + atomic rename so readers never observe a
- # partially written artifact.
+ # Temp + atomic rename so readers never observe a partial artifact.
temp = target.with_name(f"{target.name}{_TEMP_SUFFIX}")
try:
with open(temp, "wb") as handle:
@@ -345,21 +259,15 @@ class ArtifactStore:
return receipt
def validate(self, artifact_id: str, *, scope: Any) -> ArtifactReceipt:
- """Return the receipt when the artifact is live for ``scope``.
-
- Used by the broker's "approved artifact id only" gate: checks
- existence, TTL, and scope without consuming the artifact. Raises
- the appropriate :class:`ArtifactError` subclass otherwise.
- """
+ """Return the receipt when the artifact is live for ``scope``
+ (existence, TTL, scope) without consuming it; raises otherwise."""
return self._entry_for(artifact_id, scope=scope).receipt
def load(self, artifact_id: str, *, scope: Any) -> tuple[bytes, ArtifactReceipt]:
"""One-shot download: verify, read, checksum, then consume.
- Returns ``(bytes, receipt)`` and atomically deletes the artifact so
- a second ``load`` raises :class:`ArtifactNotFound`. Raises
- :class:`ArtifactChecksumMismatch` (without consuming) if the file
- on disk does not match the recorded SHA-256.
+ A second ``load`` raises :class:`ArtifactNotFound`. A checksum
+ mismatch raises :class:`ArtifactChecksumMismatch` without consuming.
"""
with self._lock:
entry = self._entry_for(artifact_id, scope=scope)
@@ -372,11 +280,8 @@ class ArtifactStore:
except OSError as exc:
raise ArtifactError(f"artifact read failed: {exc}") from exc
if _sha256(data) != entry.receipt.sha256:
- raise ArtifactChecksumMismatch(
- f"artifact {artifact_id!r} failed SHA-256 validation"
- )
- # Consume atomically: remove the index entry first so a
- # concurrent load fails closed, then delete the file.
+ raise ArtifactChecksumMismatch(f"artifact {artifact_id!r} failed SHA-256 validation")
+ # Drop the index entry first so a concurrent load fails closed.
self._entries.pop(artifact_id, None)
try:
path.unlink(missing_ok=True)
@@ -385,20 +290,11 @@ class ArtifactStore:
return data, entry.receipt
def prune_expired(self, now: Optional[float] = None) -> int:
- """Delete every artifact past its TTL; return the count removed.
-
- Also removes orphaned temp files older than one sweep. Idempotent
- and safe to call on any request or a periodic sweep.
- """
+ """Delete every artifact past its TTL (and stale temp files); return
+ the count removed. Idempotent."""
now = self._clock() if now is None else float(now)
- removed = 0
with self._lock:
- for artifact_id, entry in list(self._entries.items()):
- if entry.receipt.expires_at <= now:
- self._entries.pop(artifact_id, None)
- with contextlib.suppress(OSError):
- entry.path.unlink(missing_ok=True)
- removed += 1
+ removed = self._prune_expired_locked(now)
for temp in self._root.glob(f"*{_TEMP_SUFFIX}"):
try:
if temp.stat().st_mtime <= now - self._ttl_seconds:
@@ -422,9 +318,8 @@ class ArtifactStore:
now = self._clock()
with self._lock:
entry = self._entries.get(artifact_id)
- # Check the target's own expiry BEFORE sweeping other entries so
- # an expired artifact surfaces as ArtifactExpired rather than
- # silently vanishing into the sweep.
+ # Check the target's own expiry BEFORE sweeping so an expired
+ # artifact surfaces as ArtifactExpired, not ArtifactNotFound.
if entry is None:
self._prune_expired_locked(now)
entry = self._entries.get(artifact_id)
@@ -436,17 +331,18 @@ class ArtifactStore:
path.unlink(missing_ok=True)
raise ArtifactExpired(f"artifact {artifact_id!r} expired")
if entry.receipt.scope_key != scope_key:
- raise ArtifactScopeMismatch(
- f"artifact {artifact_id!r} is bound to a different scope"
- )
+ raise ArtifactScopeMismatch(f"artifact {artifact_id!r} is bound to a different scope")
return entry
- def _prune_expired_locked(self, now: float) -> None:
+ def _prune_expired_locked(self, now: float) -> int:
+ removed = 0
for artifact_id, entry in list(self._entries.items()):
if entry.receipt.expires_at <= now:
self._entries.pop(artifact_id, None)
with contextlib.suppress(OSError):
entry.path.unlink(missing_ok=True)
+ removed += 1
+ return removed
def _artifact_path(self, artifact_id: str) -> Path:
"""Resolve a minted id strictly inside the controlled root."""
@@ -484,17 +380,10 @@ def _bounded_filename(value: str, limit: int = 160) -> str:
class ArtifactRateLimiter:
- """Sliding-window per-key limiter for artifact routes.
-
- The API server keys this by the authenticated principal so a single
- key cannot flood the store. Injected clock makes tests deterministic.
- """
+ """Sliding-window per-key limiter; the API server keys it by principal."""
def __init__(
- self,
- *,
- window_seconds: float = 60.0,
- max_requests: int = 30,
+ self, *, window_seconds: float = 60.0, max_requests: int = 30,
clock: Optional[Callable[[], float]] = None,
) -> None:
self._window_seconds = max(1.0, float(window_seconds))
@@ -511,12 +400,11 @@ class ArtifactRateLimiter:
window_start = now - self._window_seconds
with self._lock:
hits = [hit for hit in self._hits.get(key, []) if hit > window_start]
- if len(hits) >= self._max_requests:
- self._hits[key] = hits
- return False
- hits.append(now)
+ allowed = len(hits) < self._max_requests
+ if allowed:
+ hits.append(now)
self._hits[key] = hits
- return True
+ return allowed
def reset(self, key: str) -> None:
"""Drop the recorded hits for ``key`` (tests/diagnostics)."""
diff --git a/gateway/cgroup_cleanup.py b/gateway/cgroup_cleanup.py
index a364294b909..a68a971c37c 100644
--- a/gateway/cgroup_cleanup.py
+++ b/gateway/cgroup_cleanup.py
@@ -1,15 +1,13 @@
"""SIGKILL any process left in this systemd unit's cgroup.
-Runs as ``ExecStopPost=`` so it only fires after the gateway's main process
-has exited. The gateway already reaps its own tool subprocesses on a clean
-shutdown; this is the safety net for long-lived helpers it doesn't track
-(``adb``, platform bridges, etc.) that would otherwise be orphaned in the
-cgroup and block ``Restart=always`` — issue #37454.
+Runs as ``ExecStopPost=`` after the gateway's main process has exited: the
+safety net for long-lived helpers the gateway doesn't track (``adb``, platform
+bridges) that would otherwise be orphaned in the cgroup and block
+``Restart=always``.
-We deliberately iterate ``cgroup.procs`` and send per-PID SIGKILLs instead
-of writing ``1`` to ``cgroup.kill``: the original failure mode in #37454
-was the kernel returning ``EINVAL`` on the cgroup-wide kill, while per-PID
-signal delivery uses a separate code path that still works.
+Per-PID SIGKILLs over ``cgroup.procs`` are used deliberately instead of writing
+``1`` to ``cgroup.kill``: the kernel has returned ``EINVAL`` on the cgroup-wide
+kill while per-PID signal delivery still works.
"""
from __future__ import annotations
@@ -28,24 +26,18 @@ def _own_cgroup_path() -> str | None:
except OSError:
return None
match = re.search(r"^0::(.+)$", text, re.MULTILINE)
- if not match:
- return None
- return match.group(1).strip()
+ return match.group(1).strip() if match else None
def _read_cgroup_pids(cgroup_path: str) -> list[int]:
- procs_file = Path(f"/sys/fs/cgroup{cgroup_path}/cgroup.procs")
try:
- raw = procs_file.read_text(encoding="utf-8")
+ raw = Path(f"/sys/fs/cgroup{cgroup_path}/cgroup.procs").read_text(encoding="utf-8")
except OSError:
return []
pids: list[int] = []
for line in raw.splitlines():
- line = line.strip()
- if not line:
- continue
try:
- pids.append(int(line))
+ pids.append(int(line.strip()))
except ValueError:
continue
return pids
@@ -65,9 +57,7 @@ def reap_cgroup(cgroup_path: str | None = None) -> int:
try:
os.kill(pid, signal.SIGKILL) # windows-footgun: ok — Linux-only (reads /proc, /sys/fs/cgroup; runs from a systemd unit)
killed += 1
- except ProcessLookupError:
- continue
- except PermissionError:
+ except (ProcessLookupError, PermissionError):
continue
return killed
diff --git a/gateway/channel_directory.py b/gateway/channel_directory.py
index d07a7160762..b7558325e15 100644
--- a/gateway/channel_directory.py
+++ b/gateway/channel_directory.py
@@ -1,9 +1,7 @@
-"""
-Channel directory -- cached map of reachable channels/contacts per platform.
+"""Channel directory -- cached map of reachable channels/contacts per platform.
-Built on gateway startup, refreshed periodically (every 5 min), and saved to
-~/.hermes/channel_directory.json. The send_message tool reads this file for
-action="list" and for resolving human-friendly channel names to numeric IDs.
+Built on gateway startup, refreshed every 5 min, saved to ~/.hermes/channel_directory.json.
+send_message reads it for action="list" and to resolve friendly channel names to IDs.
"""
import asyncio
@@ -12,34 +10,32 @@ import logging
import time
from datetime import datetime
from pathlib import Path
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, Iterable, List, Optional, Tuple
from hermes_cli.config import get_hermes_home
from utils import atomic_json_write
logger = logging.getLogger(__name__)
-# Resolved lazily (see ``_directory_path``): a multiplexed gateway serves
-# several profile homes from one process, so an import-time constant would pin
-# every profile's directory to whichever home imported this module first.
-# ``DIRECTORY_PATH`` / ``CHANNEL_ALIASES_PATH`` stay as explicit overrides
-# (tests patch them); ``None`` means "resolve from the current home".
+# Paths resolve lazily: a multiplexed gateway serves several profile homes from
+# one process, so an import-time constant would pin every profile to whichever
+# home imported first. These globals are explicit overrides (tests patch them);
+# ``None`` means "resolve from the current home".
DIRECTORY_PATH: Optional[Path] = None
-# Throttle window for repeated Slack channel-directory refresh failures.
-# The directory rebuilds on a timer, so a persistent workspace error (e.g.
-# missing scope, revoked token) would otherwise re-log the same warning on
-# every refresh. Warn once per (team, error detail) per interval; repeats
-# drop to DEBUG.
+# User-maintained friendly-name overlay, re-applied on every build AND load
+# (hand-edits to the regenerated channel_directory.json don't survive); also
+# lets a chat be pre-named before its first traffic.
+# Format: {"<platform>": {"<chat_id>": "<friendly name>", ...}, ...}
+CHANNEL_ALIASES_PATH: Optional[Path] = None
+
+# Slack refresh failures recur on every timed rebuild (missing scope, revoked
+# token); warn once per (team, error detail) per interval, then DEBUG.
_SLACK_DIRECTORY_WARNING_INTERVAL_SECONDS = 3600
_slack_directory_warning_last: Dict[tuple[str, str], float] = {}
-# User-maintained friendly-name overlay. The directory is fully regenerated
-# from live adapters + session data on a timer, so hand-edits to
-# channel_directory.json don't survive. Aliases declared here are re-applied
-# on every build AND every load, giving durable human-friendly names (and
-# letting you pre-name a chat before it has produced any traffic).
-# Format: {"<platform>": {"<chat_id>": "<friendly name>", ...}, ...}
-CHANNEL_ALIASES_PATH: Optional[Path] = None
+# Platforms whose historical session origins must never become send targets.
+_SKIP_SESSION_DISCOVERY = frozenset({"local", "api_server", "webhook"})
+_SLACK_RAW_ID_PREFIXES = ("C0", "D0", "G0")
def _directory_path() -> Path:
@@ -50,12 +46,12 @@ def _aliases_path() -> Path:
return CHANNEL_ALIASES_PATH or get_hermes_home() / "channel_aliases.json"
-def _load_channel_aliases() -> Dict[str, Dict[str, str]]:
- aliases_path = _aliases_path()
- if not aliases_path.exists():
+def _load_json_dict(path: Path) -> Dict[str, Any]:
+ """Read a JSON object from *path*; {} when missing, unreadable, or not a dict."""
+ if not path.exists():
return {}
try:
- with open(aliases_path, encoding="utf-8") as f:
+ with open(path, encoding="utf-8") as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except Exception:
@@ -63,14 +59,12 @@ def _load_channel_aliases() -> Dict[str, Dict[str, str]]:
def _apply_channel_aliases(platforms: Dict[str, Any]) -> None:
- """Overlay friendly names onto directory entries by chat_id.
+ """Overlay friendly names onto directory entries by chat_id, in place.
- Renames matching entries in place; injects a placeholder entry for an
- aliased id that hasn't been discovered yet (so a freshly-created group is
- addressable by name before its first message). Mutates *platforms*.
+ An aliased id not yet discovered gets a placeholder entry so a
+ freshly-created group is addressable by name before its first message.
"""
- aliases = _load_channel_aliases()
- for plat_name, id_map in aliases.items():
+ for plat_name, id_map in _load_json_dict(_aliases_path()).items():
if not isinstance(id_map, dict):
continue
entries = platforms.setdefault(plat_name, [])
@@ -88,10 +82,8 @@ def _apply_channel_aliases(platforms: Dict[str, Any]) -> None:
matched = True
if not matched:
entries.append({
- "id": chat_id,
- "name": friendly,
- "type": "group" if str(chat_id).endswith("@g.us") else "dm",
- "thread_id": None,
+ "id": chat_id, "name": friendly,
+ "type": "group" if chat_id.endswith("@g.us") else "dm", "thread_id": None,
})
@@ -114,9 +106,7 @@ def _session_entry_id(origin: Dict[str, Any]) -> Optional[str]:
if not chat_id:
return None
thread_id = origin.get("thread_id")
- if thread_id:
- return f"{chat_id}:{thread_id}"
- return str(chat_id)
+ return f"{chat_id}:{thread_id}" if thread_id else str(chat_id)
def _session_entry_name(origin: Dict[str, Any]) -> str:
@@ -124,7 +114,6 @@ def _session_entry_name(origin: Dict[str, Any]) -> str:
thread_id = origin.get("thread_id")
if not thread_id:
return base_name
-
topic_label = origin.get("chat_topic") or f"topic {thread_id}"
return f"{base_name} / {topic_label}"
@@ -136,31 +125,23 @@ def _warn_slack_directory(team_id: str, detail: str) -> None:
last = _slack_directory_warning_last.get(key)
if last is None or now - last >= _SLACK_DIRECTORY_WARNING_INTERVAL_SECONDS:
_slack_directory_warning_last[key] = now
- logger.warning(
- "Channel directory: failed to list Slack channels for team %s: %s",
- team_id,
- detail,
- )
+ logger.warning("Channel directory: failed to list Slack channels for team %s: %s", team_id, detail)
else:
- logger.debug(
- "Channel directory: suppressed repeated Slack channel list failure "
- "for team %s: %s",
- team_id,
- detail,
- )
+ logger.debug("Channel directory: suppressed repeated Slack channel list failure for team %s: %s", team_id, detail)
-# ---------------------------------------------------------------------------
-# Build / refresh
-# ---------------------------------------------------------------------------
+def _report_slack_failure(team_id: str, error_code: Optional[str], detail: str) -> None:
+ """missing_scope is expected (session-history fallback); anything else warns."""
+ if error_code == "missing_scope":
+ logger.debug("Channel directory: Slack team %s lacks channels:read; using session history only", team_id)
+ else:
+ _warn_slack_directory(team_id, detail)
-async def build_channel_directory(adapters: Dict[Any, Any]) -> Dict[str, Any]:
- """
- Build a channel directory from connected platform adapters and session data.
- Returns the directory dict and writes it to the current home's
- ``channel_directory.json``.
- """
+# --- Build / refresh -------------------------------------------------------
+
+async def build_channel_directory(adapters: Dict[Any, Any]) -> Dict[str, Any]:
+ """Build the directory from connected adapters + session data and persist it."""
from gateway.config import Platform
platforms: Dict[str, List[Dict[str, str]]] = {}
@@ -180,46 +161,33 @@ async def build_channel_directory(adapters: Dict[Any, Any]) -> Dict[str, Any]:
except Exception as e:
logger.warning("Channel directory: failed to build %s: %s", platform.value, e)
- # Platforms that don't support direct channel enumeration get session-based
- # discovery automatically, but only for platforms connected in THIS gateway
- # process. Historical session origins for disabled/decommissioned platforms
- # must not be resurrected into the active send-target directory (stale
- # targets make send_message route to platforms that can no longer deliver).
- _SKIP_SESSION_DISCOVERY = frozenset({"local", "api_server", "webhook"})
+ # Platforms without channel enumeration get session-based discovery, but
+ # only when connected in THIS gateway process: origins for disabled or
+ # decommissioned platforms must not resurface as stale send targets.
adapter_platform_names = {getattr(p, "value", str(p)) for p in adapters}
- for plat in Platform:
- plat_name = plat.value
+
+ async def _discover(plat_name: str) -> None:
if (
plat_name in _SKIP_SESSION_DISCOVERY
or plat_name in platforms
or plat_name not in adapter_platform_names
):
- continue
+ return
platforms[plat_name] = await asyncio.to_thread(_build_from_sessions, plat_name)
- # Include plugin-registered platforms (dynamic enum members aren't in
- # Platform.__members__, so the loop above misses them). Same
- # connected-only rule: don't expose stale session targets for plugins
- # that are not loaded.
+ for plat in Platform:
+ await _discover(plat.value)
+ # Plugin platforms are dynamic enum members missing from Platform.__members__.
try:
from gateway.platform_registry import platform_registry
for entry in platform_registry.plugin_entries():
- if (
- entry.name not in _SKIP_SESSION_DISCOVERY
- and entry.name not in platforms
- and entry.name in adapter_platform_names
- ):
- platforms[entry.name] = await asyncio.to_thread(_build_from_sessions, entry.name)
+ await _discover(entry.name)
except Exception:
pass
- # Overlay user-maintained friendly names before persisting.
_apply_channel_aliases(platforms)
- directory = {
- "updated_at": datetime.now().isoformat(),
- "platforms": platforms,
- }
+ directory = {"updated_at": datetime.now().isoformat(), "platforms": platforms}
try:
await asyncio.to_thread(atomic_json_write, _directory_path(), directory)
@@ -230,7 +198,7 @@ async def build_channel_directory(adapters: Dict[Any, Any]) -> Dict[str, Any]:
def _build_discord(adapter) -> List[Dict[str, str]]:
- """Enumerate all text channels and forum channels the Discord bot can see."""
+ """Enumerate text + forum channels the Discord bot can see, plus session DMs."""
channels = []
client = getattr(adapter, "_client", None)
if not client:
@@ -242,26 +210,13 @@ def _build_discord(adapter) -> List[Dict[str, str]]:
return channels
for guild in client.guilds:
- for ch in guild.text_channels:
- channels.append({
- "id": str(ch.id),
- "name": ch.name,
- "guild": guild.name,
- "type": "channel",
- })
- # Forum channels (type 15) — creating a message auto-spawns a thread post.
+ # Forum channels (type 15): creating a message auto-spawns a thread post.
forums = getattr(guild, "forum_channels", None) or []
- for ch in forums:
- channels.append({
- "id": str(ch.id),
- "name": ch.name,
- "guild": guild.name,
- "type": "forum",
- })
- # Also include DM-capable users we've interacted with is not
- # feasible via guild enumeration; those come from sessions.
-
- # Merge any DMs from session history
+ for chs, ch_type in ((guild.text_channels, "channel"), (forums, "forum")):
+ for ch in chs:
+ channels.append({"id": str(ch.id), "name": ch.name, "guild": guild.name, "type": ch_type})
+
+ # DM-capable users aren't reachable via guild enumeration; they come from sessions.
channels.extend(_build_from_sessions("discord"))
return channels
@@ -269,21 +224,17 @@ def _build_discord(adapter) -> List[Dict[str, str]]:
def _slack_api_error_code(error: Exception) -> Optional[str]:
"""Return Slack Web API error code from SlackApiError-like exceptions."""
response = getattr(error, "response", None)
- if isinstance(response, dict):
+ if response is None:
+ return None
+ try:
value = response.get("error")
- return str(value) if value else None
- if response is not None:
- try:
- value = response.get("error")
- return str(value) if value else None
- except Exception:
- pass
- return None
+ except Exception:
+ return None
+ return str(value) if value else None
def _normalize_adapter_channels(raw_channels: Any) -> List[Dict[str, Any]]:
- """Validate and dedupe channel entries returned by an adapter's
- ``list_channels()`` hook (see ``build_channel_directory``)."""
+ """Validate and dedupe entries returned by an adapter's ``list_channels()`` hook."""
channels: List[Dict[str, Any]] = []
seen_ids = set()
if not isinstance(raw_channels, list):
@@ -295,28 +246,26 @@ def _normalize_adapter_channels(raw_channels: Any) -> List[Dict[str, Any]]:
name = str(raw.get("name") or channel_id).strip()
if not channel_id or not name or channel_id in seen_ids:
continue
- entry: Dict[str, Any] = {
- "id": channel_id,
- "name": name,
- "type": str(raw.get("type") or "dm"),
- }
- if raw.get("thread_id"):
- entry["thread_id"] = str(raw.get("thread_id"))
- if raw.get("guild"):
- entry["guild"] = str(raw.get("guild"))
+ entry: Dict[str, Any] = {"id": channel_id, "name": name, "type": str(raw.get("type") or "dm")}
+ for key in ("thread_id", "guild"):
+ if raw.get(key):
+ entry[key] = str(raw.get(key))
channels.append(entry)
seen_ids.add(channel_id)
return channels
+def _slack_base_id(entry_id: str) -> str:
+ """Thread-qualified IDs (``C0xxx:ts``) are internal routing keys, not Slack API IDs."""
+ return entry_id.split(":", 1)[0]
+
+
async def _build_slack(adapter) -> List[Dict[str, Any]]:
"""List Slack channels the bot has joined across all workspaces.
- Uses ``users.conversations`` against each workspace's web client. Pulls
- public + private channels the bot is a member of, then merges in DMs
- discovered from session history (IMs aren't useful to enumerate
- proactively). If the Slack app lacks channels:read, fall back to session
- history quietly instead of logging a recurring warning every refresh.
+ ``users.conversations`` per workspace client (public + private member channels),
+ then merge DMs from session history. Missing channels:read falls back to
+ session history quietly rather than warning on every refresh.
"""
team_clients = getattr(adapter, "_team_clients", None) or {}
if not team_clients:
@@ -337,14 +286,7 @@ async def _build_slack(adapter) -> List[Dict[str, Any]]:
)
if not response.get("ok"):
error_code = response.get("error", "unknown")
- if error_code == "missing_scope":
- logger.debug(
- "Channel directory: Slack team %s lacks channels:read; using session history only",
- team_id,
- )
- else:
- detail = f"users.conversations not ok: {error_code}"
- _warn_slack_directory(team_id, detail)
+ _report_slack_failure(team_id, error_code, f"users.conversations not ok: {error_code}")
break
for ch in response.get("channels", []):
cid = ch.get("id")
@@ -352,55 +294,36 @@ async def _build_slack(adapter) -> List[Dict[str, Any]]:
if not cid or not name or cid in seen_ids:
continue
seen_ids.add(cid)
- channels.append({
- "id": cid,
- "name": name,
- "type": "private" if ch.get("is_private") else "channel",
- })
+ channels.append({"id": cid, "name": name, "type": "private" if ch.get("is_private") else "channel"})
cursor = (response.get("response_metadata") or {}).get("next_cursor")
if not cursor:
break
except Exception as e:
- if _slack_api_error_code(e) == "missing_scope":
- logger.debug(
- "Channel directory: Slack team %s lacks channels:read; using session history only",
- team_id,
- )
- else:
- _warn_slack_directory(team_id, str(e))
+ _report_slack_failure(team_id, _slack_api_error_code(e), str(e))
continue
- # Merge in DM/group entries discovered from session history.
- # Thread-qualified IDs are internal routing keys, not Slack API IDs.
- def slack_lookup_id(entry_id: str) -> str:
- return entry_id.split(":", 1)[0]
-
- # Build a lookup from API-discovered channels so we can enrich session entries.
+ # Merge session-history DM/group entries, naming raw-ID entries from the
+ # API-discovered channels where the base conversation ID is known.
api_name_lookup = {ch["id"]: ch["name"] for ch in channels}
-
for entry in await asyncio.to_thread(_build_from_sessions, "slack"):
eid = entry.get("id")
- if not isinstance(eid, str):
+ if not isinstance(eid, str) or eid in seen_ids:
continue
- if eid not in seen_ids:
- # If the entry name is still a raw Slack ID (e.g. C0xxx / D0xxx),
- # try to resolve it from the API lookup using the base conversation ID.
- if entry.get("name", "").startswith(("C0", "D0", "G0")):
- base_id = slack_lookup_id(eid)
- if base_id in api_name_lookup:
- entry["name"] = api_name_lookup[base_id]
- channels.append(entry)
- seen_ids.add(eid)
-
- # Resolve remaining raw-ID entries (DMs, private channels not in bot scope)
- # by calling conversations.info + users.info once per base conversation,
- # with all base-ID lookups running concurrently.
- unresolved = [ch for ch in channels if ch.get("name", "").startswith(("C0", "D0", "G0"))]
- if unresolved and team_clients:
+ if entry.get("name", "").startswith(_SLACK_RAW_ID_PREFIXES):
+ base_id = _slack_base_id(eid)
+ if base_id in api_name_lookup:
+ entry["name"] = api_name_lookup[base_id]
+ channels.append(entry)
+ seen_ids.add(eid)
+
+ # Resolve remaining raw-ID entries (DMs, channels outside bot scope) via
+ # conversations.info + users.info once per base conversation, concurrently.
+ unresolved = [ch for ch in channels if ch.get("name", "").startswith(_SLACK_RAW_ID_PREFIXES)]
+ if unresolved:
client = next(iter(team_clients.values()))
- unresolved_by_base = {}
+ unresolved_by_base: Dict[str, list] = {}
for entry in unresolved:
- unresolved_by_base.setdefault(slack_lookup_id(entry["id"]), []).append(entry)
+ unresolved_by_base.setdefault(_slack_base_id(entry["id"]), []).append(entry)
async def _resolve_base(base_id: str, entries: list) -> None:
try:
@@ -416,11 +339,7 @@ async def _build_slack(adapter) -> List[Dict[str, Any]]:
user_resp = await client.users_info(user=peer_user)
if user_resp.get("ok"):
u = user_resp["user"]
- resolved_name = (
- u.get("profile", {}).get("display_name")
- or u.get("real_name")
- or u.get("name")
- )
+ resolved_name = u.get("profile", {}).get("display_name") or u.get("real_name") or u.get("name")
resolved_type = "dm"
else:
resolved_name = ch_info.get("name") or ch_info.get("name_normalized")
@@ -432,9 +351,7 @@ async def _build_slack(adapter) -> List[Dict[str, Any]]:
except Exception as e:
logger.debug("Channel directory: failed to resolve %s: %s", base_id, e)
- await asyncio.gather(
- *[_resolve_base(bid, ents) for bid, ents in unresolved_by_base.items()]
- )
+ await asyncio.gather(*[_resolve_base(bid, ents) for bid, ents in unresolved_by_base.items()])
return channels
@@ -442,18 +359,32 @@ async def _build_slack(adapter) -> List[Dict[str, Any]]:
def _build_from_sessions(platform_name: str) -> List[Dict[str, str]]:
"""Pull known channels/contacts from gateway session origin data.
- state.db is the primary source (#9006): gateway session rows persist
- origin_json. Falls back to sessions.json for pre-migration databases.
+ state.db is the primary source; sessions.json is the fallback for
+ pre-migration databases.
"""
- entries = _build_from_sessions_db(platform_name)
- if entries:
- return entries
- return _build_from_sessions_json(platform_name)
+ return _build_from_sessions_db(platform_name) or _build_from_sessions_json(platform_name)
+
+
+def _extend_from_origins(entries: List[Dict[str, Any]], origins: Iterable[Tuple[Dict[str, Any], Any]]) -> None:
+ """Append deduped directory entries for (origin, chat_type) pairs to *entries*.
+
+ Appends incrementally so a mid-iteration failure keeps the entries read so far.
+ """
+ seen_ids = set()
+ for origin, chat_type in origins:
+ entry_id = _session_entry_id(origin)
+ if not entry_id or entry_id in seen_ids:
+ continue
+ seen_ids.add(entry_id)
+ entries.append({
+ "id": entry_id, "name": _session_entry_name(origin),
+ "type": chat_type, "thread_id": origin.get("thread_id"),
+ })
def _build_from_sessions_db(platform_name: str) -> List[Dict[str, str]]:
"""Pull channels/contacts from state.db gateway session rows."""
- entries: List[Dict[str, str]] = []
+ entries: List[Dict[str, Any]] = []
try:
from hermes_state import get_shared_session_db, release_or_close
db = get_shared_session_db()
@@ -465,37 +396,19 @@ def _build_from_sessions_db(platform_name: str) -> List[Dict[str, str]]:
finally:
release_or_close(db)
- seen_ids = set()
- for row in rows:
- origin: Dict[str, Any] = {}
+ def _origin(row) -> Dict[str, Any]:
if row.get("origin_json"):
try:
parsed = json.loads(row["origin_json"])
- if isinstance(parsed, dict):
- origin = parsed
+ if isinstance(parsed, dict) and parsed:
+ return parsed
except (TypeError, ValueError):
pass
- if not origin:
- origin = {
- "chat_id": row.get("chat_id"),
- "thread_id": row.get("thread_id"),
- "chat_name": row.get("display_name"),
- }
- entry_id = _session_entry_id(origin)
- if not entry_id or entry_id in seen_ids:
- continue
- seen_ids.add(entry_id)
- entries.append({
- "id": entry_id,
- "name": _session_entry_name(origin),
- "type": row.get("chat_type") or "dm",
- "thread_id": origin.get("thread_id"),
- })
+ return {"chat_id": row.get("chat_id"), "thread_id": row.get("thread_id"), "chat_name": row.get("display_name")}
+
+ _extend_from_origins(entries, ((_origin(row), row.get("chat_type") or "dm") for row in rows))
except Exception as e:
- logger.debug(
- "Channel directory: state.db session read failed for %s: %s",
- platform_name, e,
- )
+ logger.debug("Channel directory: state.db session read failed for %s: %s", platform_name, e)
return entries
@@ -504,87 +417,67 @@ def _build_from_sessions_json(platform_name: str) -> List[Dict[str, str]]:
sessions_path = get_hermes_home() / "sessions" / "sessions.json"
if not sessions_path.exists():
return []
-
- entries = []
+ entries: List[Dict[str, Any]] = []
try:
with open(sessions_path, encoding="utf-8") as f:
data = json.load(f)
- seen_ids = set()
- for _key, session in data.items():
- # Skip documentation/metadata sentinels (keys starting with "_",
- # e.g. the gateway's "_README" note) — not session entries.
- if str(_key).startswith("_") or not isinstance(session, dict):
- continue
- origin = session.get("origin") or {}
- if origin.get("platform") != platform_name:
- continue
- entry_id = _session_entry_id(origin)
- if not entry_id or entry_id in seen_ids:
- continue
- seen_ids.add(entry_id)
- entries.append({
- "id": entry_id,
- "name": _session_entry_name(origin),
- "type": session.get("chat_type", "dm"),
- "thread_id": origin.get("thread_id"),
- })
+ def _origins():
+ for _key, session in data.items():
+ # Keys starting with "_" (e.g. the gateway's "_README") are
+ # metadata sentinels, not sessions.
+ if str(_key).startswith("_") or not isinstance(session, dict):
+ continue
+ origin = session.get("origin") or {}
+ if origin.get("platform") == platform_name:
+ yield origin, session.get("chat_type", "dm")
+
+ _extend_from_origins(entries, _origins())
except Exception as e:
logger.debug("Channel directory: failed to read sessions for %s: %s", platform_name, e)
-
return entries
-# ---------------------------------------------------------------------------
-# Read / resolve
-# ---------------------------------------------------------------------------
+# --- Read / resolve --------------------------------------------------------
def load_directory() -> Dict[str, Any]:
- """Load the cached channel directory from disk."""
+ """Load the cached directory from disk, with aliases re-applied on read."""
directory_path = _directory_path()
- if not directory_path.exists():
- base = {"updated_at": None, "platforms": {}}
- _apply_channel_aliases(base["platforms"])
- return base
- try:
- with open(directory_path, encoding="utf-8") as f:
- data = json.load(f)
- # Re-apply aliases on read so friendly names take effect immediately,
- # even between timed rebuilds and for brand-new alias entries.
- _apply_channel_aliases(data.setdefault("platforms", {}))
- return data
- except Exception:
- base = {"updated_at": None, "platforms": {}}
- _apply_channel_aliases(base["platforms"])
- return base
+ if directory_path.exists():
+ try:
+ with open(directory_path, encoding="utf-8") as f:
+ data = json.load(f)
+ # Aliases apply on read too, so new names take effect between timed rebuilds.
+ _apply_channel_aliases(data.setdefault("platforms", {}))
+ return data
+ except Exception:
+ pass
+ base = {"updated_at": None, "platforms": {}}
+ _apply_channel_aliases(base["platforms"])
+ return base
def lookup_channel_type(platform_name: str, chat_id: str) -> Optional[str]:
"""Return the channel ``type`` string (e.g. ``"channel"``, ``"forum"``) for *chat_id*, or *None* if unknown."""
- directory = load_directory()
- for ch in directory.get("platforms", {}).get(platform_name, []):
+ for ch in load_directory().get("platforms", {}).get(platform_name, []):
if ch.get("id") == chat_id:
return ch.get("type")
return None
def resolve_channel_name(platform_name: str, name: str) -> Optional[str]:
- """
- Resolve a human-friendly channel name to a numeric ID.
+ """Resolve a human-friendly channel name to a numeric ID (case-insensitive, first match wins).
- Matching strategy (case-insensitive, first match wins):
- - Discord: "bot-home", "#bot-home", "GuildName/bot-home"
- - Telegram: display name or group name
- - Slack: "engineering", "#engineering"
+ Accepts e.g. Discord "bot-home" / "#bot-home" / "GuildName/bot-home", Telegram
+ display or group names, Slack "engineering" / "#engineering".
"""
- directory = load_directory()
- channels = directory.get("platforms", {}).get(platform_name, [])
+ channels = load_directory().get("platforms", {}).get(platform_name, [])
if not channels:
return None
- # 0. Exact ID match — case-sensitive, no normalization. Lets callers pass
- # raw platform IDs (e.g. Slack "C0B0QV5434G") even when the format guard
- # in _parse_target_ref hasn't recognized them as explicit.
+ # 0. Exact ID match — case-sensitive, no normalization, so raw platform IDs
+ # (e.g. Slack "C0B0QV5434G") work even when _parse_target_ref's format
+ # guard didn't recognize them as explicit.
raw = name.strip()
for ch in channels:
if ch.get("id") == raw:
@@ -618,15 +511,12 @@ def resolve_channel_name(platform_name: str, name: str) -> Optional[str]:
def format_directory_for_display(platforms: Optional[Dict[str, Any]] = None) -> str:
"""Format the channel directory as a human-readable list for the model.
- ``platforms`` overrides the on-disk directory when provided (used by
- ``hermes send --list`` to merge in configured-but-undiscovered
- platforms). Platforms present with an empty channel list are rendered
- with a "(no channels discovered yet)" hint instead of being hidden —
- a configured platform is a valid send target even before discovery.
+ ``platforms`` overrides the on-disk directory (``hermes send --list`` merges in
+ configured-but-undiscovered platforms). An empty channel list renders a
+ "(no channels discovered yet)" hint: the platform is still a valid send target.
"""
if platforms is None:
- directory = load_directory()
- platforms = directory.get("platforms", {})
+ platforms = load_directory().get("platforms", {})
if not platforms:
return "No messaging platforms connected or no channels discovered yet."
@@ -640,34 +530,27 @@ def format_directory_for_display(platforms: Optional[Dict[str, Any]] = None) ->
f" (no channels discovered yet — send directly with "
f"{plat_name}:<chat_id>, or bare '{plat_name}' for the home channel)"
)
- lines.append("")
- continue
-
- # Group Discord channels by guild
- if plat_name == "discord":
+ elif plat_name == "discord":
+ # Group Discord channels by guild; DMs last.
guilds: Dict[str, List] = {}
dms: List = []
for ch in channels:
guild = ch.get("guild")
- if guild:
- guilds.setdefault(guild, []).append(ch)
- else:
- dms.append(ch)
+ (guilds.setdefault(guild, []) if guild else dms).append(ch)
for guild_name, guild_channels in sorted(guilds.items()):
lines.append(f"Discord ({guild_name}):")
- for ch in sorted(guild_channels, key=lambda c: c["name"]):
- lines.append(f" discord:{_channel_target_name(plat_name, ch)}")
+ lines.extend(
+ f" discord:{_channel_target_name(plat_name, ch)}"
+ for ch in sorted(guild_channels, key=lambda c: c["name"])
+ )
if dms:
lines.append("Discord (DMs):")
- for ch in dms:
- lines.append(f" discord:{_channel_target_name(plat_name, ch)}")
- lines.append("")
+ lines.extend(f" discord:{_channel_target_name(plat_name, ch)}" for ch in dms)
else:
lines.append(f"{plat_name.title()}:")
- for ch in channels:
- lines.append(f" {plat_name}:{_channel_target_name(plat_name, ch)}")
- lines.append("")
+ lines.extend(f" {plat_name}:{_channel_target_name(plat_name, ch)}" for ch in channels)
+ lines.append("")
lines.append('Use these as the "target" parameter when sending.')
lines.append('Bare platform name (e.g. "telegram") sends to home channel.')
diff --git a/gateway/control_socket.py b/gateway/control_socket.py
index 50c516f3937..668ac226089 100644
--- a/gateway/control_socket.py
+++ b/gateway/control_socket.py
@@ -1,46 +1,18 @@
-"""
-Gateway control socket — the gateway-owned local coordination surface.
-
-Migration step 1 of the #92091 design: every other process on the machine
-(the updater, `hermes serve`/dashboard, the Desktop app) currently discovers
-gateway identity/state by scanning the process table and string-matching argv
-or by reading ``gateway_state.json`` (which can outlive its writer). This
-module gives the gateway an OWNED contract instead: a local-only socket the
-gateway process creates at startup and removes on clean shutdown, answering
-versioned JSON verbs. A connectable socket with a well-formed ``identify``
-answer IS liveness — no PID-reuse heuristics.
-
-v1 verbs (observation only — no behavior change for the gateway):
-
-- ``identify`` → pid, profile label, hermes_home, code_sha/code_version
- (the #91283 stamps, now queryable live), supervisor kind, served profiles,
- start_time, protocol version.
-- ``status`` → the live runtime-status payload (what ``gateway_state.json``
- holds today, but answered by the process itself, race-free).
-
-Transport:
-
-- POSIX: Unix domain socket at ``$HERMES_HOME/gateway.sock``. When the home
- path is too long for ``sun_path`` (~104 bytes on macOS/BSD), the socket is
- bound in the system temp dir and a pointer file
- ``$HERMES_HOME/gateway.sock.path`` records the real location; clients
- follow the pointer transparently.
-- Windows: named pipe ``\\\\.\\pipe\\hermes-gateway-<home-hash>`` served via
- the proactor event loop. Same trust model (per-user namespace).
-
-Never a TCP port. Filesystem/pipe ACLs are the auth boundary — the same
-trust model as ``gateway_state.json`` today.
-
-v1 wire contract: ONE request per connection — a single JSON line in, a
-single JSON line out, then the server closes. Clients must not rely on
-keep-alive or pipelining. Verb handlers may touch disk (they run in an
-executor server-side) but must stay fast; the client budget is small.
-
-Consumers (``hermes update --plan`` inventory, the post-update fleet version
-matrix) PREFER the socket when it answers and fall back to the existing
-state-file/scan layer when it doesn't — old gateways mid-upgrade and crashed
-processes keep working exactly as before. The scan layer is demoted, not
-deleted.
+"""Gateway control socket — the gateway-owned local coordination surface.
+
+Instead of process-table scans or ``gateway_state.json`` (which can outlive
+its writer), the gateway serves a local-only socket answering versioned JSON
+verbs (``identify``, ``status``). A connectable socket with a well-formed
+``identify`` answer IS liveness — no PID-reuse heuristics.
+
+Transport — never a TCP port; filesystem/pipe ACLs are the auth boundary.
+POSIX: ``$HERMES_HOME/gateway.sock``, or a temp-dir socket plus a
+``gateway.sock.path`` pointer file when the home path exceeds ``sun_path``.
+Windows: named pipe ``\\\\.\\pipe\\hermes-gateway-<home-hash>``.
+
+Wire contract: ONE request per connection — one JSON line in, one out, then
+the server closes (no keep-alive/pipelining). Consumers PREFER the socket and
+fall back to the state-file/scan layer when it doesn't answer.
"""
from __future__ import annotations
@@ -66,12 +38,10 @@ _SOCKET_FILENAME = "gateway.sock"
_POINTER_FILENAME = "gateway.sock.path"
_IS_WINDOWS = sys.platform == "win32"
-# Practical sun_path limit: 104 on macOS/BSD, 108 on Linux. Stay under the
-# smaller bound with margin for the NUL terminator.
+# sun_path limit is 104 on macOS/BSD, 108 on Linux; leave margin for the NUL.
_MAX_UNIX_PATH = 100
-# Requests and responses are single JSON lines. Bound them so a misbehaving
-# peer can't balloon gateway memory.
+# Single-line JSON in/out; bounded so a misbehaving peer can't balloon memory.
_MAX_REQUEST_BYTES = 64 * 1024
_MAX_RESPONSE_BYTES = 512 * 1024
@@ -92,20 +62,15 @@ def windows_pipe_name(home: Path) -> str:
return rf"\\.\pipe\hermes-gateway-{_home_hash(home)}"
-def _pointer_path(home: Path) -> Path:
- return Path(home) / _POINTER_FILENAME
-
-
-def _default_socket_path(home: Path) -> Path:
- return Path(home) / _SOCKET_FILENAME
+def _fits_sun_path(path: Path) -> bool:
+ return len(str(path).encode("utf-8")) <= _MAX_UNIX_PATH
def _fallback_socket_path(home: Path) -> Path:
"""Short temp-dir path for homes whose direct socket path exceeds sun_path.
- Prefers ``tempfile.gettempdir()``; when even that yields a too-long path
- (deep $TMPDIR), falls back to ``/tmp`` on POSIX. If nothing fits, the
- tempdir candidate is returned anyway — bind will fail non-fatally and
+ Tries ``tempfile.gettempdir()`` then ``/tmp`` (POSIX). If nothing fits the
+ tempdir candidate is returned anyway — bind fails non-fatally and
consumers use the scan layer.
"""
name = f"hermes-gw-{_home_hash(home)}.sock"
@@ -113,37 +78,31 @@ def _fallback_socket_path(home: Path) -> Path:
if not _IS_WINDOWS:
candidates.append(Path("/tmp") / name)
for candidate in candidates:
- if len(str(candidate).encode("utf-8")) <= _MAX_UNIX_PATH:
+ if _fits_sun_path(candidate):
return candidate
return candidates[0]
def resolve_server_socket_path(home: Path) -> tuple[Path, Optional[Path]]:
- """Where the server should bind, plus the pointer file to write (or None).
-
- Returns ``(bind_path, pointer_file)``. ``pointer_file`` is non-None only
- when the direct in-home path is too long and the temp-dir fallback is in
- use — the server must then persist the real location for clients.
- """
- direct = _default_socket_path(home)
- if len(str(direct).encode("utf-8")) <= _MAX_UNIX_PATH:
+ """Return ``(bind_path, pointer_file)``; pointer_file is non-None only
+ when the temp-dir fallback is in use and the server must record it."""
+ direct = Path(home) / _SOCKET_FILENAME
+ if _fits_sun_path(direct):
return direct, None
- return _fallback_socket_path(home), _pointer_path(home)
+ return _fallback_socket_path(home), Path(home) / _POINTER_FILENAME
def resolve_client_socket_path(home: Path) -> Optional[Path]:
"""Where a client should connect for ``home``, or None when nothing exists."""
- direct = _default_socket_path(home)
+ direct = Path(home) / _SOCKET_FILENAME
if direct.exists():
return direct
- pointer = _pointer_path(home)
+ pointer = Path(home) / _POINTER_FILENAME
try:
if pointer.is_file():
target = pointer.read_text(encoding="utf-8").strip()
- if target:
- candidate = Path(target)
- if candidate.exists():
- return candidate
+ if target and Path(target).exists():
+ return Path(target)
except OSError:
pass
return None
@@ -154,12 +113,8 @@ def resolve_client_socket_path(home: Path) -> Optional[Path]:
# ---------------------------------------------------------------------------
def _detect_supervisor() -> str:
- """Best-effort supervisor kind for THIS process, from its own environment.
-
- Unlike the outside-in `_detect_supervisor_for_pid` scan, this answers from
- the process's own launch context — which is exactly the provenance the
- #92091 design wants declared rather than inferred.
- """
+ """Supervisor kind for THIS process, declared from its own launch env
+ (not inferred outside-in like ``_detect_supervisor_for_pid``)."""
env = os.environ
if env.get("INVOCATION_ID"):
return "systemd"
@@ -187,19 +142,14 @@ def build_identify_payload() -> dict[str, Any]:
record = _build_pid_record()
payload: dict[str, Any] = {
"protocol": CONTROL_PROTOCOL_VERSION,
- "kind": record.get("kind"),
- "pid": record.get("pid"),
- "start_time": record.get("start_time"),
- "hermes_home": record.get("hermes_home"),
+ **{k: record.get(k) for k in ("kind", "pid", "start_time", "hermes_home")},
"profile": _profile_label_for_home(record.get("hermes_home") or ""),
"supervisor": _detect_supervisor(),
}
payload.update(_get_code_identity_fields())
- # served_profiles (multiplex mode) is stamped into the runtime status by
- # the runner; surface it when present so fleet consumers see coverage.
+ # served_profiles (multiplex mode) is stamped into runtime status by the runner.
try:
- runtime = read_runtime_status() or {}
- served = runtime.get("served_profiles")
+ served = (read_runtime_status() or {}).get("served_profiles")
if isinstance(served, list) and served:
payload["served_profiles"] = served
except Exception:
@@ -211,8 +161,7 @@ def build_status_payload() -> dict[str, Any]:
"""Default ``status`` answer — current runtime status, answered live."""
from gateway.status import read_runtime_status
- payload = read_runtime_status() or {}
- payload = dict(payload)
+ payload = dict(read_runtime_status() or {})
payload["protocol"] = CONTROL_PROTOCOL_VERSION
payload["answered_at"] = time.time()
payload["answering_pid"] = os.getpid()
@@ -226,11 +175,9 @@ def build_status_payload() -> dict[str, Any]:
class GatewayControlServer:
"""Gateway-owned control socket server (identify/status, v1).
- Lifecycle is owned by the gateway process: ``start()`` after the PID-file
- claim (the point where this process becomes the authoritative gateway for
- its HERMES_HOME), ``stop()`` on shutdown. All failures are non-fatal —
- the gateway never refuses to serve messaging because its control socket
- couldn't bind; consumers simply fall back to the scan layer.
+ ``start()`` after the PID-file claim, ``stop()`` on shutdown. All failures
+ are non-fatal — the gateway never refuses to serve messaging because its
+ control socket couldn't bind; consumers fall back to the scan layer.
"""
def __init__(
@@ -269,21 +216,16 @@ class GatewayControlServer:
async def _start_posix(self) -> bool:
bind_path, pointer_file = resolve_server_socket_path(self._home)
- # Clear a stale socket left by a crashed predecessor. We only get
- # here after winning the PID-file O_EXCL race, so any existing file
- # is either stale or a plain collision — never a live sibling for
- # this HERMES_HOME.
+ # We only get here after winning the PID-file O_EXCL race, so any
+ # existing file is stale or a collision — never a live sibling.
with contextlib.suppress(OSError):
if bind_path.exists():
bind_path.unlink()
- # Bind under a restrictive umask so the socket is never
- # world-connectable, even for the instant before an explicit chmod
- # could run. Restore the process umask immediately after.
+ # Restrictive umask so the socket is never world-connectable, even
+ # for the instant before chmod.
old_umask = os.umask(0o177)
try:
- self._server = await asyncio.start_unix_server(
- self._handle_connection, path=str(bind_path)
- )
+ self._server = await asyncio.start_unix_server(self._handle_connection, path=str(bind_path))
finally:
os.umask(old_umask)
with contextlib.suppress(OSError):
@@ -301,16 +243,11 @@ class GatewayControlServer:
if start_serving_pipe is None:
logger.debug(
"Event loop %s has no start_serving_pipe — control socket "
- "disabled (selector loop on Windows).",
- type(loop).__name__,
+ "disabled (selector loop on Windows).", type(loop).__name__,
)
return False
pipe_name = windows_pipe_name(self._home)
-
- def _factory():
- return _PipeControlProtocol(self)
-
- servers = await start_serving_pipe(_factory, pipe_name)
+ servers = await start_serving_pipe(lambda: _PipeControlProtocol(self), pipe_name)
self._pipe_server = servers[0] if servers else None
logger.info("Gateway control pipe listening at %s", pipe_name)
return self._pipe_server is not None
@@ -330,20 +267,17 @@ class GatewayControlServer:
def cleanup_files(self) -> None:
"""Best-effort removal of socket + pointer files (atexit-safe)."""
- if self._bind_path is not None:
- with contextlib.suppress(OSError):
- self._bind_path.unlink(missing_ok=True)
- if self._pointer_file is not None:
- with contextlib.suppress(OSError):
- self._pointer_file.unlink(missing_ok=True)
+ for path in (self._bind_path, self._pointer_file):
+ if path is not None:
+ with contextlib.suppress(OSError):
+ path.unlink(missing_ok=True)
# -- request handling ----------------------------------------------------
def handle_request_line(self, raw: bytes) -> bytes:
- """Process one JSON request line, return one JSON response line.
+ """One JSON request line -> one JSON response line. Never raises.
Shared by the POSIX stream handler and the Windows pipe protocol.
- Never raises.
"""
request_id: Any = None
try:
@@ -355,21 +289,15 @@ class GatewayControlServer:
handler = self._handlers.get(verb) if isinstance(verb, str) else None
if handler is None:
response: dict[str, Any] = {
- "ok": False,
- "error": f"unknown verb: {verb!r}",
+ "ok": False, "error": f"unknown verb: {verb!r}",
"protocol": CONTROL_PROTOCOL_VERSION,
"supported_verbs": sorted(self._handlers),
}
else:
- response = {
- "ok": True,
- "protocol": CONTROL_PROTOCOL_VERSION,
- "result": handler(),
- }
+ response = {"ok": True, "protocol": CONTROL_PROTOCOL_VERSION, "result": handler()}
except Exception as exc:
response = {
- "ok": False,
- "error": f"{type(exc).__name__}: {exc}",
+ "ok": False, "error": f"{type(exc).__name__}: {exc}",
"protocol": CONTROL_PROTOCOL_VERSION,
}
if request_id is not None:
@@ -382,22 +310,15 @@ class GatewayControlServer:
encoded = b'{"ok": false, "error": "response too large"}'
return encoded + b"\n"
- async def _handle_connection(
- self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
- ) -> None:
+ async def _handle_connection(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
try:
- raw = await asyncio.wait_for(
- reader.readline(), timeout=_DEFAULT_CLIENT_TIMEOUT
- )
+ raw = await asyncio.wait_for(reader.readline(), timeout=_DEFAULT_CLIENT_TIMEOUT)
if not raw or len(raw) > _MAX_REQUEST_BYTES:
return
- # Handlers read state files from disk; keep that off the
- # gateway's event loop (the same loop drives every platform
- # adapter), so a fast-polling consumer can't stall heartbeats.
+ # Handlers read disk; keep that off the loop that drives every
+ # platform adapter so a fast-polling consumer can't stall heartbeats.
loop = asyncio.get_running_loop()
- response = await loop.run_in_executor(
- None, self.handle_request_line, raw.rstrip(b"\n")
- )
+ response = await loop.run_in_executor(None, self.handle_request_line, raw.rstrip(b"\n"))
writer.write(response)
await writer.drain()
except (asyncio.TimeoutError, ConnectionError, OSError):
@@ -438,28 +359,18 @@ class _PipeControlProtocol(asyncio.Protocol):
# ---------------------------------------------------------------------------
def query_gateway_control(
- home: Path,
- verb: str,
- *,
- timeout: float = _DEFAULT_CLIENT_TIMEOUT,
+ home: Path, verb: str, *, timeout: float = _DEFAULT_CLIENT_TIMEOUT
) -> Optional[dict[str, Any]]:
"""Ask the gateway serving ``home`` a control verb; None when unanswered.
- Returns the verb's ``result`` payload on success. Any failure — no
- socket, stale socket nobody accepts on, timeout, malformed answer,
- ``ok: false`` — returns None so callers fall back to the scan layer.
- Never raises.
+ Returns the verb's ``result`` payload. Any failure (no/stale socket,
+ timeout, malformed answer, ``ok: false``) returns None so callers fall
+ back to the scan layer. Never raises.
"""
- request = (
- json.dumps({"verb": verb, "id": 1, "protocol": CONTROL_PROTOCOL_VERSION})
- .encode("utf-8")
- + b"\n"
- )
+ request = json.dumps({"verb": verb, "id": 1, "protocol": CONTROL_PROTOCOL_VERSION}).encode("utf-8") + b"\n"
+ query = _query_windows_pipe if _IS_WINDOWS else _query_unix_socket
try:
- if _IS_WINDOWS:
- raw = _query_windows_pipe(Path(home), request, timeout)
- else:
- raw = _query_unix_socket(Path(home), request, timeout)
+ raw = query(Path(home), request, timeout)
except Exception:
return None
if not raw:
@@ -474,6 +385,22 @@ def query_gateway_control(
return result if isinstance(result, dict) else None
+def _read_response_line(read: Callable[[], bytes], deadline: float) -> Optional[bytes]:
+ """Read chunks until a newline, EOF, deadline, or the size cap (-> None)."""
+ chunks: list[bytes] = []
+ while time.monotonic() < deadline:
+ chunk = read()
+ if not chunk:
+ break
+ chunks.append(chunk)
+ if b"\n" in chunk:
+ break
+ if sum(len(c) for c in chunks) > _MAX_RESPONSE_BYTES:
+ return None
+ line, _, _ = b"".join(chunks).partition(b"\n")
+ return line or None
+
+
def _query_unix_socket(home: Path, request: bytes, timeout: float) -> Optional[bytes]:
path = resolve_client_socket_path(home)
if path is None:
@@ -485,28 +412,13 @@ def _query_unix_socket(home: Path, request: bytes, timeout: float) -> Optional[b
except (ConnectionRefusedError, FileNotFoundError, OSError):
return None
sock.sendall(request)
- chunks: list[bytes] = []
- deadline = time.monotonic() + timeout
- while time.monotonic() < deadline:
- try:
- chunk = sock.recv(65536)
- except socket.timeout:
- return None
- if not chunk:
- break
- chunks.append(chunk)
- if b"\n" in chunk:
- break
- if sum(len(c) for c in chunks) > _MAX_RESPONSE_BYTES:
- return None
- data = b"".join(chunks)
- line, _, _ = data.partition(b"\n")
- return line or None
+ try:
+ return _read_response_line(lambda: sock.recv(65536), time.monotonic() + timeout)
+ except socket.timeout:
+ return None
-def _query_windows_pipe(
- home: Path, request: bytes, timeout: float
-) -> Optional[bytes]: # pragma: no cover - exercised on the wine2e lane
+def _query_windows_pipe(home: Path, request: bytes, timeout: float) -> Optional[bytes]: # pragma: no cover - wine2e lane
pipe_name = windows_pipe_name(home)
deadline = time.monotonic() + timeout
handle = None
@@ -522,19 +434,7 @@ def _query_windows_pipe(
time.sleep(0.05)
try:
handle.write(request)
- chunks: list[bytes] = []
- while time.monotonic() < deadline:
- chunk = handle.read(65536)
- if not chunk:
- break
- chunks.append(chunk)
- if b"\n" in chunk:
- break
- if sum(len(c) for c in chunks) > _MAX_RESPONSE_BYTES:
- return None
- data = b"".join(chunks)
- line, _, _ = data.partition(b"\n")
- return line or None
+ return _read_response_line(lambda: handle.read(65536), deadline)
finally:
with contextlib.suppress(Exception):
handle.close()
@@ -545,16 +445,11 @@ def identify_gateway(home: Path, *, timeout: float = _DEFAULT_CLIENT_TIMEOUT) ->
return query_gateway_control(home, "identify", timeout=timeout)
-def pause_gateway_for_update(
- home: Path, *, timeout: float = _DEFAULT_CLIENT_TIMEOUT
-) -> Optional[dict[str, Any]]:
+def pause_gateway_for_update(home: Path, *, timeout: float = _DEFAULT_CLIENT_TIMEOUT) -> Optional[dict[str, Any]]:
"""Ask the gateway serving ``home`` to drain and exit for an update.
- Step 2 of the socket migration (#92091). Returns the gateway's ACK —
- ``{"pausing": bool, "already_stopping": bool, "pid": int,
- "drain_timeout": float}`` — or None when no gateway answers (older
- gateway without the verb, no socket, dead socket). None means the
- caller falls back to the legacy pause path (signals / tree-kill),
- exactly as before this verb existed.
+ Returns the ACK ``{"pausing", "already_stopping", "pid", "drain_timeout"}``
+ or None when no gateway answers (old gateway without the verb, no/dead
+ socket) — the caller then uses the legacy signal/tree-kill pause path.
"""
return query_gateway_control(home, "pause-for-update", timeout=timeout)
diff --git a/gateway/hooks.py b/gateway/hooks.py
index 6ecba2a435b..dcf29962a56 100644
--- a/gateway/hooks.py
+++ b/gateway/hooks.py
@@ -1,41 +1,25 @@
"""
Event Hook System
-A lightweight event-driven system that fires handlers at key lifecycle points.
-Hooks are discovered from ~/.hermes/hooks/ directories, each containing:
- - HOOK.yaml (metadata: name, description, events list)
- - handler.py (Python handler with async def handle(event_type, context))
+Fires handlers at gateway lifecycle points. Hooks are discovered from
+~/.hermes/hooks/<name>/ directories, each containing HOOK.yaml (name,
+description, events) and handler.py (``def handle(event_type, context)``,
+sync or async). Handler errors are logged and never block the pipeline.
Events:
- - gateway:startup -- Gateway process starts
- - session:start -- New session created (first message of a new session)
- - session:end -- Session ends (user ran /new or /reset)
- - session:reset -- Session reset completed (new session entry created)
- - agent:start -- Agent begins processing a message
- - agent:step -- Each turn in the tool-calling loop
- - agent:end -- Agent finishes processing
- - command:* -- Any slash command executed (wildcard match)
-
-Errors in hooks are caught and logged but never block the main pipeline.
-
-Context dict passed to ``agent:start`` / ``agent:end`` handlers:
- platform -- source platform name (e.g. "telegram", "matrix", "slack")
- user_id -- platform user id of the sender
- chat_id -- platform chat id (group/DM identifier)
- thread_id -- Telegram forum-topic id / thread root id (string; empty
- when not in a thread / topic)
- chat_type -- "dm" | "group" | "forum" (empty if unknown)
- session_id -- Hermes session id
- message -- inbound message text (truncated to 500 chars)
-
-``agent:end`` adds:
- response -- agent response text (truncated to 500 chars)
- model -- model name that handled the turn
- provider -- provider that handled the turn
-
-Handlers posting a follow-up into the same Telegram forum-topic should
-include ``message_thread_id=int(thread_id)`` when ``chat_type == "forum"``
-and ``thread_id`` is non-empty.
+ gateway:startup, session:start, session:end (user ran /new or /reset),
+ session:reset, agent:start, agent:step (each tool-loop turn), agent:end,
+ command:* (any slash command; wildcard match).
+
+Context passed to ``agent:start`` / ``agent:end``:
+ platform, user_id, chat_id, thread_id (Telegram forum-topic / thread root
+ id as string; empty when not in a thread), chat_type ("dm" | "group" |
+ "forum" | ""), session_id, message (truncated to 500 chars).
+``agent:end`` adds: response (truncated to 500 chars), model, provider.
+
+Handlers posting a follow-up into the same Telegram forum-topic should pass
+``message_thread_id=int(thread_id)`` when ``chat_type == "forum"`` and
+``thread_id`` is non-empty.
"""
import asyncio
@@ -52,44 +36,22 @@ HOOKS_DIR = get_hermes_home() / "hooks"
class HookRegistry:
- """
- Discovers, loads, and fires event hooks.
-
- Usage:
- registry = HookRegistry()
- registry.discover_and_load()
- await registry.emit("agent:start", {"platform": "telegram", ...})
- """
+ """Discovers, loads, and fires event hooks."""
def __init__(self):
- # event_type -> [handler_fn, ...]
- self._handlers: Dict[str, List[Callable]] = {}
+ self._handlers: Dict[str, List[Callable]] = {} # event_type -> handlers
self._loaded_hooks: List[dict] = [] # metadata for listing
@property
def loaded_hooks(self) -> List[dict]:
- """Return metadata about all loaded hooks."""
return list(self._loaded_hooks)
def _register_builtin_hooks(self) -> None:
- """Register built-in hooks that are always active.
-
- Currently empty — no shipped built-in hooks. Kept as the extension
- point for future always-on gateway hooks so they drop in without
- re-plumbing discover_and_load().
- """
+ """Extension point for always-on built-in hooks; currently none shipped."""
return
def discover_and_load(self) -> None:
- """
- Scan the hooks directory for hook directories and load their handlers.
-
- Also registers built-in hooks that are always active.
-
- Each hook directory must contain:
- - HOOK.yaml with at least 'name' and 'events' keys
- - handler.py with a top-level 'handle' function (sync or async)
- """
+ """Register built-in hooks, then load every valid hook dir under HOOKS_DIR."""
self._register_builtin_hooks()
if not HOOKS_DIR.exists():
@@ -117,17 +79,12 @@ class HookRegistry:
print(f"[hooks] Skipping {hook_name}: no events declared", flush=True)
continue
- # Dynamically load the handler module.
- # Register in sys.modules BEFORE exec_module so Pydantic /
- # dataclasses / typing introspection can resolve forward
- # references (triggered by `from __future__ import annotations`
- # in the handler). Without this, a handler that declares a
- # Pydantic BaseModel for webhook/event payloads fails at first
+ # Register in sys.modules BEFORE exec_module so Pydantic/dataclass
+ # forward references (from ``from __future__ import annotations``)
+ # resolve; otherwise a handler declaring a BaseModel fails at first
# dispatch with "TypeAdapter ... is not fully defined".
module_name = f"hermes_hook_{hook_name}"
- spec = importlib.util.spec_from_file_location(
- module_name, handler_path
- )
+ spec = importlib.util.spec_from_file_location(module_name, handler_path)
if spec is None or spec.loader is None:
print(f"[hooks] Skipping {hook_name}: could not load handler.py", flush=True)
continue
@@ -145,7 +102,6 @@ class HookRegistry:
print(f"[hooks] Skipping {hook_name}: no 'handle' function found", flush=True)
continue
- # Register the handler for each declared event
for event in events:
self._handlers.setdefault(event, []).append(handle_fn)
@@ -162,42 +118,19 @@ class HookRegistry:
print(f"[hooks] Error loading hook {hook_dir.name}: {e}", flush=True)
def _resolve_handlers(self, event_type: str) -> List[Callable]:
- """Return all handlers that should fire for ``event_type``.
+ """Exact-match handlers first, then ``<base>:*`` wildcard handlers.
- Exact matches fire first, followed by wildcard matches (e.g.
- ``command:*`` matches ``command:reset``).
+ A handler registered for a bare base type ("agent") does NOT fire for
+ "agent:start" — only exact matches and explicit wildcards.
"""
handlers = list(self._handlers.get(event_type, []))
if ":" in event_type:
- base = event_type.split(":")[0]
- wildcard_key = f"{base}:*"
- handlers.extend(self._handlers.get(wildcard_key, []))
+ handlers.extend(self._handlers.get(f"{event_type.split(':')[0]}:*", []))
return handlers
async def emit(self, event_type: str, context: Optional[Dict[str, Any]] = None) -> None:
- """
- Fire all handlers registered for an event, discarding return values.
-
- Supports wildcard matching: handlers registered for "command:*" will
- fire for any "command:..." event. Handlers registered for a base type
- like "agent" won't fire for "agent:start" -- only exact matches and
- explicit wildcards.
-
- Args:
- event_type: The event identifier (e.g. "agent:start").
- context: Optional dict with event-specific data.
- """
- if context is None:
- context = {}
-
- for fn in self._resolve_handlers(event_type):
- try:
- result = fn(event_type, context)
- # Support both sync and async handlers
- if asyncio.iscoroutine(result):
- await result
- except Exception as e:
- print(f"[hooks] Error in handler for '{event_type}': {e}", flush=True)
+ """Fire all handlers for an event, discarding return values."""
+ await self.emit_collect(event_type, context)
async def emit_collect(
self,
@@ -206,12 +139,9 @@ class HookRegistry:
) -> List[Any]:
"""Fire handlers and return their non-None return values in order.
- Like :meth:`emit` but captures each handler's return value. Used for
- decision-style hooks (e.g. ``command:<name>`` policies that want to
- allow/deny/rewrite the command before normal dispatch).
-
- Exceptions from individual handlers are logged but do not abort the
- remaining handlers.
+ Used for decision-style hooks (e.g. ``command:<name>`` policies that
+ allow/deny/rewrite a command). A failing handler is logged and does not
+ abort the remaining handlers.
"""
if context is None:
context = {}
@@ -220,7 +150,7 @@ class HookRegistry:
for fn in self._resolve_handlers(event_type):
try:
result = fn(event_type, context)
- if asyncio.iscoroutine(result):
+ if asyncio.iscoroutine(result): # sync and async handlers both supported
result = await result
if result is not None:
results.append(result)
diff --git a/gateway/hosted_room_discussion.py b/gateway/hosted_room_discussion.py
index 2a1f5db020d..6e399bae300 100644
--- a/gateway/hosted_room_discussion.py
+++ b/gateway/hosted_room_discussion.py
@@ -1,16 +1,14 @@
"""Deterministic policy for same-gateway hosted-room Discussions.
-This module translates a frozen local member roster and the complete typed room
-log into one next driver task. It performs no I/O, starts no workers, and knows
-nothing about transports or model runtimes. Callers persist the returned task
-with :mod:`gateway.hosted_room_driver` and append publication plans with
-:mod:`gateway.hosted_rooms`.
-
-The unpublished driver payload intentionally remains unchanged. Discussion
-coordinates live in deterministic ``TaskIdentity`` values and typed terminal
-events; a restart can therefore reconstruct a task without widening the driver
-schema. Callers must reconcile terminal driver rows into publication plans
-before asking for the next task.
+Translates a frozen local member roster plus the complete typed room log into
+one next driver task. Pure: no I/O, no workers, no transport or model
+knowledge. Callers persist the task with :mod:`gateway.hosted_room_driver`
+and append publication plans with :mod:`gateway.hosted_rooms`.
+
+The driver payload is deliberately not widened: Discussion coordinates live
+in deterministic ``TaskIdentity`` values and typed terminal events, so a
+restart can reconstruct a task from durable state. Callers must reconcile
+terminal driver rows into publication plans before asking for the next task.
"""
from __future__ import annotations
@@ -48,66 +46,40 @@ _TURN_ID_RE = re.compile(
r"m(?P<member>[0-9a-f]{24})$"
)
-_MEMBER_FIELDS = frozenset(
- {"member_id", "profile", "handle", "display_name", "target"}
-)
_LOCAL_TARGET_FIELDS = frozenset({"kind", "profile"})
_PEER_TARGET_FIELDS = frozenset(
{"kind", "peer_id", "installation_id", "profile", "capability_digest"}
)
_REMOTE_MEMBER_FIELDS = frozenset({
- "connectionId",
- "connectionKind",
- "connectionLabel",
- "connection_id",
- "connection_kind",
- "connection_label",
- "remoteSource",
- "route",
- "sourceMissing",
- "sourceReachable",
- "sourceScoped",
- "targetProfile",
+ "connectionId", "connectionKind", "connectionLabel", "connection_id",
+ "connection_kind", "connection_label", "remoteSource", "route",
+ "sourceMissing", "sourceReachable", "sourceScoped", "targetProfile",
"target_profile",
})
_USER_PAYLOAD_FIELDS = frozenset({"text", "thread_id"})
-_MEMBER_MESSAGE_FIELDS = frozenset({
- "discussion_event_id",
- "member_id",
- "member_index",
- "round_index",
- "task_id",
- "text",
- "thread_id",
- "turn_id",
-})
-_TERMINAL_COMMON_FIELDS = frozenset({
- "discussion_event_id",
- "member_id",
- "member_index",
- "round_index",
- "seen_through_seq",
- "task_id",
- "thread_id",
- "turn_id",
+_TURN_COORDINATE_FIELDS = frozenset({
+ "discussion_event_id", "member_id", "member_index", "round_index",
+ "task_id", "thread_id", "turn_id",
})
+_MEMBER_MESSAGE_FIELDS = _TURN_COORDINATE_FIELDS | {"text"}
+_TERMINAL_COMMON_FIELDS = _TURN_COORDINATE_FIELDS | {"seen_through_seq"}
_TERMINAL_EXTRA_FIELDS = {
"turn.settled": frozenset({"message_event_id", "passed"}),
"turn.failed": frozenset({"error"}),
"turn.cancelled": frozenset({"reason"}),
"turn.deferred": frozenset({"execution_generation", "reason"}),
}
-_TERMINAL_OPTIONAL_FIELDS = {
- "turn.failed": frozenset({"reason_code"}),
-}
+_TERMINAL_OPTIONAL_FIELDS = {"turn.failed": frozenset({"reason_code"})}
_TERMINAL_EVENT_KINDS = frozenset(_TERMINAL_EXTRA_FIELDS)
-_ROOM_ACTIVITY_FIELDS = frozenset({
- "status",
- "reason_code",
- "thread_id",
- "discussion_event_id",
-})
-_ROOM_STOP_FIELDS = frozenset({"cancel_id"})
+# Gateway-authored control events: kind -> (exact payload fields, identifier fields).
+_GATEWAY_EVENT_FIELDS = {
+ "room.activity": (
+ frozenset({"status", "reason_code", "thread_id", "discussion_event_id"}),
+ ("reason_code", "thread_id", "discussion_event_id"),
+ ),
+ "room.stop_requested": (frozenset({"cancel_id"}), ("cancel_id",)),
+}
+_EPOCH_STAMPED_KINDS = _TERMINAL_EVENT_KINDS | {"message.member", *_GATEWAY_EVENT_FIELDS}
class DiscussionPolicyError(ValueError):
@@ -182,7 +154,6 @@ class EventPlan:
def append_kwargs(self, room_id: str) -> dict[str, Any]:
"""Return keyword arguments accepted by ``append_event``."""
-
return {
"room_id": room_id,
"event_id": self.event_id,
@@ -235,14 +206,8 @@ def _positive_int(value: Any, *, label: str, maximum: int | None = None) -> int:
def _zero_based_int(value: Any, *, label: str, maximum: int) -> int:
- if (
- isinstance(value, bool)
- or not isinstance(value, int)
- or not 0 <= value <= maximum
- ):
- raise DiscussionValidationError(
- f"{label} must be an integer between 0 and {maximum}"
- )
+ if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= maximum:
+ raise DiscussionValidationError(f"{label} must be an integer between 0 and {maximum}")
return value
@@ -259,24 +224,20 @@ def _exact_fields(
missing = required - keys
unknown = keys - required - optional
if missing:
- raise DiscussionValidationError(
- f"{label} is missing fields: {', '.join(sorted(missing))}"
- )
+ raise DiscussionValidationError(f"{label} is missing fields: {', '.join(sorted(missing))}")
if unknown:
- raise DiscussionValidationError(
- f"{label} has unknown fields: {', '.join(sorted(unknown))}"
- )
+ raise DiscussionValidationError(f"{label} has unknown fields: {', '.join(sorted(unknown))}")
return value
+def _peer_target(member: DiscussionMember) -> Mapping[str, Any] | None:
+ target = member.target
+ return target if target and target.get("kind") == "peer" else None
+
+
def validate_user_payload(value: Any) -> dict[str, Any]:
"""Validate and normalize the exact ``message.user`` Discussion payload."""
-
- payload = _exact_fields(
- value,
- label="user payload",
- required=_USER_PAYLOAD_FIELDS,
- )
+ payload = _exact_fields(value, label="user payload", required=_USER_PAYLOAD_FIELDS)
text = payload["text"]
if not isinstance(text, str):
raise DiscussionValidationError("user payload text must be a string")
@@ -285,16 +246,11 @@ def validate_user_payload(value: Any) -> dict[str, Any]:
raise DiscussionValidationError("user payload text must not be empty")
if len(text.encode("utf-8")) > MAX_USER_TEXT_BYTES:
raise DiscussionValidationError("user payload text is too large")
- thread_id = _identifier(payload["thread_id"], label="thread_id")
- return {"text": text, "thread_id": thread_id}
+ return {"text": text, "thread_id": _identifier(payload["thread_id"], label="thread_id")}
def _validate_member_target(
- value: Any,
- *,
- profile: str,
- known_profiles: set[str],
- index: int,
+ value: Any, *, profile: str, known_profiles: set[str], index: int
) -> dict[str, Any]:
if value is None:
if profile not in known_profiles:
@@ -305,65 +261,46 @@ def _validate_member_target(
if not isinstance(value, Mapping):
raise DiscussionValidationError(f"member {index} target must be an object")
kind = value.get("kind")
+ if kind not in ("local", "peer"):
+ raise DiscussionValidationError(f"member {index} target kind must be local or peer")
+ target = _exact_fields(
+ value,
+ label=f"member {index} {kind} target",
+ required=_LOCAL_TARGET_FIELDS if kind == "local" else _PEER_TARGET_FIELDS,
+ )
+ target_profile = _identifier(target["profile"], label=f"member {index} target profile")
if kind == "local":
- target = _exact_fields(
- value,
- label=f"member {index} local target",
- required=_LOCAL_TARGET_FIELDS,
- )
- target_profile = _identifier(
- target["profile"], label=f"member {index} target profile"
- )
if target_profile != profile or profile not in known_profiles:
raise DiscussionValidationError(
f"member {index} local target does not match a local profile"
)
return {"kind": "local", "profile": profile}
- if kind == "peer":
- target = _exact_fields(
- value,
- label=f"member {index} peer target",
- required=_PEER_TARGET_FIELDS,
+ if target_profile != profile:
+ raise DiscussionValidationError(
+ f"member {index} peer target profile does not match member profile"
)
- target_profile = _identifier(
- target["profile"], label=f"member {index} target profile"
+ capability_digest = target["capability_digest"]
+ if not isinstance(capability_digest, str) or not re.fullmatch(
+ r"[0-9a-f]{64}", capability_digest
+ ):
+ raise DiscussionValidationError(
+ f"member {index} capability_digest must be a sha256 digest"
)
- if target_profile != profile:
- raise DiscussionValidationError(
- f"member {index} peer target profile does not match member profile"
- )
- capability_digest = target["capability_digest"]
- if (
- not isinstance(capability_digest, str)
- or not re.fullmatch(r"[0-9a-f]{64}", capability_digest)
- ):
- raise DiscussionValidationError(
- f"member {index} capability_digest must be a sha256 digest"
- )
- return {
- "kind": "peer",
- "peer_id": _identifier(
- target["peer_id"], label=f"member {index} peer_id"
- ),
- "installation_id": _identifier(
- target["installation_id"],
- label=f"member {index} installation_id",
- ),
- "profile": target_profile,
- "capability_digest": capability_digest,
- }
- raise DiscussionValidationError(
- f"member {index} target kind must be local or peer"
- )
+ return {
+ "kind": "peer",
+ "peer_id": _identifier(target["peer_id"], label=f"member {index} peer_id"),
+ "installation_id": _identifier(
+ target["installation_id"], label=f"member {index} installation_id"
+ ),
+ "profile": target_profile,
+ "capability_digest": capability_digest,
+ }
def validate_roster(
- value: Any,
- *,
- local_profiles: Iterable[str],
+ value: Any, *, local_profiles: Iterable[str]
) -> tuple[DiscussionMember, ...]:
"""Validate a frozen 2-6 member roster of profiles on this gateway."""
-
if not isinstance(value, list):
raise DiscussionValidationError("members must be a list")
if not MIN_DISCUSSION_MEMBERS <= len(value) <= MAX_DISCUSSION_MEMBERS:
@@ -372,9 +309,7 @@ def validate_roster(
f"{MAX_DISCUSSION_MEMBERS} entries"
)
- known_profiles = {
- _identifier(profile, label="local profile") for profile in local_profiles
- }
+ known_profiles = {_identifier(profile, label="local profile") for profile in local_profiles}
members: list[DiscussionMember] = []
targets: set[str] = set()
handles: set[str] = set()
@@ -399,25 +334,16 @@ def validate_roster(
profile = _identifier(member["profile"], label=f"member {index} profile")
handle = _identifier(member["handle"], label=f"member {index} handle")
target = _validate_member_target(
- member.get("target"),
- profile=profile,
- known_profiles=known_profiles,
- index=index,
+ member.get("target"), profile=profile, known_profiles=known_profiles, index=index
)
display_name = member.get("display_name", "")
if not isinstance(display_name, str):
- raise DiscussionValidationError(
- f"member {index} display_name must be a string"
- )
+ raise DiscussionValidationError(f"member {index} display_name must be a string")
display_name = display_name.strip()
if len(display_name) > hosted_rooms.MAX_ACTOR_LABEL_CHARS:
raise DiscussionValidationError(f"member {index} display_name is too long")
- target_key = json.dumps(
- target,
- sort_keys=True,
- separators=(",", ":"),
- ).casefold()
+ target_key = json.dumps(target, sort_keys=True, separators=(",", ":")).casefold()
handle_key = handle.casefold()
member_key = member_id.casefold()
if target_key in targets:
@@ -445,13 +371,8 @@ def validate_roster(
return tuple(members)
-def validate_room(
- value: Any,
- *,
- local_profiles: Iterable[str],
-) -> DiscussionRoom:
+def validate_room(value: Any, *, local_profiles: Iterable[str]) -> DiscussionRoom:
"""Project a hosted-room row into the strict same-gateway policy shape."""
-
if not isinstance(value, Mapping):
raise DiscussionValidationError("room must be an object")
if value.get("disbanded_at") is not None:
@@ -463,14 +384,8 @@ def validate_room(
name = name.strip()
if len(name) > hosted_rooms.MAX_ROOM_NAME_CHARS:
raise DiscussionValidationError("room name is too long")
- gateway_id = _identifier(
- value.get("authority_gateway_id"),
- label="authority_gateway_id",
- )
- authority_epoch = _positive_int(
- value.get("authority_epoch"),
- label="authority_epoch",
- )
+ gateway_id = _identifier(value.get("authority_gateway_id"), label="authority_gateway_id")
+ authority_epoch = _positive_int(value.get("authority_epoch"), label="authority_epoch")
members = validate_roster(value.get("members"), local_profiles=local_profiles)
return DiscussionRoom(
room_id=room_id,
@@ -483,12 +398,8 @@ def validate_room(
def is_pass_text(value: Any) -> bool:
"""Return whether a settled member result is Discussion silence."""
-
text = str(value or "").strip()
- return (
- not text
- or re.fullmatch(r"\(?\s*pass\s*\)?\.?", text, re.IGNORECASE) is not None
- )
+ return not text or re.fullmatch(r"\(?\s*pass\s*\)?\.?", text, re.IGNORECASE) is not None
def resolve_mentions(
@@ -498,7 +409,6 @@ def resolve_mentions(
default_all: bool = True,
) -> tuple[DiscussionMember, ...]:
"""Resolve member handles deterministically against the frozen roster."""
-
by_handle = {member.handle.casefold(): member for member in members}
mentioned: set[str] = set()
everyone = False
@@ -515,11 +425,9 @@ def resolve_mentions(
def _unaddressed_member_mentions(
- messages: Sequence[_ValidatedEvent],
- room: DiscussionRoom,
+ messages: Sequence[_ValidatedEvent], room: DiscussionRoom
) -> tuple[DiscussionMember, ...]:
"""Return peers explicitly cited by a Bot and not heard from afterward."""
-
cited_at: dict[str, int] = {}
last_post_at: dict[str, int] = {}
for event in messages:
@@ -527,11 +435,7 @@ def _unaddressed_member_mentions(
continue
speaker_id = str(event.payload["member_id"])
last_post_at[speaker_id] = event.seq
- cited = resolve_mentions(
- (str(event.payload["text"]),),
- room.members,
- default_all=False,
- )
+ cited = resolve_mentions((str(event.payload["text"]),), room.members, default_all=False)
for member in cited:
if member.member_id != speaker_id:
cited_at[member.member_id] = event.seq
@@ -543,12 +447,12 @@ def _unaddressed_member_mentions(
)
-def _validate_event(
- raw: Any,
- *,
- room: DiscussionRoom,
- previous_seq: int,
-) -> _ValidatedEvent:
+def _require_gateway_actor(actor: Mapping[str, Any], room: DiscussionRoom, message: str) -> None:
+ if actor.get("kind") != "gateway" or actor.get("id") != room.gateway_id:
+ raise DiscussionValidationError(message)
+
+
+def _validate_event(raw: Any, *, room: DiscussionRoom, previous_seq: int) -> _ValidatedEvent:
if not isinstance(raw, Mapping):
raise DiscussionValidationError("room event must be an object")
if raw.get("room_id") != room.room_id:
@@ -566,63 +470,28 @@ def _validate_event(
payload = raw.get("payload")
if not isinstance(payload, Mapping):
raise DiscussionValidationError("event payload must be an object")
+ if kind in _EPOCH_STAMPED_KINDS and raw.get("authority_epoch") != room.authority_epoch:
+ raise DiscussionValidationError(f"{kind} authority epoch does not match the room")
if kind == "message.user":
payload = validate_user_payload(payload)
if actor.get("kind") != "user":
raise DiscussionValidationError("message.user requires a user actor")
elif kind == "message.member":
- if raw.get("authority_epoch") != room.authority_epoch:
- raise DiscussionValidationError(
- "message.member authority epoch does not match the room"
- )
_validate_member_message(payload, actor=actor, room=room)
elif kind in _TERMINAL_EVENT_KINDS:
- if raw.get("authority_epoch") != room.authority_epoch:
- raise DiscussionValidationError(
- f"{kind} authority epoch does not match the room"
- )
_validate_terminal_event(kind, payload, actor=actor, room=room)
- elif kind == "room.activity":
- if raw.get("authority_epoch") != room.authority_epoch:
- raise DiscussionValidationError(
- "room.activity authority epoch does not match the room"
- )
- _exact_fields(
- payload,
- label="room.activity payload",
- required=_ROOM_ACTIVITY_FIELDS,
- )
- if payload.get("status") not in {"settled", "bounded"}:
+ elif kind in _GATEWAY_EVENT_FIELDS:
+ fields, identifier_fields = _GATEWAY_EVENT_FIELDS[kind]
+ _exact_fields(payload, label=f"{kind} payload", required=fields)
+ if kind == "room.activity" and payload.get("status") not in {"settled", "bounded"}:
raise DiscussionValidationError("invalid room.activity status")
- _identifier(payload.get("reason_code"), label="reason_code")
- _identifier(payload.get("thread_id"), label="thread_id")
- _identifier(payload.get("discussion_event_id"), label="discussion_event_id")
- if actor.get("kind") != "gateway" or actor.get("id") != room.gateway_id:
- raise DiscussionValidationError("room.activity requires the room gateway")
- elif kind == "room.stop_requested":
- if raw.get("authority_epoch") != room.authority_epoch:
- raise DiscussionValidationError(
- "room.stop_requested authority epoch does not match the room"
- )
- _exact_fields(
- payload,
- label="room.stop_requested payload",
- required=_ROOM_STOP_FIELDS,
- )
- _identifier(payload.get("cancel_id"), label="cancel_id")
- if actor.get("kind") != "gateway" or actor.get("id") != room.gateway_id:
- raise DiscussionValidationError(
- "room.stop_requested requires the room gateway"
- )
+ for field in identifier_fields:
+ _identifier(payload.get(field), label=field)
+ _require_gateway_actor(actor, room, f"{kind} requires the room gateway")
return _ValidatedEvent(
- raw=raw,
- seq=seq,
- event_id=event_id,
- kind=kind,
- actor=actor,
- payload=payload,
+ raw=raw, seq=seq, event_id=event_id, kind=kind, actor=actor, payload=payload
)
@@ -634,49 +503,29 @@ def _member_by_id(room: DiscussionRoom, member_id: Any) -> DiscussionMember:
raise DiscussionValidationError(f"unknown Discussion member '{normalized}'")
-def _validate_turn_coordinates(
- payload: Mapping[str, Any], room: DiscussionRoom
-) -> None:
+def _validate_turn_coordinates(payload: Mapping[str, Any], room: DiscussionRoom) -> None:
_member_by_id(room, payload.get("member_id"))
- member_index = _zero_based_int(
- payload.get("member_index"),
- label="member_index",
- maximum=MAX_DISCUSSION_MEMBERS - 1,
- )
- round_index = _zero_based_int(
- payload.get("round_index"),
- label="round_index",
- maximum=MAX_DISCUSSION_ROUNDS - 1,
+ _zero_based_int(
+ payload.get("member_index"), label="member_index", maximum=MAX_DISCUSSION_MEMBERS - 1
)
- thread_id = _identifier(payload.get("thread_id"), label="thread_id")
- task_id = _identifier(payload.get("task_id"), label="task_id")
- turn_id = _identifier(payload.get("turn_id"), label="turn_id")
- discussion_event_id = _identifier(
- payload.get("discussion_event_id"),
- label="discussion_event_id",
+ _zero_based_int(
+ payload.get("round_index"), label="round_index", maximum=MAX_DISCUSSION_ROUNDS - 1
)
- del member_index, round_index, thread_id, task_id, turn_id, discussion_event_id
+ for field in ("thread_id", "task_id", "turn_id", "discussion_event_id"):
+ _identifier(payload.get(field), label=field)
def _validate_member_message(
- payload: Mapping[str, Any],
- *,
- actor: Mapping[str, Any],
- room: DiscussionRoom,
+ payload: Mapping[str, Any], *, actor: Mapping[str, Any], room: DiscussionRoom
) -> None:
- _exact_fields(
- payload,
- label="message.member payload",
- required=_MEMBER_MESSAGE_FIELDS,
- )
+ _exact_fields(payload, label="message.member payload", required=_MEMBER_MESSAGE_FIELDS)
_validate_turn_coordinates(payload, room)
text = payload.get("text")
if not isinstance(text, str) or not text.strip() or is_pass_text(text):
raise DiscussionValidationError("message.member text must be a non-pass string")
member = _member_by_id(room, payload.get("member_id"))
- expected_connection = None
- if member.target and member.target.get("kind") == "peer":
- expected_connection = member.target.get("peer_id")
+ peer = _peer_target(member)
+ expected_connection = peer.get("peer_id") if peer else None
if (
actor.get("kind") != "member"
or actor.get("id") != member.member_id
@@ -687,60 +536,44 @@ def _validate_member_message(
def _validate_terminal_event(
- kind: str,
- payload: Mapping[str, Any],
- *,
- actor: Mapping[str, Any],
- room: DiscussionRoom,
+ kind: str, payload: Mapping[str, Any], *, actor: Mapping[str, Any], room: DiscussionRoom
) -> None:
- required = _TERMINAL_COMMON_FIELDS | _TERMINAL_EXTRA_FIELDS[kind]
_exact_fields(
payload,
label=f"{kind} payload",
- required=required,
+ required=_TERMINAL_COMMON_FIELDS | _TERMINAL_EXTRA_FIELDS[kind],
optional=_TERMINAL_OPTIONAL_FIELDS.get(kind, frozenset()),
)
_validate_turn_coordinates(payload, room)
_positive_int(payload.get("seen_through_seq"), label="seen_through_seq")
- if (
- actor.get("kind") != "gateway"
- or actor.get("id") != room.gateway_id
- or actor.get("connection_id") is not None
- ):
+ if actor.get("connection_id") is not None:
raise DiscussionValidationError(f"{kind} requires a gateway actor")
+ _require_gateway_actor(actor, room, f"{kind} requires a gateway actor")
if kind == "turn.settled":
if not isinstance(payload.get("passed"), bool):
raise DiscussionValidationError("turn.settled passed must be a boolean")
message_event_id = payload.get("message_event_id")
- if payload["passed"]:
- if message_event_id is not None:
- raise DiscussionValidationError(
- "a passed turn cannot reference a member message"
- )
- else:
+ if not payload["passed"]:
_identifier(message_event_id, label="message_event_id")
- else:
- field = "error" if kind == "turn.failed" else "reason"
- if not isinstance(payload.get(field), str) or not payload[field].strip():
- raise DiscussionValidationError(f"{kind} {field} must be non-empty")
- if kind == "turn.deferred":
- _positive_int(
- payload.get("execution_generation"),
- label="execution_generation",
+ elif message_event_id is not None:
+ raise DiscussionValidationError("a passed turn cannot reference a member message")
+ return
+ field = "error" if kind == "turn.failed" else "reason"
+ if not isinstance(payload.get(field), str) or not payload[field].strip():
+ raise DiscussionValidationError(f"{kind} {field} must be non-empty")
+ if kind == "turn.deferred":
+ _positive_int(payload.get("execution_generation"), label="execution_generation")
+ if kind == "turn.failed" and "reason_code" in payload:
+ from tools.bot_failure_reasons import ALL_REASONS
+
+ if payload["reason_code"] not in ALL_REASONS:
+ raise DiscussionValidationError(
+ "turn.failed reason_code must use the shared failure vocabulary"
)
- if kind == "turn.failed" and "reason_code" in payload:
- from tools.bot_failure_reasons import ALL_REASONS
-
- if payload["reason_code"] not in ALL_REASONS:
- raise DiscussionValidationError(
- "turn.failed reason_code must use the shared failure vocabulary"
- )
def _validated_events(
- events: Sequence[Mapping[str, Any]],
- *,
- room: DiscussionRoom,
+ events: Sequence[Mapping[str, Any]], *, room: DiscussionRoom
) -> tuple[_ValidatedEvent, ...]:
validated: list[_ValidatedEvent] = []
previous_seq = 0
@@ -755,30 +588,6 @@ def _validated_events(
return tuple(validated)
-def _discussion_user_events(
- events: Sequence[_ValidatedEvent],
-) -> tuple[_ValidatedEvent, ...]:
- return tuple(event for event in events if event.kind == "message.user")
-
-
-def _message_events(
- events: Sequence[_ValidatedEvent],
- *,
- thread_id: str | None = None,
- maximum_seq: int | None = None,
-) -> tuple[_ValidatedEvent, ...]:
- result = []
- for event in events:
- if event.kind not in {"message.user", "message.member"}:
- continue
- if thread_id is not None and event.payload.get("thread_id") != thread_id:
- continue
- if maximum_seq is not None and event.seq > maximum_seq:
- continue
- result.append(event)
- return tuple(result)
-
-
def derive_member_watermarks(
room_value: Any,
events: Sequence[Mapping[str, Any]],
@@ -786,10 +595,8 @@ def derive_member_watermarks(
local_profiles: Iterable[str],
) -> dict[tuple[str, str], int]:
"""Derive ``(thread_id, member_id)`` watermarks from terminal events."""
-
room = validate_room(room_value, local_profiles=local_profiles)
- validated = _validated_events(events, room=room)
- return _derive_member_watermarks(validated)
+ return _derive_member_watermarks(_validated_events(events, room=room))
def _derive_member_watermarks(
@@ -820,8 +627,7 @@ def _derive_member_watermarks(
key = (str(event.payload["thread_id"]), str(event.payload["member_id"]))
watermark = int(event.payload["seen_through_seq"])
if event.kind == "turn.settled" and not event.payload["passed"]:
- message_id = str(event.payload["message_event_id"])
- message = messages_by_id.get(message_id)
+ message = messages_by_id.get(str(event.payload["message_event_id"]))
if (
message is None
or message.payload.get("task_id") != task_id
@@ -842,15 +648,11 @@ def _member_digest(member: DiscussionMember) -> str:
sort_keys=True,
separators=(",", ":"),
)
- seed = (
- f"{member.member_id}\0{member.profile}\0{member.handle}\0{target}"
- )
+ seed = f"{member.member_id}\0{member.profile}\0{member.handle}\0{target}"
return hashlib.sha256(seed.encode("utf-8")).hexdigest()[:24]
-def _rotate(
- members: Sequence[DiscussionMember], round_index: int
-) -> tuple[DiscussionMember, ...]:
+def _rotate(members: Sequence[DiscussionMember], round_index: int) -> tuple[DiscussionMember, ...]:
if len(members) < 2:
return tuple(members)
shift = round_index % len(members)
@@ -934,21 +736,7 @@ def _build_prompt(
return prompt
-def _turn_id(
- *,
- source_event_seq: int,
- round_index: int,
- member_index: int,
- seen_through_seq: int,
- member: DiscussionMember,
-) -> str:
- return (
- f"d{source_event_seq}.r{round_index}.p{member_index}."
- f"s{seen_through_seq}.m{_member_digest(member)}"
- )
-
-
-def _task_id(
+def _make_task_plan(
*,
room: DiscussionRoom,
discussion_event: _ValidatedEvent,
@@ -957,7 +745,11 @@ def _task_id(
round_index: int,
seen_through_seq: int,
prompt: str,
-) -> str:
+) -> DiscussionTaskPlan:
+ turn_id = (
+ f"d{discussion_event.seq}.r{round_index}.p{member_index}."
+ f"s{seen_through_seq}.m{_member_digest(member)}"
+ )
seed = json.dumps(
{
"discussion_event_id": discussion_event.event_id,
@@ -974,35 +766,7 @@ def _task_id(
sort_keys=True,
separators=(",", ":"),
)
- return f"dtask:{hashlib.sha256(seed.encode('utf-8')).hexdigest()[:48]}"
-
-
-def _make_task_plan(
- *,
- room: DiscussionRoom,
- discussion_event: _ValidatedEvent,
- member: DiscussionMember,
- member_index: int,
- round_index: int,
- seen_through_seq: int,
- prompt: str,
-) -> DiscussionTaskPlan:
- turn_id = _turn_id(
- source_event_seq=discussion_event.seq,
- round_index=round_index,
- member_index=member_index,
- seen_through_seq=seen_through_seq,
- member=member,
- )
- task_id = _task_id(
- room=room,
- discussion_event=discussion_event,
- member=member,
- member_index=member_index,
- round_index=round_index,
- seen_through_seq=seen_through_seq,
- prompt=prompt,
- )
+ task_id = f"dtask:{hashlib.sha256(seed.encode('utf-8')).hexdigest()[:48]}"
identity = driver.TaskIdentity(
room_id=room.room_id,
task_id=task_id,
@@ -1034,10 +798,8 @@ def plan_next_task(
initial_watermarks: Mapping[tuple[str, str], int] | None = None,
) -> DiscussionDecision:
"""Replay the complete room log and return at most one next member task."""
-
room = validate_room(room_value, local_profiles=local_profiles)
validated = _validated_events(events, room=room)
- user_events = _discussion_user_events(validated)
stopped_through_seq = max(
(event.seq for event in validated if event.kind == "room.stop_requested"),
default=0,
@@ -1049,8 +811,9 @@ def plan_next_task(
and event.payload.get("status") in {"settled", "bounded"}
}
latest_by_thread: dict[str, _ValidatedEvent] = {}
- for event in user_events:
- latest_by_thread[str(event.payload["thread_id"])] = event
+ for event in validated:
+ if event.kind == "message.user":
+ latest_by_thread[str(event.payload["thread_id"])] = event
pending_user_events = tuple(
event
for event in sorted(latest_by_thread.values(), key=lambda item: item.seq)
@@ -1062,6 +825,19 @@ def plan_next_task(
discussion = pending_user_events[0]
thread_id = str(discussion.payload["thread_id"])
+
+ def decide(
+ status: DecisionStatus, reason: str, task: DiscussionTaskPlan | None = None
+ ) -> DiscussionDecision:
+ return DiscussionDecision(
+ status=status,
+ reason=reason,
+ discussion_event_id=discussion.event_id,
+ source_event_seq=discussion.seq,
+ thread_id=thread_id,
+ task=task,
+ )
+
committed_member_message_ids = {
str(event.payload["message_event_id"])
for event in validated
@@ -1074,9 +850,12 @@ def plan_next_task(
# the caller can inspect the terminal driver row and finish publication.
thread_messages = tuple(
event
- for event in _message_events(validated, thread_id=thread_id)
- if event.kind == "message.user"
- or event.event_id in committed_member_message_ids
+ for event in validated
+ if event.payload.get("thread_id") == thread_id
+ and (
+ event.kind == "message.user"
+ or (event.kind == "message.member" and event.event_id in committed_member_message_ids)
+ )
)
discussion_messages = tuple(
event for event in thread_messages if event.seq >= discussion.seq
@@ -1088,13 +867,7 @@ def plan_next_task(
and event.payload.get("discussion_event_id") == discussion.event_id
)
if len(member_messages) >= MAX_DISCUSSION_MESSAGES:
- return DiscussionDecision(
- status="bounded",
- reason="max_messages",
- discussion_event_id=discussion.event_id,
- source_event_seq=discussion.seq,
- thread_id=thread_id,
- )
+ return decide("bounded", "max_messages")
terminals = {
(int(event.payload["round_index"]), str(event.payload["member_id"])): event
@@ -1122,17 +895,11 @@ def plan_next_task(
if round_index == 0
else _unaddressed_member_mentions(discussion_messages, room)
)
- ordered = _rotate(responders, round_index)
- for member_index, member in enumerate(ordered):
+ for member_index, member in enumerate(_rotate(responders, round_index)):
if (round_index, member.member_id) in terminals:
continue
watermark = watermarks.get((thread_id, member.member_id), 0)
- delta = [
- event
- for event in thread_messages
- if watermark < event.seq <= seen_through_seq
- ]
- if not delta:
+ if not any(watermark < event.seq <= seen_through_seq for event in thread_messages):
continue
prompt = _build_prompt(
room=room,
@@ -1150,35 +917,15 @@ def plan_next_task(
seen_through_seq=seen_through_seq,
prompt=prompt,
)
- return DiscussionDecision(
- status="task",
- reason="member_turn",
- discussion_event_id=discussion.event_id,
- source_event_seq=discussion.seq,
- thread_id=thread_id,
- task=task,
- )
+ return decide("task", "member_turn", task)
spoke = any(
- int(event.payload["round_index"]) == round_index
- for event in member_messages
+ int(event.payload["round_index"]) == round_index for event in member_messages
)
if not spoke:
- return DiscussionDecision(
- status="settled",
- reason="silent_round",
- discussion_event_id=discussion.event_id,
- source_event_seq=discussion.seq,
- thread_id=thread_id,
- )
+ return decide("settled", "silent_round")
if round_index == MAX_DISCUSSION_ROUNDS - 1:
- return DiscussionDecision(
- status="bounded",
- reason="max_rounds",
- discussion_event_id=discussion.event_id,
- source_event_seq=discussion.seq,
- thread_id=thread_id,
- )
+ return decide("bounded", "max_rounds")
raise AssertionError("bounded Discussion loop exhausted unexpectedly")
@@ -1191,22 +938,13 @@ def reconstruct_task_plan(
local_profiles: Iterable[str],
) -> DiscussionTaskPlan:
"""Reconstruct and verify one persisted driver task after a restart."""
-
room = validate_room(room_value, local_profiles=local_profiles)
validated = _validated_events(events, room=room)
identity = task.get("identity")
payload = task.get("payload")
- if not isinstance(identity, driver.TaskIdentity) or not isinstance(
- payload, Mapping
- ):
- raise DiscussionReconstructionError(
- "driver task has no valid identity or payload"
- )
- required_payload = frozenset({
- "target_profile",
- "prompt",
- "source_event_seq",
- })
+ if not isinstance(identity, driver.TaskIdentity) or not isinstance(payload, Mapping):
+ raise DiscussionReconstructionError("driver task has no valid identity or payload")
+ required_payload = frozenset({"target_profile", "prompt", "source_event_seq"})
if not required_payload <= frozenset(payload) or (
frozenset(payload) - required_payload - {"target_member_id"}
):
@@ -1215,9 +953,6 @@ def reconstruct_task_plan(
if match is None:
raise DiscussionReconstructionError("turn_id is not a Discussion coordinate")
source_event_seq = int(match.group("source"))
- round_index = int(match.group("round"))
- member_index = int(match.group("position"))
- seen_through_seq = int(match.group("seen"))
if payload.get("source_event_seq") != source_event_seq:
raise DiscussionReconstructionError("task source event does not match turn_id")
discussion = next(
@@ -1230,13 +965,8 @@ def reconstruct_task_plan(
)
if discussion is None:
raise DiscussionReconstructionError("task source user event is missing")
- if (
- identity.room_id != room.room_id
- or identity.thread_id != discussion.payload["thread_id"]
- ):
- raise DiscussionReconstructionError(
- "task identity does not match its room thread"
- )
+ if identity.room_id != room.room_id or identity.thread_id != discussion.payload["thread_id"]:
+ raise DiscussionReconstructionError("task identity does not match its room thread")
profile = payload.get("target_profile")
target_member_id = payload.get("target_member_id")
member = next(
@@ -1264,17 +994,13 @@ def reconstruct_task_plan(
room=room,
discussion_event=discussion,
member=member,
- member_index=member_index,
- round_index=round_index,
- seen_through_seq=seen_through_seq,
+ member_index=int(match.group("position")),
+ round_index=int(match.group("round")),
+ seen_through_seq=int(match.group("seen")),
prompt=prompt,
)
- if reconstructed.identity != identity or dict(reconstructed.payload) != dict(
- payload
- ):
- raise DiscussionReconstructionError(
- "driver task failed deterministic reconstruction"
- )
+ if reconstructed.identity != identity or dict(reconstructed.payload) != dict(payload):
+ raise DiscussionReconstructionError("driver task failed deterministic reconstruction")
return reconstructed
@@ -1301,12 +1027,10 @@ def plan_publication(
) -> PublicationPlan:
"""Plan idempotent room effects for one terminal driver task.
- A newer user event in the same thread supersedes a late result. The task
- remains terminal in driver state, but only a deterministic cancellation is
- published, preventing stale prose and its watermark from hiding the newer
- user message.
+ A newer user event in the same thread supersedes a late result: the task
+ stays terminal in driver state, but only a deterministic cancellation is
+ published so stale prose and its watermark cannot hide the newer message.
"""
-
room = validate_room(room_value, local_profiles=local_profiles)
validated = _validated_events(events, room=room)
if task.identity.room_id != room.room_id:
@@ -1320,9 +1044,7 @@ def plan_publication(
or not isinstance(execution_generation, int)
or execution_generation < 1
):
- raise DiscussionValidationError(
- "deferred publication requires an execution generation"
- )
+ raise DiscussionValidationError("deferred publication requires an execution generation")
newer_same_thread = any(
event.kind == "message.user"
@@ -1351,6 +1073,7 @@ def plan_publication(
"turn_id": task.identity.turn_id,
}
effects: list[EventPlan] = []
+ terminal_kind = f"turn.{effective_status}"
if effective_status == "settled":
text = _truncate_utf8_text(
@@ -1365,8 +1088,9 @@ def plan_publication(
"id": task.member.member_id,
"profile": task.member.profile,
}
- if task.member.target and task.member.target.get("kind") == "peer":
- member_actor["connection_id"] = task.member.target["peer_id"]
+ peer = _peer_target(task.member)
+ if peer:
+ member_actor["connection_id"] = peer["peer_id"]
if task.member.display_name:
member_actor["display_name"] = task.member.display_name
effects.append(
@@ -1388,18 +1112,9 @@ def plan_publication(
authority_epoch=room.authority_epoch,
)
)
- terminal_payload = {
- **common,
- "message_event_id": None if passed else message_event_id,
- "passed": passed,
- }
- terminal_kind = "turn.settled"
+ extra = {"message_event_id": None if passed else message_event_id, "passed": passed}
elif effective_status == "failed":
- error_text = _terminal_text(
- result,
- field="error",
- fallback="member turn failed",
- )
+ error_text = _terminal_text(result, field="error", fallback="member turn failed")
from tools.bot_failure_reasons import ALL_REASONS, classify_agent_error
supplied_reason = (
@@ -1408,48 +1123,29 @@ def plan_publication(
else ""
)
reason_code = (
- supplied_reason
- if supplied_reason in ALL_REASONS
- else classify_agent_error(error_text)
+ supplied_reason if supplied_reason in ALL_REASONS else classify_agent_error(error_text)
)
- terminal_payload = {
- **common,
- "error": error_text,
- "reason_code": reason_code,
- }
- terminal_kind = "turn.failed"
+ extra = {"error": error_text, "reason_code": reason_code}
elif effective_status == "cancelled":
- terminal_payload = {
- **common,
+ extra = {
"reason": (
"superseded_by_newer_user_event"
if newer_same_thread
- else _terminal_text(
- result,
- field="reason",
- fallback="member turn cancelled",
- )
+ else _terminal_text(result, field="reason", fallback="member turn cancelled")
),
}
- terminal_kind = "turn.cancelled"
else:
- terminal_payload = {
- **common,
+ extra = {
"execution_generation": execution_generation,
- "reason": _terminal_text(
- result,
- field="reason",
- fallback="member_unavailable",
- ),
+ "reason": _terminal_text(result, field="reason", fallback="member_unavailable"),
}
- terminal_kind = "turn.deferred"
effects.append(
EventPlan(
event_id=terminal_event_id,
kind=terminal_kind,
actor={"kind": "gateway", "id": room.gateway_id},
- payload=terminal_payload,
+ payload={**common, **extra},
authority_gateway_id=room.gateway_id,
authority_epoch=room.authority_epoch,
)
diff --git a/gateway/hosted_room_driver.py b/gateway/hosted_room_driver.py
index e2f836ca518..73ef3637bd7 100644
--- a/gateway/hosted_room_driver.py
+++ b/gateway/hosted_room_driver.py
@@ -1,13 +1,14 @@
"""Durable execution state for a same-gateway hosted room driver.
-This module owns only the driver lease and task state machine. It does not
-invoke models, touch sessions, or depend on the hosted-room event log. Callers
-provide both the database path and clock so recovery and fencing behavior can
-be tested without process-global state.
+Owns only the driver lease and task state machine: no model calls, no
+sessions, no dependency on the hosted-room event log. Callers supply the
+database path and clock so recovery and fencing are testable without
+process-global state.
"""
from __future__ import annotations
+import dataclasses
import hashlib
import json
import math
@@ -16,19 +17,13 @@ import sqlite3
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
-from typing import Any, Callable, Iterator, Literal
+from typing import Any, Callable, Iterator, Literal, get_args
Clock = Callable[[], float]
TaskStatus = Literal[
- "queued",
- "running",
- "settled",
- "failed",
- "cancelled",
- "indeterminate",
- "deferred",
- "stopping",
+ "queued", "running", "settled", "failed",
+ "cancelled", "indeterminate", "deferred", "stopping",
]
TerminalStatus = Literal["settled", "failed"]
@@ -38,82 +33,35 @@ MAX_RESULT_JSON_BYTES = 256 * 1024
TERMINAL_TASK_RETENTION_SECONDS = 30 * 24 * 60 * 60
MAX_RETAINED_TERMINAL_TASKS = 2048
MAX_TASK_PRUNE_BATCH = 1000
-TASK_STATUSES = frozenset({
- "queued",
- "running",
- "settled",
- "failed",
- "cancelled",
- "indeterminate",
- "deferred",
- "stopping",
-})
+TASK_STATUSES = frozenset(get_args(TaskStatus))
TERMINAL_STATUSES = frozenset({"settled", "failed", "cancelled"})
_IDENTIFIER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]*$")
-_TASK_PAYLOAD_REQUIRED_FIELDS = frozenset(
- {"target_profile", "prompt", "source_event_seq"}
-)
+_TASK_PAYLOAD_REQUIRED_FIELDS = frozenset({"target_profile", "prompt", "source_event_seq"})
_TASK_PAYLOAD_OPTIONAL_FIELDS = frozenset({"target_member_id"})
_LEASE_COLUMNS = frozenset({
- "room_id",
- "gateway_id",
- "authority_epoch",
- "process_generation",
- "lease_generation",
- "expires_at",
- "acquired_at",
- "updated_at",
- "released_at",
-})
-_TASK_COLUMNS = frozenset({
- "room_id",
- "task_id",
- "thread_id",
- "turn_id",
- "source_event_seq",
- "payload_json",
- "payload_digest",
- "status",
- "execution_generation",
- "cancel_generation",
- "run_gateway_id",
- "run_process_generation",
- "run_lease_generation",
- "cancel_id",
- "settlement_id",
- "settlement_status",
- "result_json",
- "created_at",
- "updated_at",
- "started_at",
- "terminal_at",
- "indeterminate_at",
+ "room_id", "gateway_id", "authority_epoch", "process_generation",
+ "lease_generation", "expires_at", "acquired_at", "updated_at", "released_at",
})
_TASK_COLUMN_ORDER = (
- "room_id",
- "task_id",
- "thread_id",
- "turn_id",
- "source_event_seq",
- "payload_json",
- "payload_digest",
- "status",
- "execution_generation",
- "cancel_generation",
- "run_gateway_id",
- "run_process_generation",
- "run_lease_generation",
- "cancel_id",
- "settlement_id",
- "settlement_status",
- "result_json",
- "created_at",
- "updated_at",
- "started_at",
- "terminal_at",
+ "room_id", "task_id", "thread_id", "turn_id", "source_event_seq",
+ "payload_json", "payload_digest", "status", "execution_generation",
+ "cancel_generation", "run_gateway_id", "run_process_generation",
+ "run_lease_generation", "cancel_id", "settlement_id", "settlement_status",
+ "result_json", "created_at", "updated_at", "started_at", "terminal_at",
"indeterminate_at",
)
+_TASK_COLUMNS = frozenset(_TASK_COLUMN_ORDER)
+_TASK_ORDER = "ORDER BY source_event_seq, created_at, task_id"
+_SELECT_LEASE = "SELECT * FROM hosted_room_driver_leases WHERE room_id=?"
+_TASK_INDEX_SQL = """CREATE INDEX {if_not_exists}idx_hosted_room_driver_tasks_status
+ ON hosted_room_driver_tasks(room_id, status, source_event_seq, created_at, task_id)"""
+# Terminal settlement of a task fenced on status + both generations.
+_SETTLE_FENCED_SQL = """UPDATE hosted_room_driver_tasks
+ SET status=?, settlement_id=?, settlement_status=?,
+ result_json=?, terminal_at=?, updated_at=?
+ WHERE room_id=? AND task_id=? AND status='{status}'
+ AND execution_generation=? AND cancel_generation=?"""
class DriverStateError(ValueError):
@@ -152,11 +100,7 @@ def _identifier(value: Any, *, label: str) -> str:
if not isinstance(value, str):
raise DriverValidationError(f"{label} must be a string")
value = value.strip()
- if (
- not value
- or len(value) > MAX_IDENTIFIER_CHARS
- or not _IDENTIFIER_RE.fullmatch(value)
- ):
+ if not value or len(value) > MAX_IDENTIFIER_CHARS or not _IDENTIFIER_RE.fullmatch(value):
raise DriverValidationError(f"invalid {label}")
return value
@@ -177,9 +121,7 @@ def _ttl(value: Any) -> float:
try:
ttl = float(value)
except (TypeError, ValueError, OverflowError) as exc:
- raise DriverValidationError(
- "ttl_seconds must be a finite positive number"
- ) from exc
+ raise DriverValidationError("ttl_seconds must be a finite positive number") from exc
if not math.isfinite(ttl) or ttl <= 0:
raise DriverValidationError("ttl_seconds must be a finite positive number")
return ttl
@@ -194,12 +136,7 @@ def _expiry(now: float, ttl: float) -> float:
def _canonical_json(value: Any) -> str:
try:
- encoded = json.dumps(
- value,
- ensure_ascii=True,
- sort_keys=True,
- separators=(",", ":"),
- )
+ encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(",", ":"))
except (TypeError, ValueError, RecursionError) as exc:
raise DriverValidationError("result must be JSON-serializable") from exc
if len(encoded.encode("utf-8")) > MAX_RESULT_JSON_BYTES:
@@ -216,20 +153,12 @@ def _authority_epoch(value: Any) -> int:
def _task_payload(value: Any) -> tuple[dict[str, Any], str, str]:
if not isinstance(value, dict):
raise DriverValidationError("payload must be an object")
- unknown = (
- set(value)
- - _TASK_PAYLOAD_REQUIRED_FIELDS
- - _TASK_PAYLOAD_OPTIONAL_FIELDS
- )
+ unknown = set(value) - _TASK_PAYLOAD_REQUIRED_FIELDS - _TASK_PAYLOAD_OPTIONAL_FIELDS
missing = _TASK_PAYLOAD_REQUIRED_FIELDS - set(value)
if unknown:
- raise DriverValidationError(
- f"unknown payload fields: {', '.join(sorted(unknown))}"
- )
+ raise DriverValidationError(f"unknown payload fields: {', '.join(sorted(unknown))}")
if missing:
- raise DriverValidationError(
- f"missing payload fields: {', '.join(sorted(missing))}"
- )
+ raise DriverValidationError(f"missing payload fields: {', '.join(sorted(missing))}")
target_profile = _identifier(value["target_profile"], label="target_profile")
prompt = value["prompt"]
@@ -256,12 +185,7 @@ def _task_payload(value: Any) -> tuple[dict[str, Any], str, str]:
normalized["target_member_id"] = _identifier(
value["target_member_id"], label="target_member_id"
)
- encoded = json.dumps(
- normalized,
- ensure_ascii=True,
- sort_keys=True,
- separators=(",", ":"),
- )
+ encoded = json.dumps(normalized, ensure_ascii=True, sort_keys=True, separators=(",", ":"))
digest = hashlib.sha256(encoded.encode("utf-8")).hexdigest()
return normalized, encoded, digest
@@ -277,11 +201,7 @@ class TaskIdentity:
def __post_init__(self) -> None:
for field in ("room_id", "task_id", "thread_id", "turn_id"):
- object.__setattr__(
- self,
- field,
- _identifier(getattr(self, field), label=field),
- )
+ object.__setattr__(self, field, _identifier(getattr(self, field), label=field))
@dataclass(frozen=True)
@@ -367,12 +287,7 @@ def _initialize_schema(conn: sqlite3.Connection) -> None:
)
_create_task_table(conn)
_validate_schema(conn)
- conn.execute(
- """CREATE INDEX IF NOT EXISTS idx_hosted_room_driver_tasks_status
- ON hosted_room_driver_tasks(
- room_id, status, source_event_seq, created_at, task_id
- )"""
- )
+ conn.execute(_TASK_INDEX_SQL.format(if_not_exists="IF NOT EXISTS "))
def _validate_schema(conn: sqlite3.Connection) -> None:
@@ -404,8 +319,7 @@ def _schema_objects_exist(conn: sqlite3.Connection) -> bool:
'hosted_room_driver_leases', 'hosted_room_driver_tasks'
)"""
).fetchall()
- tables = {row[0] for row in rows}
- if tables != {"hosted_room_driver_leases", "hosted_room_driver_tasks"}:
+ if {row[0] for row in rows} != {"hosted_room_driver_leases", "hosted_room_driver_tasks"}:
return False
index = conn.execute(
"""SELECT 1 FROM sqlite_master
@@ -416,8 +330,7 @@ def _schema_objects_exist(conn: sqlite3.Connection) -> bool:
def _task_schema_supports_current_statuses(conn: sqlite3.Connection) -> bool:
row = conn.execute(
- """SELECT sql FROM sqlite_master
- WHERE type='table' AND name='hosted_room_driver_tasks'"""
+ "SELECT sql FROM sqlite_master WHERE type='table' AND name='hosted_room_driver_tasks'"
).fetchone()
sql = str(row[0] or "").lower() if row else ""
return "'stopping'" in sql and "'deferred'" in sql
@@ -433,15 +346,8 @@ def _migrate_task_status_constraint(conn: sqlite3.Connection) -> None:
SELECT {columns} FROM hosted_room_driver_tasks"""
)
conn.execute("DROP TABLE hosted_room_driver_tasks")
- conn.execute(
- "ALTER TABLE hosted_room_driver_tasks_next RENAME TO hosted_room_driver_tasks"
- )
- conn.execute(
- """CREATE INDEX idx_hosted_room_driver_tasks_status
- ON hosted_room_driver_tasks(
- room_id, status, source_event_seq, created_at, task_id
- )"""
- )
+ conn.execute("ALTER TABLE hosted_room_driver_tasks_next RENAME TO hosted_room_driver_tasks")
+ conn.execute(_TASK_INDEX_SQL.format(if_not_exists=""))
def _connect(db_path: Path | str) -> sqlite3.Connection:
@@ -488,9 +394,7 @@ def _transaction(db_path: Path | str) -> Iterator[sqlite3.Connection]:
conn.close()
-def _lease_from_row(
- row: sqlite3.Row | dict[str, Any], *, reclaimed: bool = False
-) -> DriverLease:
+def _lease_from_row(row: sqlite3.Row | dict[str, Any], *, reclaimed: bool = False) -> DriverLease:
return DriverLease(
room_id=row["room_id"],
gateway_id=row["gateway_id"],
@@ -511,6 +415,10 @@ def _task_identity_from_row(row: sqlite3.Row) -> TaskIdentity:
)
+def _optional(cast: Callable[[Any], Any], value: Any) -> Any:
+ return cast(value) if value is not None else None
+
+
def _task_from_row(row: sqlite3.Row, *, idempotent: bool = False) -> dict[str, Any]:
try:
raw_payload = json.loads(row["payload_json"])
@@ -523,7 +431,6 @@ def _task_from_row(row: sqlite3.Row, *, idempotent: bool = False) -> dict[str, A
or payload["source_event_seq"] != int(row["source_event_seq"])
):
raise TaskConflictError("stored task payload failed its integrity check")
- result = json.loads(row["result_json"]) if row["result_json"] is not None else None
return {
"identity": _task_identity_from_row(row),
"payload": payload,
@@ -533,36 +440,23 @@ def _task_from_row(row: sqlite3.Row, *, idempotent: bool = False) -> dict[str, A
"cancel_generation": int(row["cancel_generation"]),
"run_gateway_id": row["run_gateway_id"],
"run_process_generation": row["run_process_generation"],
- "run_lease_generation": (
- int(row["run_lease_generation"])
- if row["run_lease_generation"] is not None
- else None
- ),
+ "run_lease_generation": _optional(int, row["run_lease_generation"]),
"cancel_id": row["cancel_id"],
"settlement_id": row["settlement_id"],
"settlement_status": row["settlement_status"],
- "result": result,
+ "result": _optional(json.loads, row["result_json"]),
"created_at": float(row["created_at"]),
"updated_at": float(row["updated_at"]),
- "started_at": (
- float(row["started_at"]) if row["started_at"] is not None else None
- ),
- "terminal_at": (
- float(row["terminal_at"]) if row["terminal_at"] is not None else None
- ),
- "indeterminate_at": (
- float(row["indeterminate_at"])
- if row["indeterminate_at"] is not None
- else None
- ),
+ "started_at": _optional(float, row["started_at"]),
+ "terminal_at": _optional(float, row["terminal_at"]),
+ "indeterminate_at": _optional(float, row["indeterminate_at"]),
"idempotent": idempotent,
}
def _load_task(conn: sqlite3.Connection, identity: TaskIdentity) -> sqlite3.Row:
row = conn.execute(
- """SELECT * FROM hosted_room_driver_tasks
- WHERE room_id=? AND task_id=?""",
+ "SELECT * FROM hosted_room_driver_tasks WHERE room_id=? AND task_id=?",
(identity.room_id, identity.task_id),
).fetchone()
if row is None:
@@ -572,6 +466,14 @@ def _load_task(conn: sqlite3.Connection, identity: TaskIdentity) -> sqlite3.Row:
return row
+def _tasks_in_order(
+ conn: sqlite3.Connection, room_id: str, status: str | None = None
+) -> list[sqlite3.Row]:
+ where, params = ("", (room_id,)) if status is None else (" AND status=?", (room_id, status))
+ sql = f"SELECT * FROM hosted_room_driver_tasks WHERE room_id=?{where} {_TASK_ORDER}"
+ return conn.execute(sql, params).fetchall()
+
+
def _load_active_room(conn: sqlite3.Connection, room_id: str) -> sqlite3.Row:
try:
row = conn.execute(
@@ -591,43 +493,38 @@ def _load_active_room(conn: sqlite3.Connection, room_id: str) -> sqlite3.Row:
def _require_room_authority(
- conn: sqlite3.Connection,
- *,
- room_id: str,
- gateway_id: str,
- authority_epoch: int,
+ conn: sqlite3.Connection, *, room_id: str, gateway_id: str, authority_epoch: int
) -> sqlite3.Row:
room = _load_active_room(conn, room_id)
- if (
- room["authority_gateway_id"] != gateway_id
- or int(room["authority_epoch"]) != authority_epoch
- ):
+ if room["authority_gateway_id"] != gateway_id or int(room["authority_epoch"]) != authority_epoch:
raise StaleLeaseError("hosted room authority changed")
return room
-def _require_active_lease(
- conn: sqlite3.Connection,
- lease: DriverLease,
- *,
- now: float,
-) -> sqlite3.Row:
- _require_room_authority(
+def _require_lease_authority(conn: sqlite3.Connection, lease: DriverLease) -> sqlite3.Row:
+ return _require_room_authority(
conn,
room_id=lease.room_id,
gateway_id=lease.gateway_id,
authority_epoch=lease.authority_epoch,
)
- row = conn.execute(
- "SELECT * FROM hosted_room_driver_leases WHERE room_id=?",
- (lease.room_id,),
- ).fetchone()
+
+
+def _lease_row_matches(row: sqlite3.Row | None, lease: DriverLease) -> bool:
+ return (
+ row is not None
+ and row["gateway_id"] == lease.gateway_id
+ and int(row["authority_epoch"]) == lease.authority_epoch
+ and row["process_generation"] == lease.process_generation
+ and int(row["lease_generation"]) == lease.lease_generation
+ )
+
+
+def _require_active_lease(conn: sqlite3.Connection, lease: DriverLease, *, now: float) -> sqlite3.Row:
+ _require_lease_authority(conn, lease)
+ row = conn.execute(_SELECT_LEASE, (lease.room_id,)).fetchone()
if (
- row is None
- or row["gateway_id"] != lease.gateway_id
- or int(row["authority_epoch"]) != lease.authority_epoch
- or row["process_generation"] != lease.process_generation
- or int(row["lease_generation"]) != lease.lease_generation
+ not _lease_row_matches(row, lease)
or row["released_at"] is not None
or float(row["expires_at"]) <= now
):
@@ -635,6 +532,80 @@ def _require_active_lease(
return row
+def _check_same_room(lease: DriverLease, identity: TaskIdentity) -> None:
+ if lease.room_id != identity.room_id:
+ raise DriverValidationError("lease and task belong to different rooms")
+
+
+def _cancel_generation(value: int) -> int:
+ if not isinstance(value, int) or value < 0:
+ raise DriverValidationError("expected_cancel_generation must be non-negative")
+ return value
+
+
+def _expected_generations(
+ lease: DriverLease, identity: TaskIdentity, execution_generation: int, cancel_generation: int
+) -> None:
+ _check_same_room(lease, identity)
+ if not isinstance(execution_generation, int) or execution_generation < 1:
+ raise DriverValidationError("expected_execution_generation must be a positive integer")
+ _cancel_generation(cancel_generation)
+
+
+def _terminal_settlement_id(settlement_id: Any, status: Any) -> str:
+ settlement_id = _identifier(settlement_id, label="settlement_id")
+ if status not in {"settled", "failed"}:
+ raise DriverValidationError("status must be 'settled' or 'failed'")
+ return settlement_id
+
+
+def _existing_settlement(
+ row: sqlite3.Row, settlement_id: str, status: str, result_json: str
+) -> dict[str, Any] | None:
+ """Return the idempotent replay of an identical settlement, or raise on a different one."""
+ if row["settlement_id"] is None:
+ return None
+ if (
+ row["settlement_id"] == settlement_id
+ and row["settlement_status"] == status
+ and row["result_json"] == result_json
+ ):
+ return _task_from_row(row, idempotent=True)
+ raise TaskConflictError("task already has a different terminal settlement")
+
+
+def _require_generations(
+ row: sqlite3.Row, status: str, execution_generation: int, cancel_generation: int, stale: str
+) -> None:
+ if (
+ row["status"] != status
+ or int(row["execution_generation"]) != execution_generation
+ or int(row["cancel_generation"]) != cancel_generation
+ ):
+ raise StaleTaskError(stale)
+
+
+def _fenced_task(
+ conn: sqlite3.Connection, lease: DriverLease, identity: TaskIdentity, now: float
+) -> sqlite3.Row:
+ _require_active_lease(conn, lease, now=now)
+ return _load_task(conn, identity)
+
+
+def _commit_task(
+ conn: sqlite3.Connection,
+ identity: TaskIdentity,
+ sql: str,
+ params: tuple[Any, ...],
+ *,
+ stale: str,
+) -> dict[str, Any]:
+ """Apply one fenced UPDATE that must hit exactly one row, then reload the task."""
+ if conn.execute(sql, params).rowcount != 1:
+ raise StaleTaskError(stale)
+ return _task_from_row(_load_task(conn, identity))
+
+
def acquire_lease(
db_path: Path | str,
*,
@@ -649,25 +620,16 @@ def acquire_lease(
room_id = _identifier(room_id, label="room_id")
gateway_id = _identifier(gateway_id, label="gateway_id")
authority_epoch = _authority_epoch(authority_epoch)
- process_generation = _identifier(
- process_generation,
- label="process_generation",
- )
+ process_generation = _identifier(process_generation, label="process_generation")
ttl_seconds = _ttl(ttl_seconds)
now = _timestamp(clock)
expires_at = _expiry(now, ttl_seconds)
with _transaction(db_path) as conn:
_require_room_authority(
- conn,
- room_id=room_id,
- gateway_id=gateway_id,
- authority_epoch=authority_epoch,
+ conn, room_id=room_id, gateway_id=gateway_id, authority_epoch=authority_epoch
)
- row = conn.execute(
- "SELECT * FROM hosted_room_driver_leases WHERE room_id=?",
- (room_id,),
- ).fetchone()
+ row = conn.execute(_SELECT_LEASE, (room_id,)).fetchone()
if row is None:
conn.execute(
"""INSERT INTO hosted_room_driver_leases (
@@ -675,29 +637,15 @@ def acquire_lease(
lease_generation, expires_at, acquired_at,
updated_at, released_at
) VALUES (?, ?, ?, ?, 1, ?, ?, ?, NULL)""",
- (
- room_id,
- gateway_id,
- authority_epoch,
- process_generation,
- expires_at,
- now,
- now,
- ),
+ (room_id, gateway_id, authority_epoch, process_generation, expires_at, now, now),
)
- row = conn.execute(
- "SELECT * FROM hosted_room_driver_leases WHERE room_id=?",
- (room_id,),
- ).fetchone()
- return _lease_from_row(row)
+ return _lease_from_row(conn.execute(_SELECT_LEASE, (room_id,)).fetchone())
- if (
- row["gateway_id"] == gateway_id
- and int(row["authority_epoch"]) == authority_epoch
- and row["process_generation"] == process_generation
- and row["released_at"] is None
- and float(row["expires_at"]) > now
- ):
+ same_authority = (
+ row["gateway_id"] == gateway_id and int(row["authority_epoch"]) == authority_epoch
+ )
+ live = row["released_at"] is None and float(row["expires_at"]) > now
+ if same_authority and row["process_generation"] == process_generation and live:
renewed_expiry = max(float(row["expires_at"]), expires_at)
conn.execute(
"""UPDATE hosted_room_driver_leases
@@ -705,22 +653,10 @@ def acquire_lease(
WHERE room_id=? AND lease_generation=?""",
(renewed_expiry, now, room_id, int(row["lease_generation"])),
)
- current = dict(row)
- current["expires_at"] = renewed_expiry
- return _lease_from_row(current)
-
- same_authority = (
- row["gateway_id"] == gateway_id
- and int(row["authority_epoch"]) == authority_epoch
- )
- if (
- same_authority
- and row["released_at"] is None
- and float(row["expires_at"]) > now
- ):
+ return _lease_from_row({**dict(row), "expires_at": renewed_expiry})
+ if same_authority and live:
raise LeaseHeldError("room driver lease is held by another generation")
- previous_generation = int(row["lease_generation"])
updated = conn.execute(
"""UPDATE hosted_room_driver_leases
SET gateway_id=?, authority_epoch=?, process_generation=?,
@@ -732,34 +668,18 @@ def acquire_lease(
OR released_at IS NOT NULL OR expires_at <= ?
)""",
(
- gateway_id,
- authority_epoch,
- process_generation,
- expires_at,
- now,
- now,
- room_id,
- previous_generation,
- gateway_id,
- authority_epoch,
- now,
+ gateway_id, authority_epoch, process_generation, expires_at, now, now,
+ room_id, int(row["lease_generation"]), gateway_id, authority_epoch, now,
),
)
if updated.rowcount != 1:
raise LeaseHeldError("room driver lease changed during acquisition")
- current = conn.execute(
- "SELECT * FROM hosted_room_driver_leases WHERE room_id=?",
- (room_id,),
- ).fetchone()
+ current = conn.execute(_SELECT_LEASE, (room_id,)).fetchone()
return _lease_from_row(current, reclaimed=True)
def renew_lease(
- db_path: Path | str,
- lease: DriverLease,
- *,
- ttl_seconds: Any,
- clock: Clock,
+ db_path: Path | str, lease: DriverLease, *, ttl_seconds: Any, clock: Clock
) -> DriverLease:
"""Renew the exact active lease generation or fail closed."""
ttl_seconds = _ttl(ttl_seconds)
@@ -774,86 +694,45 @@ def renew_lease(
WHERE room_id=? AND gateway_id=? AND process_generation=?
AND lease_generation=? AND released_at IS NULL AND expires_at > ?""",
(
- expires_at,
- now,
- lease.room_id,
- lease.gateway_id,
- lease.process_generation,
- lease.lease_generation,
- now,
+ expires_at, now, lease.room_id, lease.gateway_id,
+ lease.process_generation, lease.lease_generation, now,
),
)
if updated.rowcount != 1:
raise StaleLeaseError("driver lease changed during renewal")
- return DriverLease(
- room_id=lease.room_id,
- gateway_id=lease.gateway_id,
- authority_epoch=lease.authority_epoch,
- process_generation=lease.process_generation,
- lease_generation=lease.lease_generation,
- expires_at=expires_at,
- )
+ return dataclasses.replace(lease, expires_at=expires_at, reclaimed=False)
-def release_lease(
- db_path: Path | str,
- lease: DriverLease,
- *,
- clock: Clock,
-) -> dict[str, Any]:
+def release_lease(db_path: Path | str, lease: DriverLease, *, clock: Clock) -> dict[str, Any]:
"""Release the exact active lease generation idempotently."""
now = _timestamp(clock)
with _transaction(db_path) as conn:
- _require_room_authority(
- conn,
- room_id=lease.room_id,
- gateway_id=lease.gateway_id,
- authority_epoch=lease.authority_epoch,
- )
- row = conn.execute(
- "SELECT * FROM hosted_room_driver_leases WHERE room_id=?",
- (lease.room_id,),
- ).fetchone()
- if (
- row is None
- or row["gateway_id"] != lease.gateway_id
- or int(row["authority_epoch"]) != lease.authority_epoch
- or row["process_generation"] != lease.process_generation
- or int(row["lease_generation"]) != lease.lease_generation
- ):
+ _require_lease_authority(conn, lease)
+ row = conn.execute(_SELECT_LEASE, (lease.room_id,)).fetchone()
+ if not _lease_row_matches(row, lease):
raise StaleLeaseError("driver lease is stale")
if row["released_at"] is not None:
return {"lease": _lease_from_row(row), "idempotent": True}
if float(row["expires_at"]) <= now:
raise StaleLeaseError("driver lease expired before release")
running = conn.execute(
- """SELECT 1 FROM hosted_room_driver_tasks
- WHERE room_id=? AND status='running' LIMIT 1""",
+ "SELECT 1 FROM hosted_room_driver_tasks WHERE room_id=? AND status='running' LIMIT 1",
(lease.room_id,),
).fetchone()
if running is not None:
- raise InvalidTaskTransitionError(
- "cannot release a room lease while tasks are running"
- )
+ raise InvalidTaskTransitionError("cannot release a room lease while tasks are running")
conn.execute(
"""UPDATE hosted_room_driver_leases
SET expires_at=?, updated_at=?, released_at=?
WHERE room_id=? AND lease_generation=?""",
(now, now, now, lease.room_id, lease.lease_generation),
)
- current = dict(row)
- current["expires_at"] = now
- current["updated_at"] = now
- current["released_at"] = now
+ current = {**dict(row), "expires_at": now, "updated_at": now, "released_at": now}
return {"lease": _lease_from_row(current), "idempotent": False}
def admit_task(
- db_path: Path | str,
- identity: TaskIdentity,
- *,
- payload: Any,
- clock: Clock,
+ db_path: Path | str, identity: TaskIdentity, *, payload: Any, clock: Clock
) -> dict[str, Any]:
"""Persist a queued task, or return the identical admission."""
normalized_payload, payload_json, payload_digest = _task_payload(payload)
@@ -861,8 +740,7 @@ def admit_task(
with _transaction(db_path) as conn:
_load_active_room(conn, identity.room_id)
existing = conn.execute(
- """SELECT * FROM hosted_room_driver_tasks
- WHERE room_id=? AND task_id=?""",
+ "SELECT * FROM hosted_room_driver_tasks WHERE room_id=? AND task_id=?",
(identity.room_id, identity.task_id),
).fetchone()
if existing is not None:
@@ -872,9 +750,7 @@ def admit_task(
existing["payload_digest"] != payload_digest
or existing["payload_json"] != payload_json
):
- raise TaskConflictError(
- "task_id is already bound to a different payload"
- )
+ raise TaskConflictError("task_id is already bound to a different payload")
return _task_from_row(existing, idempotent=True)
turn = conn.execute(
@@ -893,19 +769,11 @@ def admit_task(
created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, 'queued', 0, 0, ?, ?)""",
(
- identity.room_id,
- identity.task_id,
- identity.thread_id,
- identity.turn_id,
- normalized_payload["source_event_seq"],
- payload_json,
- payload_digest,
- now,
- now,
+ identity.room_id, identity.task_id, identity.thread_id, identity.turn_id,
+ normalized_payload["source_event_seq"], payload_json, payload_digest, now, now,
),
)
- row = _load_task(conn, identity)
- return _task_from_row(row)
+ return _task_from_row(_load_task(conn, identity))
def start_task(
@@ -917,27 +785,19 @@ def start_task(
clock: Clock,
) -> TaskAttempt:
"""Move one queued task to running under the current driver lease."""
- if lease.room_id != identity.room_id:
- raise DriverValidationError("lease and task belong to different rooms")
- if (
- not isinstance(expected_cancel_generation, int)
- or expected_cancel_generation < 0
- ):
- raise DriverValidationError("expected_cancel_generation must be non-negative")
+ _check_same_room(lease, identity)
+ _cancel_generation(expected_cancel_generation)
now = _timestamp(clock)
with _transaction(db_path) as conn:
- _require_active_lease(conn, lease, now=now)
- row = _load_task(conn, identity)
+ row = _fenced_task(conn, lease, identity, now)
if int(row["cancel_generation"]) != expected_cancel_generation:
raise StaleTaskError("task cancellation generation changed")
if row["status"] != "queued":
- raise InvalidTaskTransitionError(
- f"cannot start task in state '{row['status']}'"
- )
+ raise InvalidTaskTransitionError(f"cannot start task in state '{row['status']}'")
unresolved = conn.execute(
- """SELECT task_id, status FROM hosted_room_driver_tasks
+ f"""SELECT task_id, status FROM hosted_room_driver_tasks
WHERE room_id=? AND status IN ('running', 'indeterminate', 'stopping')
- ORDER BY source_event_seq, created_at, task_id LIMIT 1""",
+ {_TASK_ORDER} LIMIT 1""",
(identity.room_id,),
).fetchone()
if unresolved is not None:
@@ -945,15 +805,12 @@ def start_task(
"room recovery must resolve the prior task before starting new work"
)
next_queued = conn.execute(
- """SELECT task_id FROM hosted_room_driver_tasks
- WHERE room_id=? AND status='queued'
- ORDER BY source_event_seq, created_at, task_id LIMIT 1""",
+ f"""SELECT task_id FROM hosted_room_driver_tasks
+ WHERE room_id=? AND status='queued' {_TASK_ORDER} LIMIT 1""",
(identity.room_id,),
).fetchone()
if next_queued is None or next_queued["task_id"] != identity.task_id:
- raise InvalidTaskTransitionError(
- "task is not next in the hosted room event order"
- )
+ raise InvalidTaskTransitionError("task is not next in the hosted room event order")
execution_generation = int(row["execution_generation"]) + 1
updated = conn.execute(
"""UPDATE hosted_room_driver_tasks
@@ -963,14 +820,8 @@ def start_task(
WHERE room_id=? AND task_id=? AND status='queued'
AND cancel_generation=?""",
(
- execution_generation,
- lease.gateway_id,
- lease.process_generation,
- lease.lease_generation,
- now,
- now,
- identity.room_id,
- identity.task_id,
+ execution_generation, lease.gateway_id, lease.process_generation,
+ lease.lease_generation, now, now, identity.room_id, identity.task_id,
expected_cancel_generation,
),
)
@@ -994,36 +845,32 @@ def settle_task(
clock: Clock,
) -> dict[str, Any]:
"""Commit one terminal result if every lease and task fence still matches."""
- settlement_id = _identifier(settlement_id, label="settlement_id")
- if status not in {"settled", "failed"}:
- raise DriverValidationError("status must be 'settled' or 'failed'")
+ settlement_id = _terminal_settlement_id(settlement_id, status)
result_json = _canonical_json(result)
now = _timestamp(clock)
+ lease = attempt.lease
with _transaction(db_path) as conn:
row = _load_task(conn, attempt.identity)
- if row["settlement_id"] is not None:
- if (
- row["settlement_id"] == settlement_id
- and row["settlement_status"] == status
- and row["result_json"] == result_json
- ):
- return _task_from_row(row, idempotent=True)
- raise TaskConflictError("task already has a different terminal settlement")
+ existing = _existing_settlement(row, settlement_id, status, result_json)
+ if existing is not None:
+ return existing
- _require_active_lease(conn, attempt.lease, now=now)
+ _require_active_lease(conn, lease, now=now)
expected = (
row["status"] == "running"
and int(row["execution_generation"]) == attempt.execution_generation
and int(row["cancel_generation"]) == attempt.cancel_generation
- and row["run_gateway_id"] == attempt.lease.gateway_id
- and row["run_process_generation"] == attempt.lease.process_generation
- and int(row["run_lease_generation"]) == attempt.lease.lease_generation
+ and row["run_gateway_id"] == lease.gateway_id
+ and row["run_process_generation"] == lease.process_generation
+ and int(row["run_lease_generation"]) == lease.lease_generation
)
if not expected:
raise StaleTaskError("task attempt is stale or cancelled")
- updated = conn.execute(
+ return _commit_task(
+ conn,
+ attempt.identity,
"""UPDATE hosted_room_driver_tasks
SET status=?, settlement_id=?, settlement_status=?,
result_json=?, terminal_at=?, updated_at=?
@@ -1032,24 +879,13 @@ def settle_task(
AND run_gateway_id=? AND run_process_generation=?
AND run_lease_generation=?""",
(
- status,
- settlement_id,
- status,
- result_json,
- now,
- now,
- attempt.identity.room_id,
- attempt.identity.task_id,
- attempt.execution_generation,
- attempt.cancel_generation,
- attempt.lease.gateway_id,
- attempt.lease.process_generation,
- attempt.lease.lease_generation,
+ status, settlement_id, status, result_json, now, now,
+ attempt.identity.room_id, attempt.identity.task_id,
+ attempt.execution_generation, attempt.cancel_generation,
+ lease.gateway_id, lease.process_generation, lease.lease_generation,
),
+ stale="task changed during settlement",
)
- if updated.rowcount != 1:
- raise StaleTaskError("task changed during settlement")
- return _task_from_row(_load_task(conn, attempt.identity))
def settle_stopping_task(
@@ -1065,46 +901,28 @@ def settle_stopping_task(
clock: Clock,
) -> dict[str, Any]:
"""Commit a completion that won the race with an unacknowledged Stop."""
- settlement_id = _identifier(settlement_id, label="settlement_id")
- if status not in {"settled", "failed"}:
- raise DriverValidationError("status must be 'settled' or 'failed'")
+ settlement_id = _terminal_settlement_id(settlement_id, status)
if expected_execution_generation < 1 or expected_cancel_generation < 1:
raise DriverValidationError("stopping settlement generations are invalid")
result_json = _canonical_json(result)
now = _timestamp(clock)
with _transaction(db_path) as conn:
row = _load_task(conn, identity)
- if row["settlement_id"] is not None:
- if (
- row["settlement_id"] == settlement_id
- and row["settlement_status"] == status
- and row["result_json"] == result_json
- ):
- return _task_from_row(row, idempotent=True)
- raise TaskConflictError("task already has a different terminal settlement")
+ existing = _existing_settlement(row, settlement_id, status, result_json)
+ if existing is not None:
+ return existing
_require_active_lease(conn, lease, now=now)
- updated = conn.execute(
- """UPDATE hosted_room_driver_tasks
- SET status=?, settlement_id=?, settlement_status=?,
- result_json=?, terminal_at=?, updated_at=?
- WHERE room_id=? AND task_id=? AND status='stopping'
- AND execution_generation=? AND cancel_generation=?""",
+ return _commit_task(
+ conn,
+ identity,
+ _SETTLE_FENCED_SQL.format(status="stopping"),
(
- status,
- settlement_id,
- status,
- result_json,
- now,
- now,
- identity.room_id,
- identity.task_id,
- expected_execution_generation,
- expected_cancel_generation,
+ status, settlement_id, status, result_json, now, now,
+ identity.room_id, identity.task_id,
+ expected_execution_generation, expected_cancel_generation,
),
+ stale="task completion lost the stop race",
)
- if updated.rowcount != 1:
- raise StaleTaskError("task completion lost the stop race")
- return _task_from_row(_load_task(conn, identity))
def resolve_indeterminate_task(
@@ -1120,65 +938,33 @@ def resolve_indeterminate_task(
clock: Clock,
) -> dict[str, Any]:
"""Commit a verified historical receipt under the current room lease."""
- if lease.room_id != identity.room_id:
- raise DriverValidationError("lease and task belong to different rooms")
- if (
- not isinstance(expected_execution_generation, int)
- or expected_execution_generation < 1
- ):
- raise DriverValidationError(
- "expected_execution_generation must be a positive integer"
- )
- if (
- not isinstance(expected_cancel_generation, int)
- or expected_cancel_generation < 0
- ):
- raise DriverValidationError("expected_cancel_generation must be non-negative")
- settlement_id = _identifier(settlement_id, label="settlement_id")
- if status not in {"settled", "failed"}:
- raise DriverValidationError("status must be 'settled' or 'failed'")
+ _expected_generations(
+ lease, identity, expected_execution_generation, expected_cancel_generation
+ )
+ settlement_id = _terminal_settlement_id(settlement_id, status)
result_json = _canonical_json(result)
now = _timestamp(clock)
with _transaction(db_path) as conn:
- _require_active_lease(conn, lease, now=now)
- row = _load_task(conn, identity)
- if row["settlement_id"] is not None:
- if (
- row["settlement_id"] == settlement_id
- and row["settlement_status"] == status
- and row["result_json"] == result_json
- ):
- return _task_from_row(row, idempotent=True)
- raise TaskConflictError("task already has a different terminal settlement")
- if (
- row["status"] != "indeterminate"
- or int(row["execution_generation"]) != expected_execution_generation
- or int(row["cancel_generation"]) != expected_cancel_generation
- ):
- raise StaleTaskError("indeterminate task generation changed")
- updated = conn.execute(
- """UPDATE hosted_room_driver_tasks
- SET status=?, settlement_id=?, settlement_status=?,
- result_json=?, terminal_at=?, updated_at=?
- WHERE room_id=? AND task_id=? AND status='indeterminate'
- AND execution_generation=? AND cancel_generation=?""",
+ row = _fenced_task(conn, lease, identity, now)
+ existing = _existing_settlement(row, settlement_id, status, result_json)
+ if existing is not None:
+ return existing
+ _require_generations(
+ row, "indeterminate", expected_execution_generation, expected_cancel_generation,
+ "indeterminate task generation changed",
+ )
+ return _commit_task(
+ conn,
+ identity,
+ _SETTLE_FENCED_SQL.format(status="indeterminate"),
(
- status,
- settlement_id,
- status,
- result_json,
- now,
- now,
- identity.room_id,
- identity.task_id,
- expected_execution_generation,
- expected_cancel_generation,
+ status, settlement_id, status, result_json, now, now,
+ identity.room_id, identity.task_id,
+ expected_execution_generation, expected_cancel_generation,
),
+ stale="indeterminate task changed during reconciliation",
)
- if updated.rowcount != 1:
- raise StaleTaskError("indeterminate task changed during reconciliation")
- return _task_from_row(_load_task(conn, identity))
def resolve_indeterminate_cancellation(
@@ -1192,53 +978,34 @@ def resolve_indeterminate_cancellation(
clock: Clock,
) -> dict[str, Any]:
"""Commit a verified terminal cancellation for an uncertain attempt."""
- if lease.room_id != identity.room_id:
- raise DriverValidationError("lease and task belong to different rooms")
- if (
- not isinstance(expected_execution_generation, int)
- or expected_execution_generation < 1
- ):
- raise DriverValidationError(
- "expected_execution_generation must be a positive integer"
- )
- if (
- not isinstance(expected_cancel_generation, int)
- or expected_cancel_generation < 0
- ):
- raise DriverValidationError("expected_cancel_generation must be non-negative")
+ _expected_generations(
+ lease, identity, expected_execution_generation, expected_cancel_generation
+ )
cancel_id = _identifier(cancel_id, label="cancel_id")
now = _timestamp(clock)
with _transaction(db_path) as conn:
- _require_active_lease(conn, lease, now=now)
- row = _load_task(conn, identity)
+ row = _fenced_task(conn, lease, identity, now)
if row["status"] == "cancelled" and row["cancel_id"] == cancel_id:
return _task_from_row(row, idempotent=True)
- if (
- row["status"] != "indeterminate"
- or int(row["execution_generation"]) != expected_execution_generation
- or int(row["cancel_generation"]) != expected_cancel_generation
- ):
- raise StaleTaskError("indeterminate cancellation proof is stale")
- updated = conn.execute(
+ _require_generations(
+ row, "indeterminate", expected_execution_generation, expected_cancel_generation,
+ "indeterminate cancellation proof is stale",
+ )
+ return _commit_task(
+ conn,
+ identity,
"""UPDATE hosted_room_driver_tasks
SET status='cancelled', cancel_generation=?, cancel_id=?,
terminal_at=?, updated_at=?
WHERE room_id=? AND task_id=? AND status='indeterminate'
AND execution_generation=? AND cancel_generation=?""",
(
- expected_cancel_generation + 1,
- cancel_id,
- now,
- now,
- identity.room_id,
- identity.task_id,
- expected_execution_generation,
- expected_cancel_generation,
+ expected_cancel_generation + 1, cancel_id, now, now,
+ identity.room_id, identity.task_id,
+ expected_execution_generation, expected_cancel_generation,
),
+ stale="indeterminate cancellation proof lost its fence",
)
- if updated.rowcount != 1:
- raise StaleTaskError("indeterminate cancellation proof lost its fence")
- return _task_from_row(_load_task(conn, identity))
def requeue_indeterminate_task(
@@ -1251,31 +1018,19 @@ def requeue_indeterminate_task(
clock: Clock,
) -> dict[str, Any]:
"""Explicitly retry uncertain work after an operator accepts at-least-once risk."""
- if lease.room_id != identity.room_id:
- raise DriverValidationError("lease and task belong to different rooms")
- if (
- not isinstance(expected_execution_generation, int)
- or expected_execution_generation < 1
- ):
- raise DriverValidationError(
- "expected_execution_generation must be a positive integer"
- )
- if (
- not isinstance(expected_cancel_generation, int)
- or expected_cancel_generation < 0
- ):
- raise DriverValidationError("expected_cancel_generation must be non-negative")
+ _expected_generations(
+ lease, identity, expected_execution_generation, expected_cancel_generation
+ )
now = _timestamp(clock)
with _transaction(db_path) as conn:
- _require_active_lease(conn, lease, now=now)
- row = _load_task(conn, identity)
- if (
- row["status"] != "indeterminate"
- or int(row["execution_generation"]) != expected_execution_generation
- or int(row["cancel_generation"]) != expected_cancel_generation
- ):
- raise StaleTaskError("indeterminate task generation changed")
- updated = conn.execute(
+ row = _fenced_task(conn, lease, identity, now)
+ _require_generations(
+ row, "indeterminate", expected_execution_generation, expected_cancel_generation,
+ "indeterminate task generation changed",
+ )
+ return _commit_task(
+ conn,
+ identity,
"""UPDATE hosted_room_driver_tasks
SET status='queued', run_gateway_id=NULL,
run_process_generation=NULL, run_lease_generation=NULL,
@@ -1283,16 +1038,11 @@ def requeue_indeterminate_task(
WHERE room_id=? AND task_id=? AND status='indeterminate'
AND execution_generation=? AND cancel_generation=?""",
(
- now,
- identity.room_id,
- identity.task_id,
- expected_execution_generation,
- expected_cancel_generation,
+ now, identity.room_id, identity.task_id,
+ expected_execution_generation, expected_cancel_generation,
),
+ stale="indeterminate task changed during requeue",
)
- if updated.rowcount != 1:
- raise StaleTaskError("indeterminate task changed during requeue")
- return _task_from_row(_load_task(conn, identity))
def defer_indeterminate_task(
@@ -1306,27 +1056,14 @@ def defer_indeterminate_task(
clock: Clock,
) -> dict[str, Any]:
"""Fence one uncertain attempt and release later room work."""
-
- if lease.room_id != identity.room_id:
- raise DriverValidationError("lease and task belong to different rooms")
- if (
- not isinstance(expected_execution_generation, int)
- or expected_execution_generation < 1
- ):
- raise DriverValidationError(
- "expected_execution_generation must be a positive integer"
- )
- if (
- not isinstance(expected_cancel_generation, int)
- or expected_cancel_generation < 0
- ):
- raise DriverValidationError("expected_cancel_generation must be non-negative")
+ _expected_generations(
+ lease, identity, expected_execution_generation, expected_cancel_generation
+ )
reason = _identifier(reason, label="defer_reason")
result_json = _canonical_json({"reason": reason, "retryable": True})
now = _timestamp(clock)
with _transaction(db_path) as conn:
- _require_active_lease(conn, lease, now=now)
- row = _load_task(conn, identity)
+ row = _fenced_task(conn, lease, identity, now)
if (
row["status"] == "deferred"
and int(row["execution_generation"]) == expected_execution_generation
@@ -1334,30 +1071,23 @@ def defer_indeterminate_task(
and row["result_json"] == result_json
):
return _task_from_row(row, idempotent=True)
- if (
- row["status"] != "indeterminate"
- or int(row["execution_generation"]) != expected_execution_generation
- or int(row["cancel_generation"]) != expected_cancel_generation
- ):
- raise StaleTaskError("indeterminate task generation changed")
- updated = conn.execute(
+ _require_generations(
+ row, "indeterminate", expected_execution_generation, expected_cancel_generation,
+ "indeterminate task generation changed",
+ )
+ return _commit_task(
+ conn,
+ identity,
"""UPDATE hosted_room_driver_tasks
SET status='deferred', result_json=?, terminal_at=?, updated_at=?
WHERE room_id=? AND task_id=? AND status='indeterminate'
AND execution_generation=? AND cancel_generation=?""",
(
- result_json,
- now,
- now,
- identity.room_id,
- identity.task_id,
- expected_execution_generation,
- expected_cancel_generation,
+ result_json, now, now, identity.room_id, identity.task_id,
+ expected_execution_generation, expected_cancel_generation,
),
+ stale="indeterminate task changed during deferral",
)
- if updated.rowcount != 1:
- raise StaleTaskError("indeterminate task changed during deferral")
- return _task_from_row(_load_task(conn, identity))
def requeue_deferred_task(
@@ -1370,32 +1100,19 @@ def requeue_deferred_task(
clock: Clock,
) -> dict[str, Any]:
"""Explicitly retry a fenced deferred turn under a new generation."""
-
- if lease.room_id != identity.room_id:
- raise DriverValidationError("lease and task belong to different rooms")
- if (
- not isinstance(expected_execution_generation, int)
- or expected_execution_generation < 1
- ):
- raise DriverValidationError(
- "expected_execution_generation must be a positive integer"
- )
- if (
- not isinstance(expected_cancel_generation, int)
- or expected_cancel_generation < 0
- ):
- raise DriverValidationError("expected_cancel_generation must be non-negative")
+ _expected_generations(
+ lease, identity, expected_execution_generation, expected_cancel_generation
+ )
now = _timestamp(clock)
with _transaction(db_path) as conn:
- _require_active_lease(conn, lease, now=now)
- row = _load_task(conn, identity)
- if (
- row["status"] != "deferred"
- or int(row["execution_generation"]) != expected_execution_generation
- or int(row["cancel_generation"]) != expected_cancel_generation
- ):
- raise StaleTaskError("deferred task generation changed")
- updated = conn.execute(
+ row = _fenced_task(conn, lease, identity, now)
+ _require_generations(
+ row, "deferred", expected_execution_generation, expected_cancel_generation,
+ "deferred task generation changed",
+ )
+ return _commit_task(
+ conn,
+ identity,
"""UPDATE hosted_room_driver_tasks
SET status='queued', run_gateway_id=NULL,
run_process_generation=NULL, run_lease_generation=NULL,
@@ -1404,33 +1121,23 @@ def requeue_deferred_task(
WHERE room_id=? AND task_id=? AND status='deferred'
AND execution_generation=? AND cancel_generation=?""",
(
- now,
- identity.room_id,
- identity.task_id,
- expected_execution_generation,
- expected_cancel_generation,
+ now, identity.room_id, identity.task_id,
+ expected_execution_generation, expected_cancel_generation,
),
+ stale="deferred task changed during requeue",
)
- if updated.rowcount != 1:
- raise StaleTaskError("deferred task changed during requeue")
- return _task_from_row(_load_task(conn, identity))
def requeue_not_admitted_task(
- db_path: Path | str,
- attempt: TaskAttempt,
- *,
- clock: Clock,
+ db_path: Path | str, attempt: TaskAttempt, *, clock: Clock
) -> dict[str, Any]:
"""Return a running task to its durable queue after proven non-admission."""
now = _timestamp(clock)
lease = attempt.lease
identity = attempt.identity
- if lease.room_id != identity.room_id:
- raise DriverValidationError("lease and task belong to different rooms")
+ _check_same_room(lease, identity)
with _transaction(db_path) as conn:
- _require_active_lease(conn, lease, now=now)
- row = _load_task(conn, identity)
+ row = _fenced_task(conn, lease, identity, now)
if (
row["status"] == "queued"
and int(row["execution_generation"]) == attempt.execution_generation
@@ -1449,7 +1156,9 @@ def requeue_not_admitted_task(
or int(row["run_lease_generation"] or 0) != lease.lease_generation
):
raise StaleTaskError("not-admitted task attempt lost its fence")
- updated = conn.execute(
+ return _commit_task(
+ conn,
+ identity,
"""UPDATE hosted_room_driver_tasks
SET status='queued', run_gateway_id=NULL,
run_process_generation=NULL, run_lease_generation=NULL,
@@ -1459,19 +1168,12 @@ def requeue_not_admitted_task(
AND run_gateway_id=? AND run_process_generation=?
AND run_lease_generation=?""",
(
- now,
- identity.room_id,
- identity.task_id,
- attempt.execution_generation,
- attempt.cancel_generation,
- lease.gateway_id,
- lease.process_generation,
- lease.lease_generation,
+ now, identity.room_id, identity.task_id,
+ attempt.execution_generation, attempt.cancel_generation,
+ lease.gateway_id, lease.process_generation, lease.lease_generation,
),
+ stale="not-admitted task changed during requeue",
)
- if updated.rowcount != 1:
- raise StaleTaskError("not-admitted task changed during requeue")
- return _task_from_row(_load_task(conn, identity))
def cancel_task(
@@ -1484,29 +1186,23 @@ def cancel_task(
) -> dict[str, Any]:
"""Cancel a queued task before any external work was admitted."""
cancel_id = _identifier(cancel_id, label="cancel_id")
- if (
- not isinstance(expected_cancel_generation, int)
- or expected_cancel_generation < 0
- ):
- raise DriverValidationError("expected_cancel_generation must be non-negative")
+ _cancel_generation(expected_cancel_generation)
now = _timestamp(clock)
with _transaction(db_path) as conn:
row = _load_task(conn, identity)
if row["status"] == "cancelled" and row["cancel_id"] == cancel_id:
return _task_from_row(row, idempotent=True)
if row["status"] in TERMINAL_STATUSES:
- raise InvalidTaskTransitionError(
- f"cannot cancel task in state '{row['status']}'"
- )
+ raise InvalidTaskTransitionError(f"cannot cancel task in state '{row['status']}'")
if row["status"] not in {"queued", "deferred"}:
raise InvalidTaskTransitionError(
"running work requires acknowledged two-phase cancellation"
)
if int(row["cancel_generation"]) != expected_cancel_generation:
raise StaleTaskError("task cancellation generation changed")
-
- next_generation = expected_cancel_generation + 1
- updated = conn.execute(
+ return _commit_task(
+ conn,
+ identity,
"""UPDATE hosted_room_driver_tasks
SET status='cancelled', cancel_generation=?, cancel_id=?,
terminal_at=?, updated_at=?
@@ -1514,18 +1210,11 @@ def cancel_task(
AND status IN ('queued', 'deferred')
AND cancel_generation=?""",
(
- next_generation,
- cancel_id,
- now,
- now,
- identity.room_id,
- identity.task_id,
- expected_cancel_generation,
+ expected_cancel_generation + 1, cancel_id, now, now,
+ identity.room_id, identity.task_id, expected_cancel_generation,
),
+ stale="task changed during cancellation",
)
- if updated.rowcount != 1:
- raise StaleTaskError("task changed during cancellation")
- return _task_from_row(_load_task(conn, identity))
def begin_task_cancel(
@@ -1538,11 +1227,7 @@ def begin_task_cancel(
) -> dict[str, Any]:
"""Persist a stop intent without claiming the remote run has stopped."""
cancel_id = _identifier(cancel_id, label="cancel_id")
- if (
- not isinstance(expected_cancel_generation, int)
- or expected_cancel_generation < 0
- ):
- raise DriverValidationError("expected_cancel_generation must be non-negative")
+ _cancel_generation(expected_cancel_generation)
now = _timestamp(clock)
with _transaction(db_path) as conn:
row = _load_task(conn, identity)
@@ -1554,7 +1239,9 @@ def begin_task_cancel(
)
if int(row["cancel_generation"]) != expected_cancel_generation:
raise StaleTaskError("task cancellation generation changed")
- updated = conn.execute(
+ return _commit_task(
+ conn,
+ identity,
"""UPDATE hosted_room_driver_tasks
SET status='stopping', cancel_generation=?, cancel_id=?,
updated_at=?
@@ -1562,17 +1249,11 @@ def begin_task_cancel(
AND status IN ('running', 'indeterminate')
AND cancel_generation=?""",
(
- expected_cancel_generation + 1,
- cancel_id,
- now,
- identity.room_id,
- identity.task_id,
- expected_cancel_generation,
+ expected_cancel_generation + 1, cancel_id, now,
+ identity.room_id, identity.task_id, expected_cancel_generation,
),
+ stale="task changed during stop request",
)
- if updated.rowcount != 1:
- raise StaleTaskError("task changed during stop request")
- return _task_from_row(_load_task(conn, identity))
def complete_task_cancel(
@@ -1596,92 +1277,52 @@ def complete_task_cancel(
or int(row["cancel_generation"]) != expected_cancel_generation
):
raise StaleTaskError("task stop acknowledgement is stale")
- updated = conn.execute(
+ return _commit_task(
+ conn,
+ identity,
"""UPDATE hosted_room_driver_tasks
SET status='cancelled', terminal_at=?, updated_at=?
WHERE room_id=? AND task_id=? AND status='stopping'
AND cancel_id=? AND cancel_generation=?""",
- (
- now,
- now,
- identity.room_id,
- identity.task_id,
- cancel_id,
- expected_cancel_generation,
- ),
+ (now, now, identity.room_id, identity.task_id, cancel_id, expected_cancel_generation),
+ stale="task changed during stop acknowledgement",
)
- if updated.rowcount != 1:
- raise StaleTaskError("task changed during stop acknowledgement")
- return _task_from_row(_load_task(conn, identity))
def recover_room(
- db_path: Path | str,
- lease: DriverLease,
- *,
- clock: Clock,
+ db_path: Path | str, lease: DriverLease, *, clock: Clock
) -> dict[str, list[TaskIdentity]]:
"""Fence abandoned running attempts without requeueing uncertain work."""
now = _timestamp(clock)
- with _transaction(db_path) as conn:
- _require_active_lease(conn, lease, now=now)
- stale_rows = conn.execute(
- """SELECT * FROM hosted_room_driver_tasks
- WHERE room_id=? AND status='running'
+ foreign_running = """room_id=? AND status='running'
AND NOT (
run_gateway_id=? AND run_process_generation=?
AND run_lease_generation=?
- )
- ORDER BY source_event_seq, created_at, task_id""",
- (
- lease.room_id,
- lease.gateway_id,
- lease.process_generation,
- lease.lease_generation,
- ),
+ )"""
+ fence = (lease.room_id, lease.gateway_id, lease.process_generation, lease.lease_generation)
+ with _transaction(db_path) as conn:
+ _require_active_lease(conn, lease, now=now)
+ stale_rows = conn.execute(
+ f"SELECT * FROM hosted_room_driver_tasks WHERE {foreign_running} {_TASK_ORDER}",
+ fence,
).fetchall()
if stale_rows:
conn.execute(
- """UPDATE hosted_room_driver_tasks
+ f"""UPDATE hosted_room_driver_tasks
SET status='indeterminate', indeterminate_at=?, updated_at=?
- WHERE room_id=? AND status='running'
- AND NOT (
- run_gateway_id=? AND run_process_generation=?
- AND run_lease_generation=?
- )""",
- (
- now,
- now,
- lease.room_id,
- lease.gateway_id,
- lease.process_generation,
- lease.lease_generation,
- ),
+ WHERE {foreign_running}""",
+ (now, now, *fence),
)
- queued_rows = conn.execute(
- """SELECT * FROM hosted_room_driver_tasks
- WHERE room_id=? AND status='queued'
- ORDER BY source_event_seq, created_at, task_id""",
- (lease.room_id,),
- ).fetchall()
- indeterminate_rows = conn.execute(
- """SELECT * FROM hosted_room_driver_tasks
- WHERE room_id=? AND status='indeterminate'
- ORDER BY source_event_seq, created_at, task_id""",
- (lease.room_id,),
- ).fetchall()
return {
- "queued": [_task_identity_from_row(row) for row in queued_rows],
- "indeterminate": [
- _task_identity_from_row(row) for row in indeterminate_rows
- ],
+ status: [
+ _task_identity_from_row(row)
+ for row in _tasks_in_order(conn, lease.room_id, status)
+ ]
+ for status in ("queued", "indeterminate")
}
-def get_task(
- db_path: Path | str,
- identity: TaskIdentity,
-) -> dict[str, Any]:
+def get_task(db_path: Path | str, identity: TaskIdentity) -> dict[str, Any]:
"""Read one task without mutating its state."""
conn = _connect(db_path)
try:
@@ -1691,10 +1332,7 @@ def get_task(
def list_tasks(
- db_path: Path | str,
- *,
- room_id: Any,
- status: TaskStatus | None = None,
+ db_path: Path | str, *, room_id: Any, status: TaskStatus | None = None
) -> list[dict[str, Any]]:
"""Return room tasks in deterministic admission order."""
room_id = _identifier(room_id, label="room_id")
@@ -1702,21 +1340,7 @@ def list_tasks(
raise DriverValidationError("invalid task status")
conn = _connect(db_path)
try:
- if status is None:
- rows = conn.execute(
- """SELECT * FROM hosted_room_driver_tasks
- WHERE room_id=?
- ORDER BY source_event_seq, created_at, task_id""",
- (room_id,),
- ).fetchall()
- else:
- rows = conn.execute(
- """SELECT * FROM hosted_room_driver_tasks
- WHERE room_id=? AND status=?
- ORDER BY source_event_seq, created_at, task_id""",
- (room_id, status),
- ).fetchall()
- return [_task_from_row(row) for row in rows]
+ return [_task_from_row(row) for row in _tasks_in_order(conn, room_id, status)]
finally:
conn.close()
@@ -1730,7 +1354,6 @@ def prune_published_terminal_tasks(
retain: int = MAX_RETAINED_TERMINAL_TASKS,
) -> int:
"""Bound execution rows after outcomes are durable in the room log."""
-
room_id = _identifier(room_id, label="room_id")
now = _timestamp(clock)
if retention_seconds <= 0:
@@ -1776,3 +1399,4 @@ def prune_published_terminal_tasks(
(room_id, *candidates),
)
return max(0, int(deleted.rowcount))
+
diff --git a/gateway/hosted_room_execution_policy.py b/gateway/hosted_room_execution_policy.py
index c969d663218..da00c49d8fb 100644
--- a/gateway/hosted_room_execution_policy.py
+++ b/gateway/hosted_room_execution_policy.py
@@ -6,7 +6,7 @@ import hashlib
import json
import re
from contextvars import ContextVar, Token
-from dataclasses import dataclass
+from dataclasses import asdict, dataclass
from typing import Any, Mapping
@@ -20,22 +20,16 @@ class RoomExecutionPolicyError(ValueError):
"""A RoomLink execution policy is malformed or no longer current."""
-def _canonical_json(value: Mapping[str, Any]) -> bytes:
- return json.dumps(
- value,
- ensure_ascii=True,
- sort_keys=True,
- separators=(",", ":"),
+def _policy_digest(unsigned: Mapping[str, Any]) -> str:
+ encoded = json.dumps(
+ unsigned, ensure_ascii=True, sort_keys=True, separators=(",", ":")
).encode("ascii")
+ return hashlib.sha256(encoded).hexdigest()
def _identifier(value: Any, *, field: str) -> str:
normalized = str(value or "").strip()
- if (
- not normalized
- or len(normalized) > 128
- or _IDENTIFIER_RE.fullmatch(normalized) is None
- ):
+ if not normalized or len(normalized) > 128 or _IDENTIFIER_RE.fullmatch(normalized) is None:
raise RoomExecutionPolicyError(f"{field} is invalid")
return normalized
@@ -54,12 +48,8 @@ class RoomExecutionPolicy:
@classmethod
def from_mapping(cls, value: Mapping[str, Any]) -> "RoomExecutionPolicy":
required = {
- "version",
- "target_profile",
- "enabled_toolsets",
- "approval_mode",
- "max_iterations",
- "policy_digest",
+ "version", "target_profile", "enabled_toolsets",
+ "approval_mode", "max_iterations", "policy_digest",
}
if not isinstance(value, Mapping) or set(value) != required:
raise RoomExecutionPolicyError("execution policy fields are invalid")
@@ -95,23 +85,13 @@ class RoomExecutionPolicy:
"approval_mode": approval_mode,
"max_iterations": max_iterations,
}
- expected = hashlib.sha256(_canonical_json(unsigned)).hexdigest()
supplied = str(value["policy_digest"] or "").strip().lower()
- if supplied != expected:
- raise RoomExecutionPolicyError(
- "policy_digest does not match the execution policy"
- )
+ if supplied != _policy_digest(unsigned):
+ raise RoomExecutionPolicyError("policy_digest does not match the execution policy")
return cls(**unsigned, policy_digest=supplied)
def as_mapping(self) -> dict[str, Any]:
- return {
- "version": self.version,
- "target_profile": self.target_profile,
- "enabled_toolsets": list(self.enabled_toolsets),
- "approval_mode": self.approval_mode,
- "max_iterations": self.max_iterations,
- "policy_digest": self.policy_digest,
- }
+ return {**asdict(self), "enabled_toolsets": list(self.enabled_toolsets)}
def execution_policy_mapping(
@@ -137,32 +117,21 @@ def execution_policy_mapping(
approvals = (
config.get("approvals") if isinstance(config.get("approvals"), Mapping) else {}
)
- max_iterations = min(
- resolve_turn_limit(agent.get("max_turns")),
- MAX_POLICY_ITERATIONS,
- )
- approval_mode = (
- "off"
- if _YOLO_MODE_FROZEN
- else _normalize_approval_mode(approvals.get("mode", "manual"))
- )
unsigned = {
"version": POLICY_VERSION,
"target_profile": _identifier(target_profile, field="target_profile"),
"enabled_toolsets": toolsets,
- "approval_mode": approval_mode,
- "max_iterations": max_iterations,
- }
- value = {
- **unsigned,
- "policy_digest": hashlib.sha256(_canonical_json(unsigned)).hexdigest(),
+ "approval_mode": (
+ "off" if _YOLO_MODE_FROZEN else _normalize_approval_mode(approvals.get("mode", "manual"))
+ ),
+ "max_iterations": min(resolve_turn_limit(agent.get("max_turns")), MAX_POLICY_ITERATIONS),
}
+ value = {**unsigned, "policy_digest": _policy_digest(unsigned)}
return RoomExecutionPolicy.from_mapping(value).as_mapping()
_CURRENT_POLICY: ContextVar[RoomExecutionPolicy | None] = ContextVar(
- "hosted_room_execution_policy",
- default=None,
+ "hosted_room_execution_policy", default=None
)
diff --git a/gateway/hosted_room_replicas.py b/gateway/hosted_room_replicas.py
index 26b87080eda..2d7d6edeee6 100644
--- a/gateway/hosted_room_replicas.py
+++ b/gateway/hosted_room_replicas.py
@@ -1,22 +1,14 @@
"""Replica store and takeover primitives for hosted Group Chat rooms.
-The authority gateway owns a room's ordered log in ``gateway/hosted_rooms.py``.
-This module gives every OTHER participant gateway a durable local copy of that
-log, and the fenced primitives to continue the room when the authority host
-dies:
-
-- ``ingest_page()`` persists replay pages (``groups.log`` output, which carries
- the room's authority stamp) idempotently, refusing sequence gaps and
- authority-epoch regressions.
-- ``promote_replica()`` instantiates the replicated log as a locally-owned
- hosted room at ``epoch + 1`` with a lineage-proving ``authority.claimed``
- event, so a surviving participant can resume the room.
-- ``demote_room()`` fences a returning stale authority: presented with proof of
- a newer epoch, the local room records ``authority.lost`` and stops being
- authoritative.
-
-Storage primitives only: none of these decide *when* takeover is safe. The
-caller (an explicit user action today; a lease/quorum driver later) must
+The authority gateway owns a room's ordered log in ``gateway/hosted_rooms.py``;
+this module gives every OTHER participant gateway a durable local copy plus the
+fenced primitives to continue the room when the authority host dies:
+``ingest_page()`` (idempotent, gap- and epoch-regression-safe replay),
+``promote_replica()`` (resume locally at ``epoch + 1`` with a lineage-proving
+``authority.claimed`` event) and ``demote_room()`` (a returning stale authority
+records ``authority.lost`` when shown proof of a newer epoch).
+
+Storage primitives only: none decide *when* takeover is safe. The caller must
establish that the previous owner can no longer commit before promoting.
"""
@@ -45,6 +37,11 @@ from gateway.hosted_rooms import (
MAX_REPLICA_ROOMS = 256
MAX_REPLICA_EVENT_BYTES = 256 * 1024 * 1024
+_SYSTEM_ACTOR = {"kind": "system", "id": "authority-control"}
+_INSERT_ROOM_EVENT = """INSERT INTO hosted_room_events
+ (room_id, seq, event_id, kind, actor_json, authority_epoch,
+ payload_json, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)"""
class ReplicaError(HostedRoomError):
@@ -102,20 +99,34 @@ def _ensure_schema(db_path: Path | str) -> None:
conn.close()
+def _room_id(value: Any) -> str:
+ return _validate_identifier(value, label="room_id", max_chars=MAX_ROOM_ID_CHARS)
+
+
+def _positive_int(value: Any, message: str) -> int:
+ if isinstance(value, bool) or not isinstance(value, int) or value < 1:
+ raise ReplicaError(message)
+ return value
+
+
+def _clock(now: float | None) -> float:
+ return time.time() if now is None else float(now)
+
+
+def _control_event_json(payload: dict[str, Any]) -> tuple[str, str]:
+ """Canonical (actor_json, payload_json) for a system authority-control event."""
+ return (
+ _canonical_json(_SYSTEM_ACTOR, label="actor", max_bytes=4 * 1024),
+ _canonical_json(payload, label="payload", max_bytes=MAX_EVENT_JSON_BYTES),
+ )
+
+
def _event_bytes(event: dict[str, Any]) -> int:
return (
len(str(event["event_id"]).encode("utf-8"))
+ len(str(event["kind"]).encode("utf-8"))
- + len(
- json.dumps(
- event["actor"], ensure_ascii=False, separators=(",", ":")
- ).encode("utf-8")
- )
- + len(
- json.dumps(
- event["payload"], ensure_ascii=False, separators=(",", ":")
- ).encode("utf-8")
- )
+ + len(json.dumps(event["actor"], ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
+ + len(json.dumps(event["payload"], ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
)
@@ -133,16 +144,14 @@ def _validate_page(page: Any) -> tuple[list[dict[str, Any]], dict[str, Any]]:
label="page.authority.gateway_id",
max_chars=MAX_ACTOR_ID_CHARS,
)
- epoch = authority.get("epoch")
- if isinstance(epoch, bool) or not isinstance(epoch, int) or epoch < 1:
- raise ReplicaError("page.authority.epoch must be a positive integer")
+ epoch = _positive_int(
+ authority.get("epoch"), "page.authority.epoch must be a positive integer"
+ )
previous_seq: int | None = None
for event in events:
if not isinstance(event, dict):
raise ReplicaError("page events must be objects")
- seq = event.get("seq")
- if isinstance(seq, bool) or not isinstance(seq, int) or seq < 1:
- raise ReplicaError("event.seq must be a positive integer")
+ seq = _positive_int(event.get("seq"), "event.seq must be a positive integer")
if previous_seq is not None and seq != previous_seq + 1:
raise ReplicaGapError("page events must be contiguous")
previous_seq = seq
@@ -165,19 +174,16 @@ def ingest_page(
page: Any,
now: float | None = None,
) -> dict[str, Any]:
- """Persist one replay page for ``room_id``; idempotent, gap- and
- epoch-regression-safe.
+ """Persist one replay page idempotently; refuses seq gaps and epoch regressions.
- ``page`` is the verbatim result of the authority's ``groups.log`` call
- (``read_events()``), whose ``authority`` stamp proves lineage.
+ ``page`` is the verbatim ``groups.log`` (``read_events()``) result whose
+ ``authority`` stamp proves lineage.
"""
- room_id = _validate_identifier(
- room_id, label="room_id", max_chars=MAX_ROOM_ID_CHARS
- )
+ room_id = _room_id(room_id)
room_name = _validate_room_name(room_name)
_, members_json = _validate_members(members)
events, authority = _validate_page(page)
- now = time.time() if now is None else float(now)
+ now = _clock(now)
_ensure_schema(db_path)
with _replica_transaction(db_path) as conn:
@@ -189,14 +195,10 @@ def ingest_page(
(room_id,),
).fetchone()
if row is None:
- count = conn.execute(
- "SELECT COUNT(*) FROM hosted_room_replicas"
- ).fetchone()[0]
+ count = conn.execute("SELECT COUNT(*) FROM hosted_room_replicas").fetchone()[0]
if int(count) >= MAX_REPLICA_ROOMS:
raise ReplicaError("replica room capacity exhausted")
- stored_epoch = 0
- last_seq = 0
- stored_bytes = 0
+ stored_epoch = last_seq = stored_bytes = 0
else:
stored_epoch = int(row["authority_epoch"])
last_seq = int(row["last_seq"])
@@ -209,34 +211,24 @@ def ingest_page(
new_events = [e for e in events if int(e["seq"]) > last_seq]
if new_events and int(new_events[0]["seq"]) != last_seq + 1:
- raise ReplicaGapError(
- "page skips sequences the replica has not stored"
- )
+ raise ReplicaGapError("page skips sequences the replica has not stored")
added_bytes = 0
for event in new_events:
size = _event_bytes(event)
if stored_bytes + added_bytes + size > MAX_REPLICA_EVENT_BYTES:
raise ReplicaError("replica event storage exhausted")
- actor_json = _canonical_json(
- event["actor"], label="actor", max_bytes=4 * 1024
- )
+ actor_json = _canonical_json(event["actor"], label="actor", max_bytes=4 * 1024)
payload_json = _canonical_json(
event["payload"], label="payload", max_bytes=MAX_EVENT_JSON_BYTES
)
- epoch_value = event.get("authority_epoch")
conn.execute(
"""INSERT INTO hosted_room_replica_events
(room_id, seq, event_id, kind, actor_json, authority_epoch,
payload_json, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
(
- room_id,
- int(event["seq"]),
- event["event_id"],
- event["kind"],
- actor_json,
- epoch_value,
- payload_json,
+ room_id, int(event["seq"]), event["event_id"], event["kind"], actor_json,
+ event.get("authority_epoch"), payload_json,
float(event.get("created_at") or now),
),
)
@@ -253,16 +245,8 @@ def ingest_page(
created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(
- room_id,
- room_name,
- members_json,
- authority["gateway_id"],
- authority["epoch"],
- new_last,
- max(latest_seq, new_last),
- added_bytes,
- now,
- now,
+ room_id, room_name, members_json, authority["gateway_id"], authority["epoch"],
+ new_last, max(latest_seq, new_last), added_bytes, now, now,
),
)
else:
@@ -273,15 +257,8 @@ def ingest_page(
event_bytes=event_bytes+?, updated_at=?
WHERE room_id=?""",
(
- room_name,
- members_json,
- authority["gateway_id"],
- authority["epoch"],
- new_last,
- max(latest_seq, new_last),
- added_bytes,
- now,
- room_id,
+ room_name, members_json, authority["gateway_id"], authority["epoch"],
+ new_last, max(latest_seq, new_last), added_bytes, now, room_id,
),
)
return {
@@ -295,18 +272,12 @@ def ingest_page(
def replica_state(db_path: Path | str, *, room_id: Any) -> dict[str, Any]:
"""Return the stored replica's coverage and authority lineage."""
- room_id = _validate_identifier(
- room_id, label="room_id", max_chars=MAX_ROOM_ID_CHARS
- )
+ room_id = _room_id(room_id)
_ensure_schema(db_path)
with _replica_transaction(db_path) as conn:
_initialize_replica_schema(conn)
row = conn.execute(
- """SELECT room_id, name, members_json, authority_gateway_id,
- authority_epoch, last_seq, latest_seq, event_bytes,
- created_at, updated_at
- FROM hosted_room_replicas WHERE room_id=?""",
- (room_id,),
+ "SELECT * FROM hosted_room_replicas WHERE room_id=?", (room_id,)
).fetchone()
if row is None:
raise ReplicaError("replica not found")
@@ -335,30 +306,22 @@ def promote_replica(
) -> dict[str, Any]:
"""Continue a replicated room on THIS gateway at ``epoch + 1``.
- Copies the replica's log into the authoritative store, appends a lineage-
- proving ``authority.claimed`` event, and returns the new room state. The
- old authority is fenced everywhere the claim replicates: its epoch is now
- stale and every fenced primitive rejects it.
-
- The caller decides that takeover is safe (the previous owner can no longer
- commit). This primitive only makes the takeover atomic and provable.
+ Copies the replica log into the authoritative store and appends a
+ lineage-proving ``authority.claimed`` event; wherever the claim replicates,
+ the old epoch is stale and every fenced primitive rejects it. The caller
+ decides takeover is safe; this only makes it atomic and provable.
"""
- room_id = _validate_identifier(
- room_id, label="room_id", max_chars=MAX_ROOM_ID_CHARS
- )
+ room_id = _room_id(room_id)
if not isinstance(reason, str) or not reason or len(reason) > 200:
raise ReplicaError("reason must be a non-empty string of at most 200 chars")
- now = time.time() if now is None else float(now)
+ now = _clock(now)
local_gateway = local_authority_gateway_id()
_ensure_schema(db_path)
with _replica_transaction(db_path) as conn:
_initialize_replica_schema(conn)
replica = conn.execute(
- """SELECT room_id, name, members_json, authority_gateway_id,
- authority_epoch, last_seq, event_bytes
- FROM hosted_room_replicas WHERE room_id=?""",
- (room_id,),
+ "SELECT * FROM hosted_room_replicas WHERE room_id=?", (room_id,)
).fetchone()
if replica is None:
raise ReplicaError("replica not found")
@@ -382,22 +345,13 @@ def promote_replica(
last_seq = int(replica["last_seq"])
claim_seq = last_seq + 1
claim_event_id = f"system:authority-claimed:{target_epoch}"
- claim_actor_json = _canonical_json(
- {"kind": "system", "id": "authority-control"},
- label="actor",
- max_bytes=4 * 1024,
- )
- claim_payload_json = _canonical_json(
- {
- "previous_gateway_id": previous_gateway,
- "authority_gateway_id": local_gateway,
- "authority_epoch": target_epoch,
- "promoted_from_replica": True,
- "reason": reason,
- },
- label="payload",
- max_bytes=MAX_EVENT_JSON_BYTES,
- )
+ claim_actor_json, claim_payload_json = _control_event_json({
+ "previous_gateway_id": previous_gateway,
+ "authority_gateway_id": local_gateway,
+ "authority_epoch": target_epoch,
+ "promoted_from_replica": True,
+ "reason": reason,
+ })
claim_bytes = (
len(claim_event_id.encode("utf-8"))
+ len(b"authority.claimed")
@@ -412,15 +366,8 @@ def promote_replica(
created_at, updated_at, disbanded_at)
VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?, NULL)""",
(
- room_id,
- replica["name"],
- replica["members_json"],
- local_gateway,
- target_epoch,
- claim_seq + 1,
- int(replica["event_bytes"]) + claim_bytes,
- now,
- now,
+ room_id, replica["name"], replica["members_json"], local_gateway, target_epoch,
+ claim_seq + 1, int(replica["event_bytes"]) + claim_bytes, now, now,
),
)
conn.execute(
@@ -433,26 +380,14 @@ def promote_replica(
(room_id,),
)
conn.execute(
- """INSERT INTO hosted_room_events
- (room_id, seq, event_id, kind, actor_json, authority_epoch,
- payload_json, created_at)
- VALUES (?, ?, ?, 'authority.claimed', ?, ?, ?, ?)""",
+ _INSERT_ROOM_EVENT,
(
- room_id,
- claim_seq,
- claim_event_id,
- claim_actor_json,
- target_epoch,
- claim_payload_json,
- now,
+ room_id, claim_seq, claim_event_id, "authority.claimed",
+ claim_actor_json, target_epoch, claim_payload_json, now,
),
)
- conn.execute(
- "DELETE FROM hosted_room_replica_events WHERE room_id=?", (room_id,)
- )
- conn.execute(
- "DELETE FROM hosted_room_replicas WHERE room_id=?", (room_id,)
- )
+ conn.execute("DELETE FROM hosted_room_replica_events WHERE room_id=?", (room_id,))
+ conn.execute("DELETE FROM hosted_room_replicas WHERE room_id=?", (room_id,))
return {
"room_id": room_id,
"authority_gateway_id": local_gateway,
@@ -474,27 +409,19 @@ def demote_room(
) -> dict[str, Any]:
"""Fence THIS gateway's stale room authority against a proven newer epoch.
- Called when a returning gateway observes (via a replicated
- ``authority.claimed`` event or a transport rejection) that another gateway
- now owns the room at a higher epoch. Appends ``authority.lost`` and adopts
- the observed lineage so no further local sends can be committed at the
- stale epoch. Idempotent for repeated observations of the same lineage.
+ Called when a returning gateway observes (replicated ``authority.claimed``
+ or a transport rejection) that another gateway owns the room at a higher
+ epoch. Appends ``authority.lost`` and adopts the observed lineage so no
+ local send can commit at the stale epoch. Idempotent per lineage.
"""
- room_id = _validate_identifier(
- room_id, label="room_id", max_chars=MAX_ROOM_ID_CHARS
- )
+ room_id = _room_id(room_id)
observed_gateway_id = _validate_identifier(
- observed_gateway_id,
- label="observed_gateway_id",
- max_chars=MAX_ACTOR_ID_CHARS,
+ observed_gateway_id, label="observed_gateway_id", max_chars=MAX_ACTOR_ID_CHARS
)
- if (
- isinstance(observed_epoch, bool)
- or not isinstance(observed_epoch, int)
- or observed_epoch < 1
- ):
- raise ReplicaError("observed_epoch must be a positive integer")
- now = time.time() if now is None else float(now)
+ observed_epoch = _positive_int(
+ observed_epoch, "observed_epoch must be a positive integer"
+ )
+ now = _clock(now)
local_gateway = local_authority_gateway_id()
with _replica_transaction(db_path) as conn:
@@ -507,10 +434,7 @@ def demote_room(
raise ReplicaError("room not found in the local authoritative store")
current_gateway = str(row["authority_gateway_id"])
current_epoch = int(row["authority_epoch"])
- if (
- current_gateway == observed_gateway_id
- and current_epoch == observed_epoch
- ):
+ if current_gateway == observed_gateway_id and current_epoch == observed_epoch:
return {
"room_id": room_id,
"authority_gateway_id": current_gateway,
@@ -522,37 +446,17 @@ def demote_room(
"observed epoch does not supersede the stored authority"
)
if current_gateway != local_gateway:
- raise ReplicaError(
- "room is not locally authoritative; nothing to demote"
- )
- seq = int(row["next_seq"])
- lost_actor_json = _canonical_json(
- {"kind": "system", "id": "authority-control"},
- label="actor",
- max_bytes=4 * 1024,
- )
- lost_payload_json = _canonical_json(
- {
- "previous_gateway_id": current_gateway,
- "authority_gateway_id": observed_gateway_id,
- "authority_epoch": observed_epoch,
- },
- label="payload",
- max_bytes=MAX_EVENT_JSON_BYTES,
- )
+ raise ReplicaError("room is not locally authoritative; nothing to demote")
+ lost_actor_json, lost_payload_json = _control_event_json({
+ "previous_gateway_id": current_gateway,
+ "authority_gateway_id": observed_gateway_id,
+ "authority_epoch": observed_epoch,
+ })
conn.execute(
- """INSERT INTO hosted_room_events
- (room_id, seq, event_id, kind, actor_json, authority_epoch,
- payload_json, created_at)
- VALUES (?, ?, ?, 'authority.lost', ?, ?, ?, ?)""",
+ _INSERT_ROOM_EVENT,
(
- room_id,
- seq,
- f"system:authority-lost:{observed_epoch}",
- lost_actor_json,
- observed_epoch,
- lost_payload_json,
- now,
+ room_id, int(row["next_seq"]), f"system:authority-lost:{observed_epoch}",
+ "authority.lost", lost_actor_json, observed_epoch, lost_payload_json, now,
),
)
conn.execute(
diff --git a/gateway/kanban_watchers.py b/gateway/kanban_watchers.py
index 46221c13163..2df15b25e67 100644
--- a/gateway/kanban_watchers.py
+++ b/gateway/kanban_watchers.py
@@ -1,11 +1,8 @@
"""Kanban board watcher methods for GatewayRunner.
-Extracted verbatim from ``gateway/run.py`` (god-file decomposition Phase 3).
-These are the background-loop methods that subscribe to kanban boards, deliver
-notifications/artifacts, and drive the multi-agent dispatcher. They use only
-``self`` state, so they live on a mixin that ``GatewayRunner`` inherits — the
-``self._kanban_*`` call sites resolve identically via the MRO, making this a
-behavior-neutral move that lifts ~1,000 LOC out of run.py.
+Background loops that subscribe to kanban boards, deliver notifications and
+artifacts, and drive the multi-agent dispatcher. They use only ``self`` state,
+so they live on a mixin ``GatewayRunner`` inherits.
"""
from __future__ import annotations
@@ -23,8 +20,7 @@ from typing import Any, Callable, Optional
from agent.i18n import t
import contextlib
-# Match the logger run.py uses (logging.getLogger(__name__) where __name__ ==
-# "gateway.run") so extracted log records keep their original logger name.
+# Keep the logger name run.py used so extracted log records are unchanged.
logger = logging.getLogger("gateway.run")
@@ -55,17 +51,10 @@ def _resolve_auto_decompose_settings(
) -> "tuple[bool, int]":
"""Resolve the live (enabled, per_tick) auto-decompose settings.
- Read fresh from config on every dispatcher tick (#49638) so that flipping
- ``kanban.auto_decompose: false`` to STOP runaway fan-out takes effect on the
- next tick instead of requiring a gateway restart. Auto-decompose is a
- safety toggle — a user who sees it create and launch tasks they didn't
- intend reaches for this flag to halt it, and a stale boot-captured value
- silently ignoring that change is the bug reported in #49638.
-
- Fails **safe**: if the config read raises, return ``(False, 3)`` — a
- transient read error must never re-enable a feature the user turned off,
- nor fall back to the burst-prone default-on behaviour. ``per_tick`` is
- clamped to ``>= 1``.
+ Read fresh every dispatcher tick so flipping ``kanban.auto_decompose:
+ false`` stops runaway fan-out on the next tick without a restart. Fails
+ safe: a config read error returns ``(False, 3)`` rather than re-enabling
+ a feature the user turned off. ``per_tick`` is clamped to ``>= 1``.
"""
try:
cfg = load_config()
@@ -85,11 +74,8 @@ def _resolve_auto_decompose_settings(
def _kanban_dispatch_allowed() -> bool:
"""Return False while the global emergency stop (`hermes pause`) is engaged.
- Checked every dispatcher tick BEFORE spawning new workers so a pause takes
- effect on the next tick without a gateway restart. In-flight workers are
- never touched — this only stops NEW spawns. Fails open: if the estop
- module is unimportable, dispatch proceeds (the sentinel gate must not
- become a new crash surface for the dispatcher).
+ Checked every tick before spawning, so a pause applies on the next tick;
+ in-flight workers are never touched. Fails open if estop is unimportable.
"""
try:
from agent.estop import check_paused
@@ -101,45 +87,31 @@ def _kanban_dispatch_allowed() -> bool:
def _run_in_fresh_context(func: Callable[..., Any], /, *args: Any) -> Any:
"""Run *func* in an empty ``Context`` so request-local ContextVars stay behind.
- ``asyncio.to_thread`` copies the calling task's context onto the worker
- thread. Supervised Kanban ticks are process-owned writers; if that copy
- still carries a ``delegate_task`` child marker, ``write_txn``
- false-trips. Since watchers spawn from a fresh ``Context``
- (``_spawn_supervised``), this offload-boundary scrub is defense in
- depth: it covers non-supervised spawn paths and any task context frozen
- before spawn isolation shipped. An empty Context keeps the DB guard
- intact for real children without exempting dispatcher writes.
+ ``asyncio.to_thread`` copies the caller's context; a lingering
+ ``delegate_task`` child marker would make ``write_txn`` false-trip for
+ these process-owned writers. An empty Context keeps the DB guard intact
+ for real children without exempting dispatcher writes.
"""
return Context().run(func, *args)
async def _to_thread_process_service(func: Callable[..., Any], /, *args: Any) -> Any:
- """Offload blocking process-service work (dispatcher + notifier writers)
- without inheriting request-local ContextVars."""
+ """Offload blocking process-service work without inheriting request ContextVars."""
return await asyncio.to_thread(_run_in_fresh_context, func, *args)
def _acquire_singleton_lock(lock_path) -> "tuple[Optional[object], str]":
- """Take an exclusive, non-blocking advisory lock for the sole dispatcher.
-
- Only one gateway process machine-wide may run the embedded kanban
- dispatcher: concurrent dispatchers double the reclaim frequency (each
- runs its own ``release_stale_claims`` → promote → dispatch loop), double
- claim-attempt events in the event log, and — with ``wal_autocheckpoint=0`` —
- concurrent manual WAL checkpoints can corrupt index pages. The
- ``dispatch_in_gateway`` config flag is the primary control; this lock is the
- backstop that survives config drift and same-profile restart races.
-
- Delegates to :func:`gateway.status._try_acquire_file_lock` (``fcntl`` on
- POSIX, ``msvcrt`` on Windows) so the guard is cross-platform.
-
- Returns ``(handle, "held")`` on success — the caller keeps the file handle
- for the process lifetime and **must** release it via
- :func:`_release_singleton_lock` when done. ``(None, "contended")`` when
- another process holds the lock (caller must NOT dispatch). ``(None,
- "unavailable")`` when locking cannot be performed (non-POSIX filesystem
- without flock, or the status.py helpers are unimportable) — caller falls
- back to config-only control.
+ """Take the exclusive, non-blocking advisory lock for the sole dispatcher.
+
+ Only one gateway machine-wide may run the embedded dispatcher: concurrent
+ dispatchers double reclaim frequency and claim events, and with
+ ``wal_autocheckpoint=0`` concurrent manual checkpoints can corrupt index
+ pages. ``dispatch_in_gateway`` is the primary control; this is the backstop.
+
+ Returns ``(handle, "held")`` (caller must release via
+ :func:`_release_singleton_lock`), ``(None, "contended")`` when another
+ process holds it (caller must NOT dispatch), or ``(None, "unavailable")``
+ when locking cannot be performed (caller falls back to config control).
"""
try:
from gateway.status import _try_acquire_file_lock # deferred; same package
@@ -157,7 +129,7 @@ def _acquire_singleton_lock(lock_path) -> "tuple[Optional[object], str]":
def _release_singleton_lock(handle) -> None:
- """Release a dispatcher singleton lock acquired via :func:`_acquire_singleton_lock`."""
+ """Release a lock acquired via :func:`_acquire_singleton_lock`."""
if handle is None:
return
try:
@@ -172,16 +144,11 @@ def _release_singleton_lock(handle) -> None:
def _wake_scope_id(adapter: Any, sub: dict) -> Optional[str]:
"""Return the tenant scope (Slack workspace) a subscription's wake keys to.
- ``build_session_key()`` includes ``SessionSource.scope_id`` on platforms
- where one bot serves several isolated tenants, so a wake source must carry
- the same scope as inbound messages from that chat to resolve to the same
- session.
-
- The subscription's persisted ``delivery_metadata`` wins over the adapter's
- live chat → scope mapping, because it records the scope the subscription was
- created from; the mapping only covers rows that stored no metadata. ``None``
- means the chat has no scope, which is what an unscoped platform's key
- contains.
+ ``build_session_key()`` includes ``scope_id`` on multi-tenant platforms,
+ so the wake must carry the same scope as inbound messages. Persisted
+ ``delivery_metadata`` wins (it records the creating scope); the adapter's
+ live chat → scope map only covers rows without metadata. ``None`` means
+ unscoped, matching an unscoped platform's key.
"""
delivery_meta = sub.get("delivery_metadata")
if isinstance(delivery_meta, dict):
@@ -223,32 +190,20 @@ class GatewayKanbanWatchersMixin:
async def _kanban_notifier_watcher(self, interval: float = 5.0) -> None:
"""Poll ``kanban_notify_subs`` and deliver terminal events to users.
- For each subscription row, fetches ``task_events`` newer than the
- stored cursor with kind in the terminal set (``completed``,
- ``blocked``, ``gave_up``, ``crashed``, ``timed_out``,
- ``review_requested``, ``changes_requested``,
- ``block_loop_detected``). Sends one
- message per new event to ``(platform, chat_id, thread_id)``,
- then advances the cursor. The subscription is removed only when the
- task is ``archived``. A ``done`` task can be reopened for review or
- continuation, so its subscription and origin-session ownership must
- survive completion. Cursor advancement prevents old events replaying
- when that happens.
-
- Runs in the gateway event loop; all SQLite work is pushed to a
- thread via ``asyncio.to_thread`` so the loop never blocks on the
- WAL lock. Failures in one tick don't stop subsequent ticks.
-
- **Multi-board:** iterates every board discovered on disk per
- tick. Each gateway polls only subscriptions owned by profiles whose
- adapters it hosts. The dispatch-owning gateway also handles legacy
- subscriptions without a profile stamp.
+ Per subscription, claims ``task_events`` newer than the stored cursor
+ (kinds in TERMINAL_KINDS), sends one message per event to
+ ``(platform, chat_id, thread_id)``, then advances the cursor. The
+ subscription is removed only when the task is ``archived``: ``done``
+ is reversible (review/continuation), so the cursor — not unsubscribing
+ — is the dedup mechanism. Earlier unsub-on-terminal silently dropped
+ users when the dispatcher respawned a crashed task.
+
+ All SQLite work runs in a thread; one tick's failure never stops the
+ next. Iterates every board on disk per tick; each gateway polls only
+ subscriptions owned by profiles whose adapters it hosts, and legacy
+ rows without a profile stamp are visible only to the process holding
+ the singleton dispatcher lock.
"""
- # Dispatch and delivery have separate ownership. A deployment may run
- # one dispatcher while each profile has its own gateway credentials;
- # those adapter-owning gateways must still poll and deliver their own
- # subscriptions. Legacy rows without a notifier_profile are visible
- # only while this process holds the actual singleton dispatcher lock.
from gateway.config import Platform as _Platform
try:
from hermes_cli import kanban_db as _kb
@@ -256,37 +211,14 @@ class GatewayKanbanWatchersMixin:
logger.warning("kanban notifier: kanban_db not importable; notifier disabled")
return
- # "status" covers dashboard drag-drop and `_set_status_direct()`
- # writes — surface those transitions to subscribers too.
- # ``review_requested`` wakes the origin subscriber like a block does,
- # but is not a block (see kanban_db.request_review); the task is not
- # archived, so the subscription stays alive and later review
- # cycles keep notifying.
+ # "status" covers dashboard drag-drop and `_set_status_direct()`.
+ # ``review_requested`` wakes the origin like a block but is not one;
+ # the task is not archived so later review cycles keep notifying.
TERMINAL_KINDS = ("completed", "blocked", "gave_up", "crashed", "timed_out", "status", "archived", "unblocked", "block_loop_detected", "review_requested", "changes_requested")
- # Subscriptions are removed only when the task reaches the irreversible
- # archived status. ``done`` is reversible in review/controller flows,
- # so removing its subscription would silence a later reopen. We used
- # to also unsub on any terminal
- # event kind (gave_up / crashed / timed_out / blocked), but that
- # silently dropped the user out of the loop whenever the dispatcher
- # respawned the task: a worker that crashes, gets reclaimed, runs
- # again, and crashes a second time would only notify on the first
- # crash because the subscription was deleted after the first event.
- # Same shape as the reblock-after-unblock cycle that PR #22941
- # fixed for `blocked`. Keeping the subscription alive until the
- # task is archived lets the cursor (advanced atomically by
- # claim_unseen_events_for_sub) handle dedup, and any retry-loop
- # event reaches the user.
- # Per-subscription send-failure counter. Adapter.send raising
- # means the chat is dead (deleted, bot kicked, etc.) — after N
- # consecutive send failures the sub is dropped so we don't spin
- # against a dead chat every 5 seconds forever.
- # Raised from 3 to 12 (~60s at the 5s tick cadence): now that a
- # reported SendResult(success=False) also lands here (see the
- # delivery loop below), a transient Telegram/API outage of a few
- # ticks must NOT permanently unsubscribe a live review-gate channel.
- # A genuinely dead chat still drops, just ~60s later — a fine trade
- # for an unattended gate where a false drop means silent work pileup.
+ # Consecutive send failures (adapter raised OR reported
+ # SendResult(success=False)) before a sub is dropped as a dead chat.
+ # 12 ≈ 60s at the 5s cadence: a transient API outage must not
+ # permanently unsubscribe a live review-gate channel.
MAX_SEND_FAILURES = 12
sub_fail_counts: dict[tuple, int] = getattr(
self, "_kanban_sub_fail_counts", {}
@@ -300,14 +232,11 @@ class GatewayKanbanWatchersMixin:
# Initial delay so the gateway can finish wiring adapters.
await asyncio.sleep(5)
- # Stale done-sub GC cadence. Subscriptions survive ``done`` (it is
- # reversible), so boards that never archive would otherwise
- # accumulate rows scanned on every 5s tick forever. The sweep is a
- # single DELETE per board, gated to once per watcher startup and at
- # most once per hour thereafter — cheap relative to the tick's own
- # per-sub claims. Retention is kanban.done_sub_retention_days in
- # config.yaml (default 30; 0 disables), re-read at each sweep so a
- # config change applies without a restart.
+ # Stale done-sub GC: subs survive ``done``, so boards that never
+ # archive would accumulate rows scanned every tick. One DELETE per
+ # board, at startup and at most hourly; retention is
+ # kanban.done_sub_retention_days (default 30; 0 disables), re-read
+ # at each sweep.
_GC_INTERVAL_SECONDS = 3600.0
_gc_next_at = 0.0 # 0 → sweep on the first tick after startup
@@ -325,9 +254,7 @@ class GatewayKanbanWatchersMixin:
_kanban_cfg.get("done_sub_retention_days", 30)
)
except Exception:
- # Fail safe on the shipped default; the sweep itself
- # treats <= 0 as disabled.
- _gc_retention_days = 30
+ _gc_retention_days = 30 # fail safe on the shipped default
def _collect():
deliveries: list[dict] = []
@@ -342,19 +269,12 @@ class GatewayKanbanWatchersMixin:
getattr(platform, "value", str(platform)).lower()
for platform in self.adapters
}
- # Widen to every platform any secondary profile has live,
- # not just the default profile's. This is only a coarse
- # pre-filter to skip claiming events for subs nobody can
- # possibly deliver — the precise per-profile check (via
- # gateway/authz_mixin.py::_authorization_adapter, which
- # forbids default-profile fallback) still runs at delivery
- # time below, rewinding the claim if it resolves to None.
- # Without this, a subscription owned by a secondary
- # profile on a platform the DEFAULT profile never
- # connected (e.g. beta owns discord, default doesn't) was
- # dropped here before ever being claimed — no rewind
- # applies to an unclaimed event, so it silently never
- # retries.
+ # Include every platform any secondary profile has live.
+ # This is only a coarse pre-filter; the precise
+ # per-profile check (_authorization_adapter, no default
+ # fallback) runs at delivery and rewinds the claim if it
+ # resolves to None. An unclaimed event never retries, so
+ # dropping a secondary-profile sub here would lose it.
for _profile_adapter_map in getattr(self, "_profile_adapters", {}).values():
active_platforms.update(
getattr(platform, "value", str(platform)).lower()
@@ -364,11 +284,8 @@ class GatewayKanbanWatchersMixin:
logger.debug("kanban notifier: no connected adapters; skipping tick")
return deliveries
- # Enumerate every board on disk, but poll each resolved DB
- # path once. Multiple slugs can point at the same DB when
- # HERMES_KANBAN_DB pins the board path; without this guard
- # one gateway could collect the same subscription/event
- # more than once before advancing the cursor.
+ # Poll each resolved DB path once: several slugs can map
+ # to one DB when HERMES_KANBAN_DB pins the board path.
try:
boards = _kb.list_boards(include_archived=False)
except Exception:
@@ -388,13 +305,9 @@ class GatewayKanbanWatchersMixin:
)
continue
seen_db_paths.add(resolved_db_path)
- # Zero-subscription early exit: probe the board with a
- # cheap read-only connection BEFORE the writable
- # `connect()`. A board with no subscriptions has
- # nothing to notify, and the writable open (schema
- # init/migration on first open, WAL/-shm sidecars,
- # checkpoint traffic) is exactly the per-tick cost
- # this skip avoids.
+ # Cheap read-only probe before the writable connect()
+ # (schema init, WAL sidecars, checkpoints) — a board
+ # with no subscriptions has nothing to notify.
try:
if _kb.count_notify_subs(
board=slug,
@@ -419,12 +332,8 @@ class GatewayKanbanWatchersMixin:
continue
try:
if _gc_due:
- # Hourly (plus once at startup) stale-sub GC:
- # drop subscriptions for tasks that have been
- # ``done``/``blocked`` untouched past the retention
- # window. Best-effort — a failed sweep never
- # blocks delivery; the next hourly gate
- # retries it.
+ # Best-effort: a failed sweep never blocks
+ # delivery; the next hourly gate retries.
try:
_purged = _kb.purge_stale_done_notify_subs(
conn,
@@ -440,18 +349,9 @@ class GatewayKanbanWatchersMixin:
"kanban notifier: stale-sub GC failed for board %s: %s",
slug, _gc_exc,
)
- # `connect()` runs the schema + idempotent migration
- # on first open per process, so an explicit
- # `init_db()` here would be redundant. Worse:
- # `init_db()` deliberately busts the per-process
- # cache and re-runs the migration on a *second*
- # connection, which races the first and used to
- # log a benign but noisy `duplicate column name`
- # traceback (and intermittent "database is locked"
- # — issue #21378) on every gateway start against
- # a legacy DB. `_add_column_if_missing` now
- # tolerates that race, but we still skip the
- # redundant call to avoid the wasted work.
+ # No explicit init_db(): connect() already runs the
+ # migration once per process, and init_db() would
+ # re-run it on a second connection racing the first.
subs = _kb.list_notify_subs(
conn,
notifier_profiles=notifier_profiles,
@@ -501,9 +401,7 @@ class GatewayKanbanWatchersMixin:
"board": slug,
})
except Exception as sub_exc:
- # Isolate per-subscription failures so one
- # bad subscription cannot block delivery for
- # all other subscriptions in this tick.
+ # One bad subscription must not block the rest of the tick.
logger.warning(
"kanban notifier: subscription for %s on board %s failed: %s",
sub.get("task_id"), slug, sub_exc,
@@ -518,71 +416,75 @@ class GatewayKanbanWatchersMixin:
task = d["task"]
board_slug = d.get("board")
platform_str = (sub["platform"] or "").lower()
+
+ async def _rewind() -> None:
+ await _to_thread_process_service(
+ self._kanban_rewind,
+ sub,
+ d["cursor"],
+ d.get("old_cursor", 0),
+ board_slug,
+ )
+
try:
plat = _Platform(platform_str)
except ValueError:
- # Unknown platform string; skip and advance cursor so
- # we don't replay forever.
+ # Unknown platform: advance the cursor so it can't replay forever.
await _to_thread_process_service(
self._kanban_advance, sub, d["cursor"], board_slug,
)
continue
sub_profile = sub.get("notifier_profile") or ""
- # Route via the SAME chokepoint the authorization path uses
- # (gateway/authz_mixin.py::_authorization_adapter): a stamped
- # profile with its own adapter-registry entry must be served
- # by THAT profile's same-platform adapter and must NOT silently
- # fall back to the default profile's adapter — otherwise a
- # secondary profile's task notification is delivered by the
- # wrong bot (the cross-profile mis-delivery this whole change
- # exists to fix). The helper returns None only when the profile
- # (or default) genuinely has no adapter for the platform.
+ # Same chokepoint as authorization: a stamped profile is
+ # served by ITS same-platform adapter and never falls back
+ # to the default profile's bot (cross-profile mis-delivery).
+ # None only when the profile (or default) has no adapter.
adapter = self._authorization_adapter(plat, sub_profile or None)
if adapter is None:
logger.debug(
"kanban notifier: adapter %s disconnected before delivery for %s; rewinding claim",
platform_str, sub["task_id"],
)
- await _to_thread_process_service(
- self._kanban_rewind,
- sub,
- d["cursor"],
- d.get("old_cursor", 0),
- board_slug,
- )
+ await _rewind()
continue
title = (task.title if task else sub["task_id"])[:120]
board_tag = f"[{board_slug}] " if board_slug else ""
- # Per-subscription failure-counter key. Hoisted out of the
- # event loop: the wake self-post path (in the loop's
- # ``else`` clause) needs it even when every event in the
- # claim was skipped before reaching the send site.
+ # Hoisted: the wake self-post path (the loop's ``else``)
+ # needs the key even when every event was skipped.
sub_key = (
sub["task_id"], sub["platform"],
sub["chat_id"], sub.get("thread_id") or "",
)
+
+ async def _delivery_failed(fmt: str, prefix: tuple, drop_fmt: str, exc: Exception, exc_info: bool) -> None:
+ """Bump the failure counter; drop the sub past the limit, else rewind the claim so the next tick retries."""
+ fails = sub_fail_counts.get(sub_key, 0) + 1
+ sub_fail_counts[sub_key] = fails
+ logger.warning(fmt, *prefix, fails, MAX_SEND_FAILURES, exc, exc_info=exc_info)
+ if fails >= MAX_SEND_FAILURES:
+ logger.warning(drop_fmt, sub["task_id"], platform_str, fails)
+ await _to_thread_process_service(self._kanban_unsub, sub, board_slug)
+ sub_fail_counts.pop(sub_key, None)
+ else:
+ await _rewind()
+
mode = sub.get("delivery_mode") or "notify"
wake_agent = mode in ("notify+wake", "wake")
send_passive = mode != "wake"
- # Worker handoff carried into the synthetic wake turn below
- # (#70752): without it the woken creator only sees
- # "Task X completed" and re-decomposes work that already
- # exists on the board.
+ # Worker handoff carried into the synthetic wake turn so the
+ # woken creator doesn't re-decompose work already on the board.
wake_handoff = ""
wake_review_detail = ""
+ from gateway.wake import adapter_supports_push
+
for ev in d["events"]:
kind = ev.kind
- # Identity prefix: attribute terminal pings to the
- # worker that did the work. Makes fleets (where one
- # chat subscribes to many tasks) legible at a glance.
+ # Attribute the ping to the worker that did the work.
who = (task.assignee if task and task.assignee else None)
tag = f"@{who} " if who else ""
if kind == "completed":
- # Prefer the run's summary (the worker's
- # intentional human-facing handoff, carried
- # in the event payload), then fall back to
- # task.result for legacy rows written before
- # runs shipped.
+ # Prefer the run summary from the event payload;
+ # fall back to task.result for legacy rows.
handoff = ""
payload_summary = None
if ev.payload and ev.payload.get("summary"):
@@ -633,16 +535,13 @@ class GatewayKanbanWatchersMixin:
new_status = str(ev.payload["status"])
msg = f"🔄 {board_tag}{tag}Kanban {sub['task_id']} → {new_status}"
elif kind == "review_requested":
- # Implementation complete; task moved to the
- # first-class review lane. Wake the origin thread.
+ # Implementation done; task moved to the review lane.
handoff = ""
if ev.payload and ev.payload.get("summary"):
summary = str(ev.payload["summary"])
handoff = f"\n{summary[:200]}"
- # Carry the worker's handoff into the wake turn
- # like ``completed`` does: a reviewer woken with
- # a bare "ready for review" has to re-read the
- # board to learn what was implemented.
+ # Carry the handoff into the wake turn like
+ # ``completed`` so the reviewer needn't re-read the board.
lines = summary.strip().splitlines()
wake_handoff = (
lines[0][:200] if lines else summary[:200]
@@ -668,13 +567,9 @@ class GatewayKanbanWatchersMixin:
)
wake_review_detail = reason_text
elif kind == "block_loop_detected":
- # A task re-blocked for the same cause past the
- # recurrence limit and was routed to `triage` for a
- # human decision. This is the ONE transition that
- # exists to force human attention, yet it emits no
- # `blocked`/`status` event — so before adding it to
- # TERMINAL_KINDS it produced zero notification and
- # the task stalled in triage silently. Ping loudly.
+ # Re-blocked for the same cause past the limit and
+ # routed to `triage` for a human. It emits no
+ # blocked/status event, so ping loudly here.
reason = ""
recurrences = None
if ev.payload:
@@ -687,13 +582,9 @@ class GatewayKanbanWatchersMixin:
f" — needs a human decision{rc}{reason}"
)
else:
- # archived / unblocked are claimed by TERMINAL_KINDS
- # (so the cursor advances past them and they can't
- # wedge a later completed/blocked event behind an
- # unclaimed row) but are intentionally SILENT: an
- # archive needs no user ping, and unblocked is an
- # internal transition. They are also excluded from
- # _WAKE_KINDS below, so they never wake the creator.
+ # archived / unblocked are claimed (so the cursor
+ # advances past them) but intentionally silent, and
+ # excluded from _WAKE_KINDS so they never wake the creator.
continue
delivery_metadata = sub.get("delivery_metadata")
metadata: dict[str, Any] = (
@@ -704,21 +595,11 @@ class GatewayKanbanWatchersMixin:
if sub.get("thread_id") and not metadata.get("thread_id"):
metadata["thread_id"] = sub["thread_id"]
- # Adapters with no push channel (the API server —
- # ``supports_async_delivery = False``) can NEVER
- # satisfy a text-send: ``send()`` always reports
- # SendResult(success=False) by design (see
- # ApiServerAdapter.send()). Treating that as a
- # delivery failure would rewind/drop the subscription
- # forever and — because the wake dispatch below lives
- # in this loop's ``else`` clause — would also make the
- # wake-on-completion path (the actual fix for the
- # api_server wrong-session bug) unreachable. So for
- # non-push adapters, skip the doomed send attempt
- # entirely: there is nothing to text-notify, the
- # creator is woken via the self-post below instead.
- from gateway.wake import adapter_supports_push
-
+ # Non-push adapters (api_server) always report
+ # SendResult(success=False) from send(); treating that
+ # as failure would drop the sub forever and make the
+ # wake path in this loop's ``else`` unreachable. Skip
+ # the doomed send; the self-post below IS the delivery.
if not adapter_supports_push(adapter) and wake_agent:
logger.debug(
"kanban notifier: adapter %s has no push "
@@ -726,29 +607,19 @@ class GatewayKanbanWatchersMixin:
"on wake self-post instead",
platform_str, sub["task_id"],
)
- # Do NOT reset the failure counter here: on this
- # path the wake self-post below IS the delivery,
- # so the counter is resolved (reset or bumped) by
- # the self-post outcome, not by skipping the send.
+ # Counter is resolved by the self-post outcome, not here.
continue
if not send_passive:
- # Wake-only subscriptions intentionally skip the
- # visible platform message. The retained wake path
- # below is the sole delivery — the failure counter
- # is resolved (reset or bumped) by the wake
- # outcome there, not by skipping the send here.
+ # Wake-only: the wake path below is the sole delivery
+ # and resolves the failure counter.
continue
try:
_send_res = await adapter.send(
sub["chat_id"], msg, metadata=metadata,
)
- # A SendResult(success=False) without an exception
- # (returned by push-capable adapters on a genuine
- # transient failure) must count as a FAILED
- # delivery — otherwise the cursor advances and the
- # event is permanently lost. Adapters returning
- # None (or anything non-SendResult shaped) keep
- # the legacy "no exception == delivered" contract.
+ # SendResult(success=False) without an exception is
+ # a FAILED delivery (else the event is lost); None /
+ # non-SendResult keeps the "no exception == delivered" contract.
if getattr(_send_res, "success", True) is False:
raise RuntimeError(
"adapter send() reported failure: "
@@ -758,15 +629,9 @@ class GatewayKanbanWatchersMixin:
"kanban notifier: delivered %s event for %s to %s/%s on board %s",
kind, sub["task_id"], platform_str, sub["chat_id"], board_slug,
)
- # After delivering the text notification, surface
- # any artifact paths the worker referenced in
- # ``kanban_complete(summary=..., artifacts=[...])``
- # (or the legacy ``result`` field) as native
- # uploads. ``extract_local_files`` finds bare
- # absolute paths in the summary;
- # ``send_document`` / ``send_image_file`` uploads
- # them. Only fires on the ``completed`` event so
- # we never spam attachments on retries.
+ # Upload artifact paths from the completion payload
+ # / legacy result as native files. Only on
+ # ``completed`` so retries never spam attachments.
if kind == "completed":
try:
await self._deliver_kanban_artifacts(
@@ -781,63 +646,28 @@ class GatewayKanbanWatchersMixin:
"kanban notifier: artifact delivery for %s failed: %s",
sub["task_id"], art_exc,
)
- # Reset the failure counter on success.
sub_fail_counts.pop(sub_key, None)
except Exception as exc:
- fails = sub_fail_counts.get(sub_key, 0) + 1
- sub_fail_counts[sub_key] = fails
- logger.warning(
+ await _delivery_failed(
"kanban notifier: send failed for %s on %s "
"(attempt %d/%d): %s",
- sub["task_id"], platform_str, fails,
- MAX_SEND_FAILURES, exc,
+ (sub["task_id"], platform_str),
+ "kanban notifier: dropping subscription "
+ "%s on %s after %d consecutive send failures",
+ exc, False,
)
- if fails >= MAX_SEND_FAILURES:
- logger.warning(
- "kanban notifier: dropping subscription "
- "%s on %s after %d consecutive send failures",
- sub["task_id"], platform_str, fails,
- )
- await _to_thread_process_service(self._kanban_unsub, sub, board_slug)
- sub_fail_counts.pop(sub_key, None)
- else:
- await _to_thread_process_service(
- self._kanban_rewind,
- sub,
- d["cursor"],
- d.get("old_cursor", 0),
- board_slug,
- )
- # Rewind the pre-send claim on transient failure so
- # a later tick can retry. After too many failures,
- # dropping the subscription is the terminal action.
break
else:
- # All text pings delivered (or intentionally skipped
- # for non-push adapters, whose delivery is the wake
- # self-post below). Whether the cursor may advance now
- # depends on the adapter class:
- #
- # * push-capable: the text send WAS the delivery, so
- # advance immediately (pre-existing behavior); the
- # wake injection below stays best-effort.
- # * non-push (api_server): the wake self-post IS the
- # delivery. Advancing first would let a failed /
- # retry-exhausted self-post (swallowed by the
- # best-effort except) permanently lose the event.
- # So the self-post runs FIRST and the cursor only
- # advances after it succeeds — a failure rewinds the
- # claim exactly like a failed send() above, so the
- # next tick retries.
+ # All text pings delivered (or skipped for non-push /
+ # wake-only). Cursor advance ordering by adapter class:
+ # * push + notify: the text send WAS the delivery →
+ # advance now; wake injection stays best-effort.
+ # * non-push or wake-only: the wake IS the delivery →
+ # it runs FIRST and the cursor advances only after it
+ # succeeds; failure rewinds like a failed send().
task_terminal = task and task.status == "archived"
- # Kinds that hand a decision back to the origin, so the
- # origin has to take a turn. ``review_requested`` (the
- # implementation is done and waits for a reviewer),
- # ``changes_requested`` (a reviewer BLOCKed and work
- # returns to the implementer) and ``block_loop_detected``
- # (routed to triage) belong here for the same reason
- # ``blocked`` does. ``status`` / ``archived`` /
- # ``unblocked`` stay out: bookkeeping.
+ # Kinds that hand a decision back to the origin, which
+ # must take a turn. status/archived/unblocked are bookkeeping.
_WAKE_KINDS = (
"completed", "gave_up", "crashed", "timed_out",
"blocked", "review_requested", "changes_requested",
@@ -848,40 +678,26 @@ class GatewayKanbanWatchersMixin:
if wake_agent
else set()
)
- from gateway.wake import adapter_supports_push as _adapter_push_ok
-
- _is_push_adapter = _adapter_push_ok(adapter)
+ _is_push_adapter = adapter_supports_push(adapter)
_session_key = ""
_synth = ""
if _wake_kinds:
if _is_push_adapter:
_session_key = getattr(task, "session_id", None) or ""
else:
- # Non-push (api_server) wakes go to the
- # subscription's delivery destination —
- # sub["chat_id"] IS the raw session id the
- # subscriber registered with. task.session_id
- # is worker/creator provenance and may point
- # at a WORKER session for child tasks with
- # inherited subscriptions; falling back to it
- # only when chat_id is empty (legacy rows).
+ # Non-push wakes target sub["chat_id"] (the raw
+ # session id the subscriber registered).
+ # task.session_id may be a WORKER session for
+ # child tasks; use it only for legacy rows.
_session_key = (
sub["chat_id"]
or getattr(task, "session_id", None)
or ""
)
- if _wake_kinds:
_title = (task.title if task else sub["task_id"])[:120]
_assignee = task.assignee if task else ""
- _parts = []
- if "completed" in _wake_kinds: _parts.append(t("gateway.kanban.wake.completed"))
- if "gave_up" in _wake_kinds: _parts.append(t("gateway.kanban.wake.gave_up"))
- if "crashed" in _wake_kinds: _parts.append(t("gateway.kanban.wake.crashed"))
- if "timed_out" in _wake_kinds: _parts.append(t("gateway.kanban.wake.timed_out"))
- if "blocked" in _wake_kinds: _parts.append(t("gateway.kanban.wake.blocked"))
- if "review_requested" in _wake_kinds: _parts.append(t("gateway.kanban.wake.review_requested"))
- if "changes_requested" in _wake_kinds: _parts.append(t("gateway.kanban.wake.changes_requested"))
- if "block_loop_detected" in _wake_kinds: _parts.append(t("gateway.kanban.wake.block_loop_detected"))
+ # i18n keys: gateway.kanban.wake.<kind> for each _WAKE_KINDS entry.
+ _parts = [t(f"gateway.kanban.wake.{k}") for k in _WAKE_KINDS if k in _wake_kinds]
_status = t("gateway.kanban.wake.status_joiner").join(_parts) or t("gateway.kanban.wake.status_default")
_synth = t(
"gateway.kanban.wake.message",
@@ -891,11 +707,9 @@ class GatewayKanbanWatchersMixin:
assignee=_assignee,
board=board_slug,
)
- # Graph-safe wake turn (#70752): carry the worker's
- # completion handoff into the synthetic turn and
- # label it as an automatic notification so the woken
- # creator inspects the board instead of
- # re-decomposing work that already exists.
+ # Label as an automatic notification and carry the
+ # handoff so the creator inspects the board instead
+ # of re-decomposing.
if wake_handoff:
_synth += "\n" + t(
"gateway.kanban.wake.handoff",
@@ -911,8 +725,7 @@ class GatewayKanbanWatchersMixin:
)
if not _is_push_adapter and _wake_kinds and _session_key:
- # Wake self-post IS the delivery on this path —
- # it must succeed BEFORE the cursor advances.
+ # Self-post IS the delivery: must succeed BEFORE the cursor advances.
from gateway.wake import deliver_wake
try:
@@ -927,59 +740,27 @@ class GatewayKanbanWatchersMixin:
)
sub_fail_counts.pop(sub_key, None)
except Exception as _wk_err:
- fails = sub_fail_counts.get(sub_key, 0) + 1
- sub_fail_counts[sub_key] = fails
- logger.warning(
+ await _delivery_failed(
"kanban notifier: wake self-post failed "
"for %s (attempt %d/%d): %s",
- sub["task_id"], fails,
- MAX_SEND_FAILURES, _wk_err, exc_info=True,
+ (sub["task_id"],),
+ "kanban notifier: dropping subscription "
+ "%s on %s after %d consecutive wake failures",
+ _wk_err, True,
)
- if fails >= MAX_SEND_FAILURES:
- logger.warning(
- "kanban notifier: dropping subscription "
- "%s on %s after %d consecutive wake failures",
- sub["task_id"], platform_str, fails,
- )
- await _to_thread_process_service(self._kanban_unsub, sub, board_slug)
- sub_fail_counts.pop(sub_key, None)
- else:
- # Rewind the pre-send claim so the next
- # tick retries the self-post — the event
- # is NOT lost.
- await _to_thread_process_service(
- self._kanban_rewind,
- sub,
- d["cursor"],
- d.get("old_cursor", 0),
- board_slug,
- )
continue
async def _push_wake() -> None:
- """Wake the creator session behind a push adapter.
-
- Shared by the wake-only (pre-advance, delivery)
- and notify+wake (post-advance, best-effort)
- branches below; raises on failure so the caller
- decides whether to rewind or merely log.
- """
+ """Wake the creator session behind a push adapter; raises on failure."""
from gateway.session import SessionSource
from gateway.wake import deliver_wake
- # Rebuild the creator's real session scope from
- # the chat_type persisted on the subscription
- # row (#56580). build_session_key() keys DMs
- # (":dm:<chat_id>") on a wholly different shape
- # from group/thread, so the old hardcoded
- # "group" mis-routed DM/thread creators into a
- # fresh session. Legacy rows written before the
- # column existed may still carry chat_type in
- # delivery_metadata (#60600 rows) — fall back
- # to that, then to "group" (the historical
- # default that suits the dashboard/group flows).
- # handle_message() get_or_create_session's the
- # target, so a mismatch only ever degrades to a
- # fresh session, never an exception.
+ # Rebuild the creator's real session scope from the
+ # persisted chat_type: build_session_key() keys DMs
+ # differently from group/thread, so a hardcoded
+ # "group" mis-routed DM/thread creators into a fresh
+ # session. Legacy rows may carry chat_type in
+ # delivery_metadata; last resort is "group". A
+ # mismatch only degrades to a fresh session.
_chat_type = str(sub.get("chat_type") or "").strip()
if not _chat_type:
_delivery_meta = sub.get("delivery_metadata")
@@ -998,11 +779,6 @@ class GatewayKanbanWatchersMixin:
profile=sub_profile or None,
scope_id=_wake_scope_id(adapter, sub),
)
- # deliver_wake preserves the synthetic
- # MessageEvent/handle_message path for
- # push-capable adapters (the non-push /
- # self-post branch is handled BEFORE the
- # cursor advance above).
await deliver_wake(
adapter,
text=_synth,
@@ -1015,81 +791,40 @@ class GatewayKanbanWatchersMixin:
)
if _is_push_adapter and not send_passive and _wake_kinds:
- # Wake-only (delivery_mode='wake') push sub: the
- # text ping was intentionally skipped above, so
- # the wake IS the sole delivery. It must succeed
- # BEFORE the cursor advances — advancing first
- # would let a failed wake (previously swallowed
- # by the best-effort except below) permanently
- # lose the event. Mirrors the non-push
- # (api_server) self-post ordering above.
+ # Wake-only push sub: the wake is the sole delivery
+ # and must succeed BEFORE the cursor advances.
try:
await _push_wake()
sub_fail_counts.pop(sub_key, None)
except Exception as _wk_err:
- fails = sub_fail_counts.get(sub_key, 0) + 1
- sub_fail_counts[sub_key] = fails
- logger.warning(
+ await _delivery_failed(
"kanban notifier: wake-only delivery failed "
"for %s (attempt %d/%d): %s",
- sub["task_id"], fails,
- MAX_SEND_FAILURES, _wk_err, exc_info=True,
+ (sub["task_id"],),
+ "kanban notifier: dropping subscription "
+ "%s on %s after %d consecutive wake failures",
+ _wk_err, True,
)
- if fails >= MAX_SEND_FAILURES:
- logger.warning(
- "kanban notifier: dropping subscription "
- "%s on %s after %d consecutive wake failures",
- sub["task_id"], platform_str, fails,
- )
- await _to_thread_process_service(self._kanban_unsub, sub, board_slug)
- sub_fail_counts.pop(sub_key, None)
- else:
- # Rewind the pre-send claim so the next
- # tick retries the wake — the event is
- # NOT lost.
- await _to_thread_process_service(
- self._kanban_rewind,
- sub,
- d["cursor"],
- d.get("old_cursor", 0),
- board_slug,
- )
continue
- # Delivery complete (text ping for push adapters, wake
- # self-post for non-push, wake injection for wake-only
- # push subs): advance cursor. The cursor is the dedup
- # mechanism — it prevents re-delivery of the same
- # event on subsequent ticks.
+ # Delivery complete: advance the cursor (the dedup mechanism).
await _to_thread_process_service(
self._kanban_advance, sub, d["cursor"], board_slug,
)
if not _is_push_adapter:
- # Nothing left to deliver on this path (the wake,
- # if any, already succeeded above).
sub_fail_counts.pop(sub_key, None)
- # Unsubscribe only on archive. Completion (``done``)
- # remains reversible: controllers reopen completed
- # work for review corrections and continuation. The
- # retained cursor prevents replay while preserving the
- # original delivery and wake ownership for that cycle.
if _is_push_adapter and send_passive and _wake_kinds:
- # notify+wake: the text ping above was the
- # delivery and the cursor has advanced; the wake
- # injection stays best-effort.
+ # notify+wake: text ping was the delivery and the
+ # cursor has advanced; the wake stays best-effort,
+ # but log at WARNING so a persistently failing wake is visible.
try:
await _push_wake()
except Exception as _wk_err:
- # Best-effort: the notification itself already
- # delivered and the cursor has advanced, so a
- # broken wake path must not wedge the tick — but
- # log at WARNING with a traceback rather than
- # DEBUG so a persistently-failing wake is visible
- # in normal logs instead of silently no-op'ing.
logger.warning(
"kanban notifier: wakeup injection failed for %s: %s",
sub["task_id"], _wk_err, exc_info=True,
)
+ # Unsubscribe only on archive; ``done`` is reversible.
if task_terminal:
await _to_thread_process_service(
self._kanban_unsub, sub, board_slug,
@@ -1102,41 +837,30 @@ class GatewayKanbanWatchersMixin:
return
await asyncio.sleep(1)
- def _kanban_advance(
- self, sub: dict, cursor: int, board: Optional[str] = None,
- ) -> None:
- """Sync helper: advance a subscription's cursor. Runs in to_thread.
-
- ``board`` scopes the DB connection to the board that owns this
- subscription. Unsub cursors in one board can't touch another's.
- """
+ def _kanban_sub_op(self, board: Optional[str], op: str, sub: dict, **extra: Any) -> None:
+ """Sync helper (runs in to_thread): call ``kanban_db.<op>`` for one subscription on its board."""
from hermes_cli import kanban_db as _kb
conn = _kb.connect(board=board)
try:
- _kb.advance_notify_cursor(
+ getattr(_kb, op)(
conn,
task_id=sub["task_id"],
platform=sub["platform"],
chat_id=sub["chat_id"],
thread_id=sub.get("thread_id") or "",
- new_cursor=cursor,
+ **extra,
)
finally:
conn.close()
+ def _kanban_advance(
+ self, sub: dict, cursor: int, board: Optional[str] = None,
+ ) -> None:
+ """Advance a subscription's cursor on the board that owns it."""
+ self._kanban_sub_op(board, "advance_notify_cursor", sub, new_cursor=cursor)
+
def _kanban_unsub(self, sub: dict, board: Optional[str] = None) -> None:
- from hermes_cli import kanban_db as _kb
- conn = _kb.connect(board=board)
- try:
- _kb.remove_notify_sub(
- conn,
- task_id=sub["task_id"],
- platform=sub["platform"],
- chat_id=sub["chat_id"],
- thread_id=sub.get("thread_id") or "",
- )
- finally:
- conn.close()
+ self._kanban_sub_op(board, "remove_notify_sub", sub)
def _kanban_rewind(
self,
@@ -1145,21 +869,11 @@ class GatewayKanbanWatchersMixin:
old_cursor: int,
board: Optional[str] = None,
) -> None:
- """Sync helper: undo a claimed notification cursor after send failure."""
- from hermes_cli import kanban_db as _kb
- conn = _kb.connect(board=board)
- try:
- _kb.rewind_notify_cursor(
- conn,
- task_id=sub["task_id"],
- platform=sub["platform"],
- chat_id=sub["chat_id"],
- thread_id=sub.get("thread_id") or "",
- claimed_cursor=claimed_cursor,
- old_cursor=old_cursor,
- )
- finally:
- conn.close()
+ """Undo a claimed notification cursor after send failure."""
+ self._kanban_sub_op(
+ board, "rewind_notify_cursor", sub,
+ claimed_cursor=claimed_cursor, old_cursor=old_cursor,
+ )
async def _deliver_kanban_artifacts(
self,
@@ -1172,19 +886,10 @@ class GatewayKanbanWatchersMixin:
) -> None:
"""Upload artifact files referenced by a completed kanban task.
- Workers passing ``kanban_complete(artifacts=[...])`` ship absolute
- file paths through the completion event so downstream humans get
- the deliverable as a native upload instead of a path printed in
- chat.
-
- Sources scanned, in priority order:
- 1. ``event_payload['artifacts']`` (explicit list — preferred)
- 2. ``event_payload['summary']`` (truncated first line)
- 3. ``task.result`` (legacy fallback)
-
- Files are deduplicated, missing files are silently skipped (the
- path may have been mentioned for reference only), and delivery
- errors are logged but do not break the notifier loop.
+ Sources, in priority order: ``event_payload['artifacts']``,
+ ``event_payload['summary']``, then ``task.result`` (legacy). Paths are
+ deduplicated, missing files are skipped (may be mentioned for
+ reference only), and upload errors are logged, never raised.
"""
from pathlib import Path as _Path
@@ -1202,7 +907,6 @@ class GatewayKanbanWatchersMixin:
seen.add(expanded)
candidates.append(expanded)
- # 1. Explicit artifacts list in payload.
if isinstance(event_payload, dict):
raw = event_payload.get("artifacts")
if isinstance(raw, (list, tuple)):
@@ -1210,14 +914,12 @@ class GatewayKanbanWatchersMixin:
if isinstance(item, str):
_add(item)
- # 2. Paths embedded in the payload summary.
summary = event_payload.get("summary")
if isinstance(summary, str) and summary:
paths, _ = adapter.extract_local_files(summary)
for p in paths:
_add(p)
- # 3. Legacy: paths embedded in task.result.
if task is not None and getattr(task, "result", None):
result_text = str(task.result)
paths, _ = adapter.extract_local_files(result_text)
@@ -1237,8 +939,7 @@ class GatewayKanbanWatchersMixin:
from urllib.parse import quote as _quote
- # Partition images so they ride a single send_multiple_images call
- # on platforms that support batch image uploads (Signal/Slack RPCs).
+ # Images ride one send_multiple_images call (batch uploads on Signal/Slack).
image_paths = [p for p in candidates if _Path(p).suffix.lower() in _IMAGE_EXTS]
other_paths = [p for p in candidates if _Path(p).suffix.lower() not in _IMAGE_EXTS]
@@ -1273,25 +974,15 @@ class GatewayKanbanWatchersMixin:
async def _kanban_dispatcher_watcher(self) -> None:
"""Embedded kanban dispatcher — one tick every `dispatch_interval_seconds`.
- Gated by `kanban.dispatch_in_gateway` in config.yaml (default True).
- When true, the gateway hosts the single dispatcher for this profile:
- no separate `hermes kanban daemon` process needed. When false, the
- loop exits immediately and an external daemon is expected.
-
- Each tick calls :func:`kanban_db.dispatch_once` inside
- ``asyncio.to_thread`` so the SQLite WAL lock never blocks the
- event loop. Failures in one tick don't stop subsequent ticks —
- same pattern as `_kanban_notifier_watcher`.
-
- Shutdown: the loop checks ``self._running`` between ticks; gateway
- stop() flips it to False and cancels pending tasks, and the
- in-flight ``to_thread`` returns on its own after the current
- ``dispatch_once`` call finishes (typically <1ms on an idle board).
+ Gated by `kanban.dispatch_in_gateway` (default True); when false the
+ loop exits and an external `hermes kanban daemon` is expected. Each
+ tick runs :func:`kanban_db.dispatch_once` in a thread; one tick's
+ failure never stops the next. Shutdown: ``self._running`` is checked
+ between ticks and the in-flight ``to_thread`` returns on its own.
"""
- # Read config once at boot. If the user flips the flag later, they
- # restart the gateway; same pattern as every other background
- # watcher here. Honours HERMES_KANBAN_DISPATCH_IN_GATEWAY env var
- # as an escape hatch (false-y value disables without editing YAML).
+ # Config is read once at boot (restart to apply), except the
+ # auto-decompose toggle which is re-read every tick. The env var is
+ # an escape hatch to disable without editing YAML.
try:
from hermes_cli.config import load_config as _load_config
except Exception:
@@ -1320,13 +1011,8 @@ class GatewayKanbanWatchersMixin:
logger.warning("kanban dispatcher: kanban_db not importable; dispatcher disabled")
return
- # Single-dispatcher backstop. dispatch_in_gateway defaults to true, so a
- # new profile gateway (or a same-profile restart race) can silently
- # start a second dispatcher; concurrent dispatchers double reclaim
- # frequency, double claim-attempt events, and — with
- # wal_autocheckpoint=0 — concurrent manual WAL checkpoints can corrupt
- # index pages. The lock lives at the machine-global kanban root
- # (shared across profiles by design), so it serialises ALL gateways.
+ # Single-dispatcher backstop (see _acquire_singleton_lock). The lock
+ # lives at the machine-global kanban root, so it serialises ALL gateways.
self._kanban_dispatcher_lock_handle = None
_lock_path = _kb.kanban_home() / "kanban" / ".dispatcher.lock"
_lock_handle, _lock_state = _acquire_singleton_lock(_lock_path)
@@ -1355,40 +1041,31 @@ class GatewayKanbanWatchersMixin:
interval = 60.0
interval = max(interval, 1.0) # sanity floor — tighter than this is a footgun
- # Read max_spawn config to limit concurrent kanban tasks
max_spawn = kanban_cfg.get("max_spawn", None)
if max_spawn is not None:
logger.info("kanban dispatcher: max_spawn=%s", max_spawn)
- # Cap the number of simultaneously running tasks so slow workers
- # (local LLMs, resource-constrained hosts) don't pile up and time
- # out. When set, the dispatcher skips spawning when the board
- # already has this many tasks in 'running' status.
- raw_max_in_progress = kanban_cfg.get("max_in_progress", None)
- max_in_progress = None
- if raw_max_in_progress is not None:
+ def _positive_int_setting(key: str) -> Optional[int]:
+ """Parse an optional ``kanban.<key>`` int cap; None when unset or invalid (< 1 is invalid)."""
+ raw = kanban_cfg.get(key, None)
+ if raw is None:
+ return None
try:
- max_in_progress = int(raw_max_in_progress)
+ value = int(raw)
except (TypeError, ValueError):
- logger.warning(
- "kanban dispatcher: invalid kanban.max_in_progress=%r; ignoring",
- raw_max_in_progress,
- )
- max_in_progress = None
- else:
- if max_in_progress < 1:
- logger.warning(
- "kanban dispatcher: kanban.max_in_progress=%r is below 1; ignoring",
- raw_max_in_progress,
- )
- max_in_progress = None
- else:
- logger.info("kanban dispatcher: max_in_progress=%s", max_in_progress)
- # When the operator never set kanban.max_in_progress, fall back to a
- # memory-derived default (OOF-30/OOF-77): unbounded fan-out on small
- # hosted VMs has repeatedly swap-thrashed the whole machine. Explicit
- # config always wins; None stays None on hosts where total memory
- # can't be read (macOS/Windows dev machines).
+ logger.warning("kanban dispatcher: invalid kanban.%s=%r; ignoring", key, raw)
+ return None
+ if value < 1:
+ logger.warning("kanban dispatcher: kanban.%s=%r is below 1; ignoring", key, raw)
+ return None
+ logger.info("kanban dispatcher: %s=%d", key, value)
+ return value
+
+ # Cap simultaneously running tasks so slow workers don't pile up and
+ # time out. Explicit config wins; otherwise a memory-derived default
+ # (unbounded fan-out swap-thrashes small hosts), or None where total
+ # memory can't be read.
+ max_in_progress = _positive_int_setting("max_in_progress")
effective_max_in_progress = _kb.resolve_max_in_progress(max_in_progress)
if max_in_progress is None and effective_max_in_progress is not None:
logger.info(
@@ -1417,7 +1094,7 @@ class GatewayKanbanWatchersMixin:
)
failure_limit = _kb.DEFAULT_FAILURE_LIMIT
- # Read stale_timeout_seconds — 0 disables stale detection.
+ # 0 disables stale detection.
raw_stale = kanban_cfg.get("dispatch_stale_timeout_seconds", 0)
try:
stale_timeout_seconds = int(raw_stale or 0)
@@ -1429,18 +1106,12 @@ class GatewayKanbanWatchersMixin:
)
stale_timeout_seconds = 0
- # kanban.reconcile_orphans (config.yaml, default true): each tick,
- # requeue 'running' cards whose claim bookkeeping is broken (no
- # valid claim, dead/gone worker) — the zombie-card reconciliation
- # pass. Set false to keep orphans frozen for manual forensics.
+ # Requeue 'running' cards with broken claim bookkeeping (zombie-card
+ # reconciliation); false keeps orphans frozen for manual forensics.
reconcile_orphans = bool(kanban_cfg.get("reconcile_orphans", True))
- # Read kanban.default_assignee — fallback profile for tasks
- # created without an explicit assignee (e.g. via the dashboard).
- # When set, the dispatcher applies it to unassigned ready tasks
- # instead of skipping them indefinitely (#27145). Empty string
- # (the schema default) means "no fallback, keep skipping" —
- # backward-compatible with existing installs.
+ # Fallback profile for tasks created without an assignee (e.g. via the
+ # dashboard). Empty (the schema default) keeps skipping them.
default_assignee = (kanban_cfg.get("default_assignee") or "").strip() or None
if default_assignee:
logger.info(
@@ -1449,49 +1120,21 @@ class GatewayKanbanWatchersMixin:
default_assignee,
)
- # Read kanban.max_in_progress_per_profile — per-profile concurrency
- # cap (#21582). When set, no single profile gets more than N
- # workers running at once, even if the global max_in_progress
- # would allow it. Prevents one profile's local model / API quota
- # / browser pool from being overwhelmed by a fan-out.
- raw_per_profile = kanban_cfg.get("max_in_progress_per_profile", None)
- max_in_progress_per_profile = None
- if raw_per_profile is not None:
- try:
- max_in_progress_per_profile = int(raw_per_profile)
- except (TypeError, ValueError):
- logger.warning(
- "kanban dispatcher: invalid kanban.max_in_progress_per_profile=%r; ignoring",
- raw_per_profile,
- )
- max_in_progress_per_profile = None
- else:
- if max_in_progress_per_profile < 1:
- logger.warning(
- "kanban dispatcher: kanban.max_in_progress_per_profile=%r is below 1; ignoring",
- raw_per_profile,
- )
- max_in_progress_per_profile = None
- else:
- logger.info(
- "kanban dispatcher: max_in_progress_per_profile=%d",
- max_in_progress_per_profile,
- )
+ # Per-profile concurrency cap: no single profile's local model / API
+ # quota / browser pool gets overwhelmed by a fan-out.
+ max_in_progress_per_profile = _positive_int_setting("max_in_progress_per_profile")
- # Initial delay so the gateway finishes wiring adapters before the
- # dispatcher spawns workers (those workers may hit gateway notify
- # subscriptions etc.). Matches the notifier watcher's delay.
+ # Initial delay so adapters are wired before workers spawn (matches the notifier).
await asyncio.sleep(5)
- # Health telemetry mirrored from `_cmd_daemon`: warn when ready
- # queue is non-empty but spawns are 0 for N consecutive ticks —
- # usually means broken PATH, missing venv, or credential loss.
+ # Health telemetry (mirrors `_cmd_daemon`): warn when the ready queue
+ # is non-empty but spawns are 0 for N consecutive ticks — usually a
+ # broken PATH, missing venv, or credential loss.
HEALTH_WINDOW = 6
bad_ticks = 0
last_warn_at = 0
- # Avoid hot-looping corrupt-looking board DBs, but do not suppress
- # same-fingerprint retries forever: transient WAL/open races can
- # surface as "database disk image is malformed" for one tick.
+ # Quarantine corrupt-looking board DBs, but retry after a while:
+ # transient WAL/open races can look like "malformed" for one tick.
CORRUPT_BOARD_RETRY_AFTER_SECONDS = 300
disabled_corrupt_boards: dict[
str, tuple[tuple[str, int | None, int | None], float]
@@ -1522,13 +1165,10 @@ class GatewayKanbanWatchersMixin:
)
def _tick_once_for_board(slug: str) -> "Optional[object]":
- """Run one dispatch_once for a specific board.
+ """Run one dispatch_once for a specific board (in a worker thread).
- Runs in a worker thread via `asyncio.to_thread`. `board=slug`
- is passed through `dispatch_once` so `resolve_workspace` and
- `_default_spawn` see the right paths. The per-board DB is
- opened explicitly so concurrent boards never share a
- connection handle or accidentally claim across each other.
+ The per-board DB is opened explicitly so boards never share a
+ connection or claim across each other.
"""
conn = None
fingerprint = _board_db_fingerprint(slug)
@@ -1555,13 +1195,9 @@ class GatewayKanbanWatchersMixin:
)
disabled_corrupt_boards.pop(slug, None)
try:
+ # No explicit init_db(): connect() runs the migration once per
+ # process (see the matching note in _kanban_notifier_watcher).
conn = _kb.connect(board=slug)
- # `connect()` runs the schema + idempotent migration on
- # first open per process; the previous explicit
- # `init_db()` call here busted the per-process cache and
- # re-ran the migration on a second connection, racing
- # the first. See the matching comment in
- # `_kanban_notifier_watcher` and issue #21378.
return _kb.dispatch_once(
conn,
board=slug,
@@ -1573,21 +1209,6 @@ class GatewayKanbanWatchersMixin:
max_in_progress_per_profile=max_in_progress_per_profile,
reconcile_orphans=reconcile_orphans,
)
- except sqlite3.DatabaseError as exc:
- if _is_corrupt_board_db_error(exc):
- disabled_corrupt_boards[slug] = (fingerprint, time.monotonic())
- logger.error(
- "kanban dispatcher: board %s database %s is not a valid "
- "SQLite database; pausing dispatch for this board until "
- "the file changes, the gateway restarts, or the "
- "quarantine timer expires. Move or restore the file, "
- "then run `hermes kanban init` if you need a fresh board.",
- slug,
- fingerprint[0],
- )
- return None
- logger.exception("kanban dispatcher: tick failed on board %s", slug)
- return None
except Exception as exc:
if _is_corrupt_board_db_error(exc):
disabled_corrupt_boards[slug] = (fingerprint, time.monotonic())
@@ -1608,47 +1229,36 @@ class GatewayKanbanWatchersMixin:
with contextlib.suppress(Exception):
conn.close()
+ def _list_boards() -> list:
+ try:
+ return _kb.list_boards(include_archived=False)
+ except Exception:
+ return [_kb.read_board_metadata(_kb.DEFAULT_BOARD)]
+
def _tick_once() -> "list[tuple[str, Optional[object]]]":
"""Run one dispatch_once per board. Returns (slug, result) pairs.
- Enumerating boards on every tick keeps the dispatcher honest
- when users create a new board mid-run: no restart required,
- the next tick picks it up automatically.
+ Boards are enumerated every tick so a board created mid-run is
+ picked up without a restart.
"""
- try:
- boards = _kb.list_boards(include_archived=False)
- except Exception:
- boards = [_kb.read_board_metadata(_kb.DEFAULT_BOARD)]
out: list[tuple[str, "Optional[object]"]] = []
- for b in boards:
+ for b in _list_boards():
slug = b.get("slug") or _kb.DEFAULT_BOARD
out.append((slug, _tick_once_for_board(slug)))
return out
def _ready_nonempty() -> bool:
- """Cheap probe: is there at least one ready+assigned+unclaimed
- task on ANY board whose assignee maps to a real Hermes profile
- (i.e. one the dispatcher would actually spawn for)?
-
- Tasks assigned to control-plane lanes (e.g. ``orion-cc``,
- ``orion-research``) are pulled by terminals via
- ``claim_task`` directly and never spawnable, so a queue full
- of those is "correctly idle", not "stuck". Filtering them out
- here keeps the stuck-warn fire only on real failures (broken
- PATH, missing venv, credential loss for a real Hermes profile).
+ """Is there a ready+assigned+unclaimed task on ANY board that the
+ dispatcher would actually spawn for?
+
+ Control-plane lanes (e.g. ``orion-cc``) are pulled by terminals
+ via ``claim_task`` and never spawnable — a queue full of those is
+ "correctly idle", not "stuck". The review column is probed only
+ when review dispatch is on (same gate as the dispatcher): a task
+ waiting for a human reviewer is idle, not stuck.
"""
- # Only probe the review column when autonomous review dispatch is
- # actually on. With ``review_dispatch`` off (the default — no
- # sdlc-review agent), a task parked in 'review' is "correctly idle"
- # waiting for a human, not a stuck dispatcher; probing it here would
- # fire a false "dispatcher stuck" warning that never clears. Shares
- # the exact gate the dispatcher uses so the two can't drift.
_review_probe = _kb.review_dispatch_enabled()
- try:
- boards = _kb.list_boards(include_archived=False)
- except Exception:
- boards = [_kb.read_board_metadata(_kb.DEFAULT_BOARD)]
- for b in boards:
+ for b in _list_boards():
slug = b.get("slug") or _kb.DEFAULT_BOARD
conn = None
try:
@@ -1665,29 +1275,11 @@ class GatewayKanbanWatchersMixin:
conn.close()
return False
- # Auto-decompose: turn fresh triage tasks into ready workgraphs
- # before the dispatcher fans out workers. Gated by
- # ``kanban.auto_decompose`` (default True). Capped by
- # ``kanban.auto_decompose_per_tick`` (default 3) so a bulk-load
- # of triage tasks doesn't burst-spend the aux LLM in one tick;
- # remainder defers to subsequent ticks.
- #
- # The flag is re-read from config EVERY tick (#49638) rather than
- # captured once at boot. Auto-decompose is a safety toggle: a user who
- # sees it fan out and run tasks they didn't intend reaches for
- # ``kanban.auto_decompose: false`` to STOP it — and that must take
- # effect on the next tick, not require a gateway restart. (Reported:
- # auto-decompose created and launched destructive tasks while the user
- # was still typing the task description, and the flag "couldn't be
- # disabled" because the gateway had captured its boot-time value.)
- def _read_auto_decompose_settings() -> tuple[bool, int]:
- """Re-resolve (enabled, per_tick) from current config each tick."""
- return _resolve_auto_decompose_settings(_load_config)
-
def _auto_decompose_tick(auto_decompose_per_tick: int) -> int:
- """Run the auto-decomposer for up to N triage tasks across all
- boards. Returns the number of triage tasks that were
- successfully decomposed or specified this tick.
+ """Auto-decompose up to N triage tasks across all boards into
+ ready workgraphs before dispatch fans out; the per-tick cap keeps
+ a bulk triage load from burst-spending the aux LLM. Returns the
+ number decomposed/specified.
"""
try:
from hermes_cli import kanban_decompose as _decomp
@@ -1696,20 +1288,14 @@ class GatewayKanbanWatchersMixin:
"kanban auto-decompose: import failed (%s); skipping", exc,
)
return 0
- try:
- boards = _kb.list_boards(include_archived=False)
- except Exception:
- boards = [_kb.read_board_metadata(_kb.DEFAULT_BOARD)]
attempted = 0
successes = 0
- for b in boards:
+ for b in _list_boards():
slug = b.get("slug") or _kb.DEFAULT_BOARD
if attempted >= auto_decompose_per_tick:
break
- # Pin this board for the duration of the call — same
- # pattern as the dashboard specify endpoint. The
- # decomposer module connects with no board kwarg and
- # relies on the env var.
+ # Pin the board via env for the call: the decomposer connects
+ # with no board kwarg (same pattern as the dashboard specify endpoint).
prev_env = os.environ.get("HERMES_KANBAN_BOARD")
try:
os.environ["HERMES_KANBAN_BOARD"] = slug
@@ -1748,8 +1334,7 @@ class GatewayKanbanWatchersMixin:
slug, tid,
)
else:
- # Common no-op reasons (no aux client configured) shouldn't
- # spam logs every tick. Log at debug.
+ # Common no-op reasons (no aux client) must not spam logs every tick.
logger.debug(
"kanban auto-decompose [%s]: %s skipped: %s",
slug, tid, outcome.reason,
@@ -1766,8 +1351,8 @@ class GatewayKanbanWatchersMixin:
)
while self._running:
try:
- # Reap zombie children before per-board work so a board DB
- # failure cannot block cleanup of unrelated workers.
+ # Reap zombies before per-board work so a board DB failure
+ # cannot block cleanup of unrelated workers.
pids = await _to_thread_process_service(_kb.reap_worker_zombies)
if pids:
logger.info(
@@ -1779,17 +1364,15 @@ class GatewayKanbanWatchersMixin:
logger.exception("kanban dispatcher: zombie reaper failed")
try:
- # Global emergency stop (`hermes pause`): skip auto-decompose
- # and dispatch entirely — no new workers while paused. Running
- # workers finish naturally; zombie reaping above still runs.
+ # Emergency stop (`hermes pause`): no auto-decompose or
+ # dispatch while paused; running workers finish naturally.
if not _kanban_dispatch_allowed():
ready_pending = False
bad_ticks = 0
else:
- # Re-read the auto-decompose toggle live each tick so a user
- # flipping kanban.auto_decompose=false to STOP runaway fan-out
- # takes effect on the next tick, not on gateway restart (#49638).
- _ad_enabled, _ad_per_tick = _read_auto_decompose_settings()
+ # Re-read the auto-decompose toggle live so disabling it
+ # takes effect on the next tick, not on restart.
+ _ad_enabled, _ad_per_tick = _resolve_auto_decompose_settings(_load_config)
if _ad_enabled:
await _to_thread_process_service(_auto_decompose_tick, _ad_per_tick)
results = await _to_thread_process_service(_tick_once)
@@ -1797,8 +1380,7 @@ class GatewayKanbanWatchersMixin:
for slug, res in (results or []):
if res is not None and getattr(res, "spawned", None):
any_spawned = True
- # Quiet by default — only log when something actually
- # happened, so an idle gateway stays silent.
+ # Quiet by default: an idle gateway stays silent.
logger.info(
"kanban dispatcher [%s]: spawned=%d reclaimed=%d "
"crashed=%d timed_out=%d promoted=%d auto_blocked=%d",
@@ -1834,8 +1416,7 @@ class GatewayKanbanWatchersMixin:
except Exception:
logger.exception("kanban dispatcher: unexpected watcher error")
- # Sleep in 1s slices so shutdown is snappy — otherwise a stop()
- # waits up to `interval` seconds for the current sleep to finish.
+ # Sleep in 1s slices so stop() never waits a full interval.
slept = 0.0
while slept < interval and self._running:
await asyncio.sleep(min(1.0, interval - slept))
diff --git a/gateway/lifecycle_ledger.py b/gateway/lifecycle_ledger.py
index 28b04131af5..39850139234 100644
--- a/gateway/lifecycle_ledger.py
+++ b/gateway/lifecycle_ledger.py
@@ -1,36 +1,21 @@
-"""Gateway lifecycle ledger — durable termination-reason evidence (NS-608).
-
-The gateway already has *graceful* shutdown forensics
-(:mod:`gateway.shutdown_forensics` — who sent the SIGTERM) and an exit-path
-diagnostic log (``gateway-exit-diag.log`` — every way ``asyncio.run`` can
-return). What it does NOT have is any record of an **unclean death**: a
-SIGKILL, a kernel OOM kill, or the whole VM dying takes the process out
-before any handler runs, so the next boot has no idea the previous life
-ended violently — support tickets like NS-608 then require manually
-cross-correlating four log files and two external APIs to answer "what
-killed the gateway?".
-
-This module closes that gap with a tiny state machine persisted to
-``<HERMES_HOME>/state/gateway.lifecycle.json``:
-
-* On startup, :func:`record_startup` reads the sentinel left by the
- previous life. ``phase == "running"`` means that life never reached any
- exit path → it died uncleanly. The finding — including the last
- heartbeat's memory sample, which is the closest thing to a pre-death
- telemetry snapshot — is appended to ``gateway-exit-diag.log`` as a
- ``gateway.previous_unclean_exit`` record and logged at WARNING. The
- sentinel is then rewritten as ``phase=running`` for the new life.
-* On every clean exit path, :func:`mark_exited` rewrites the sentinel as
- ``phase=exited`` with the exit code and a reason string. Wired into
- ``_exit_after_graceful_shutdown`` (the single funnel for all graceful
- exits, #53107) and the two watchdog ``os._exit`` sites in
- :mod:`gateway.shutdown_watchdog`.
-
-:func:`sample_memory` provides the cheap (<1ms, pure /proc reads) memory
-snapshot that :func:`gateway.shutdown_watchdog.write_loop_heartbeat`
-embeds in the 30s heartbeat — giving every unclean-death report a
-"memory available N seconds before death" data point so OOM crash cycles
-are classifiable from the volume alone (no Prometheus retention races).
+"""Gateway lifecycle ledger — durable termination-reason evidence.
+
+Graceful shutdowns already leave forensics (:mod:`gateway.shutdown_forensics`,
+``gateway-exit-diag.log``); an **unclean death** (SIGKILL, kernel OOM kill, VM
+death) runs no handler, so the next boot would otherwise have no record of it.
+
+A tiny state machine persisted to ``<HERMES_HOME>/state/gateway.lifecycle.json``
+closes that gap:
+
+* :func:`record_startup` reads the previous life's sentinel. ``phase ==
+ "running"`` means no exit path ran → unclean death. The finding (with the
+ last heartbeat's memory sample) is appended to ``gateway-exit-diag.log`` as a
+ ``gateway.previous_unclean_exit`` record and logged at WARNING, then the
+ sentinel is rewritten as ``phase=running`` for the new life.
+* :func:`mark_exited` rewrites the sentinel as ``phase=exited`` on every clean
+ exit path (``_exit_after_graceful_shutdown`` and the watchdog ``os._exit`` sites).
+* :func:`sample_memory` is the cheap /proc snapshot the 30s loop heartbeat
+ embeds, so OOM crash cycles are classifiable from the volume alone.
Everything here is best-effort: a forensics failure must never affect the
gateway lifecycle it is observing.
@@ -53,9 +38,8 @@ _LIFECYCLE_RELATIVE = ("state", "gateway.lifecycle.json")
_EXIT_DIAG_RELATIVE = ("logs", "gateway-exit-diag.log")
_STATE_DB_RELATIVE = ("state.db",)
-# Heuristic OOM-suspicion thresholds applied to the last heartbeat's memory
-# sample. Deliberately conservative: this only annotates the report with a
-# hint; classification stays with the human reading the evidence.
+# Heuristic OOM-suspicion thresholds on the last heartbeat's memory sample.
+# Deliberately conservative: only a hint; classification stays with the reader.
_LOW_MEM_AVAILABLE_KIB = 64 * 1024 # < 64 MiB available
_LOW_MEM_AVAILABLE_FRACTION = 0.05 # < 5% of MemTotal available
@@ -70,10 +54,14 @@ def _process_hermes_home() -> Path:
return get_hermes_home()
+def _home_path(home: Optional[Path], relative: tuple) -> Path:
+ base = home if home is not None else _process_hermes_home()
+ return base.joinpath(*relative)
+
+
def get_lifecycle_sentinel_path(home: Optional[Path] = None) -> Path:
"""Return ``<HERMES_HOME>/state/gateway.lifecycle.json``."""
- base = home if home is not None else _process_hermes_home()
- return base.joinpath(*_LIFECYCLE_RELATIVE)
+ return _home_path(home, _LIFECYCLE_RELATIVE)
def sample_memory() -> Dict[str, Any]:
@@ -101,10 +89,9 @@ def sample_memory() -> Dict[str, Any]:
meminfo[key] = int(line.split()[1])
if len(meminfo) == len(wanted):
break
- if "MemTotal" in meminfo:
- sample["mem_total_kib"] = meminfo["MemTotal"]
- if "MemAvailable" in meminfo:
- sample["mem_available_kib"] = meminfo["MemAvailable"]
+ for src, dst in (("MemTotal", "mem_total_kib"), ("MemAvailable", "mem_available_kib")):
+ if src in meminfo:
+ sample[dst] = meminfo[src]
if "SwapTotal" in meminfo and "SwapFree" in meminfo:
sample["swap_used_kib"] = meminfo["SwapTotal"] - meminfo["SwapFree"]
except (OSError, ValueError, IndexError):
@@ -134,8 +121,7 @@ def _write_sentinel(payload: Dict[str, Any], home: Optional[Path]) -> None:
def _append_exit_diag(record: Dict[str, Any], home: Optional[Path]) -> None:
"""Append a JSON line to gateway-exit-diag.log (same format as the CLI's
``_exit_diag`` records so existing tooling greps both)."""
- base = home if home is not None else _process_hermes_home()
- path = base.joinpath(*_EXIT_DIAG_RELATIVE)
+ path = _home_path(home, _EXIT_DIAG_RELATIVE)
try:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8") as fh:
@@ -159,8 +145,7 @@ def _pid_alive_with_start_time(pid: Any, start_time: Any) -> bool:
return False
try:
# NOT os.kill(pid, 0): on Windows that sends CTRL_C_EVENT to the
- # target's console group (bpo-14484). _pid_exists is the repo's
- # canonical no-kill cross-platform probe (psutil-backed).
+ # target's console group. _pid_exists is the canonical no-kill probe.
from gateway.status import _pid_exists
if not _pid_exists(pid_int):
@@ -173,9 +158,7 @@ def _pid_alive_with_start_time(pid: Any, start_time: Any) -> bool:
from gateway.status import get_process_start_time
actual = get_process_start_time(pid_int)
- if actual is None:
- return True
- return abs(float(actual) - float(start_time)) <= 2.0
+ return actual is None or abs(float(actual) - float(start_time)) <= 2.0
except Exception:
return True
@@ -196,8 +179,7 @@ def detect_unclean_exit(home: Optional[Path] = None) -> Optional[Dict[str, Any]]
"prior_start_time": sentinel.get("start_time"),
}
- # Enrich with the last heartbeat: when did the loop last prove liveness,
- # and what did memory look like at that moment?
+ # Enrich with the last heartbeat: last proven liveness and memory at that moment.
try:
from gateway.shutdown_watchdog import get_loop_heartbeat_path
@@ -226,29 +208,17 @@ def detect_unclean_exit(home: Optional[Path] = None) -> Optional[Dict[str, Any]]
def check_state_db_integrity(home: Optional[Path] = None) -> str:
"""Return ``"ok"``, ``"absent"``, or the first ``quick_check`` complaint.
- Called only after an unclean death, because that is when the store may
- have been torn: a SIGKILL landing on a gateway mid-WAL-checkpoint can
- leave half-written b-tree pages behind (see
- ``_enforce_macos_synchronous_full`` in :mod:`hermes_state` — macOS
- ``fsync`` guarantees neither data-on-platter nor write ordering).
-
- ``quick_check(1)`` stops at the first problem, so this costs ~2s on a
- healthy 500MB store and less on a damaged one — cheap enough for a path
- that runs at most once per unclean boot, far too expensive for every
- boot. Corruption used to sit undetected for days (2026-08-26 → 08-30)
- because nothing ever looked.
-
- The connection is opened normally, not read-only: a WAL store needs its
- -shm sidecar for a read-only open. The PRAGMA itself writes nothing.
- Never raises — this is forensics, not lifecycle.
+ Called only after an unclean death — a SIGKILL mid-WAL-checkpoint can leave
+ half-written b-tree pages (see ``_enforce_macos_synchronous_full`` in
+ :mod:`hermes_state`). ``quick_check(1)`` stops at the first problem (~2s on
+ a healthy 500MB store): cheap once per unclean boot, too costly every boot.
+ Opened normally, not read-only: a WAL store needs its -shm sidecar for a
+ read-only open, and the PRAGMA itself writes nothing. Never raises.
"""
- base = home if home is not None else _process_hermes_home()
- path = base.joinpath(*_STATE_DB_RELATIVE)
+ path = _home_path(home, _STATE_DB_RELATIVE)
if not path.exists():
return "absent"
try:
- # A WAL store cannot be opened read-only without its -shm sidecar, so
- # open normally; quick_check itself writes nothing.
conn = sqlite3.connect(str(path))
try:
row = conn.execute("PRAGMA quick_check(1)").fetchone()
@@ -273,9 +243,7 @@ def record_startup(home: Optional[Path] = None) -> Optional[Dict[str, Any]]:
try:
evidence = detect_unclean_exit(home)
if evidence is not None:
- # The death may have torn the store. This is the only moment
- # we know to look, and looking is what turns a 3.5-day silent
- # corruption into a startup warning.
+ # The death may have torn the store; this is the only moment we know to look.
verdict = check_state_db_integrity(home=home)
evidence["state_db_integrity"] = verdict
if verdict not in ("ok", "absent"):
@@ -285,13 +253,12 @@ def record_startup(home: Optional[Path] = None) -> Optional[Dict[str, Any]]:
"repaired. Run `hermes doctor`.",
verdict,
)
- record = {
+ _append_exit_diag({
"ts": datetime.now(timezone.utc).isoformat(),
"tag": "gateway.previous_unclean_exit",
"pid": os.getpid(),
**evidence,
- }
- _append_exit_diag(record, home)
+ }, home)
logger.warning(
"Previous gateway life (pid=%s, started_at=%s) exited UNCLEANLY "
"(no exit path ran — SIGKILL / OOM / VM death). "
@@ -312,13 +279,10 @@ def record_startup(home: Optional[Path] = None) -> Optional[Dict[str, Any]]:
"start_time": time.time(),
"started_at": datetime.now(timezone.utc).isoformat(),
}
- # Carry the verdict on the PREVIOUS life forward on the new
- # sentinel: it is the only place the finding survives in
- # machine-readable form (the exit-diag log is append-only prose
- # for humans), and /api/status reads it to tell the user "your
- # agent restarted after (suspected) running out of memory"
- # (NS-656). Scoped to this life only — the next clean exit or
- # boot rewrites the sentinel and the flags age out with it.
+ # Carry the verdict on the PREVIOUS life forward on the new sentinel: it
+ # is the only machine-readable copy (the exit-diag log is append-only
+ # prose) and /api/status reads it to report an OOM restart. Scoped to
+ # this life only — the next clean exit or boot rewrites the sentinel.
if evidence is not None:
claim["prior_unclean_exit"] = True
if evidence.get("suspected_oom"):
@@ -336,37 +300,31 @@ def mark_exited(
) -> None:
"""Mark the current life as cleanly exited. Idempotent, never raises.
- Only rewrites the sentinel when it is provably owned by this process —
- during a ``--replace`` takeover the replacement claims the sentinel
- before the old process finishes teardown, and the old life must not
- clobber the new owner's ``running`` phase on its way out. A sentinel
- with ``pid=None`` (or a malformed pid) has *unknown* ownership and is
- likewise left alone: we must not overwrite evidence we cannot prove is
- ours with a ``clean exit`` claim.
+ Only rewrites the sentinel when it is provably owned by this process:
+ during a ``--replace`` takeover the replacement claims the sentinel before
+ the old process finishes teardown, and the old life must not clobber the
+ new owner's ``running`` phase. A sentinel with ``pid=None`` (or malformed)
+ has unknown ownership and is likewise left alone.
"""
try:
sentinel = _read_json(get_lifecycle_sentinel_path(home))
if sentinel is not None and sentinel.get("pid") != os.getpid():
return
- _write_sentinel(
- {
- "phase": "exited",
- "pid": os.getpid(),
- "exit_code": exit_code,
- "exit_reason": reason,
- "exited_at": datetime.now(timezone.utc).isoformat(),
- },
- home,
- )
+ _write_sentinel({
+ "phase": "exited",
+ "pid": os.getpid(),
+ "exit_code": exit_code,
+ "exit_reason": reason,
+ "exited_at": datetime.now(timezone.utc).isoformat(),
+ }, home)
except Exception:
logger.debug("Failed to mark lifecycle sentinel exited", exc_info=True)
def read_prior_exit_label(profile_home: Path) -> str:
- """Container-boot helper: one-word summary of how the profile's last
- gateway life ended. ``clean`` / ``unclean`` / ``unknown`` (no sentinel
- or never ran). Read-only and exception-free — used by
- ``hermes_cli.container_boot`` to annotate ``container-boot.log``.
+ """Container-boot helper: ``clean`` / ``unclean`` / ``unknown`` summary of
+ how the profile's last gateway life ended. Read-only, exception-free;
+ used by ``hermes_cli.container_boot`` to annotate ``container-boot.log``.
"""
try:
sentinel = _read_json(get_lifecycle_sentinel_path(profile_home))
@@ -376,8 +334,7 @@ def read_prior_exit_label(profile_home: Path) -> str:
if phase == "exited":
return "clean"
if phase == "running":
- # At container boot the old PID namespace is gone — any
- # "running" sentinel is from a life that never exited cleanly.
+ # Old PID namespace is gone at container boot — never exited cleanly.
return "unclean"
except Exception:
pass
diff --git a/gateway/memory_monitor.py b/gateway/memory_monitor.py
index 272eb6e771e..3ac51b531ea 100644
--- a/gateway/memory_monitor.py
+++ b/gateway/memory_monitor.py
@@ -1,31 +1,11 @@
"""Periodic process memory usage logging for the gateway.
-Ported from cline/cline#10343 (src/standalone/memory-monitor.ts).
-
-The gateway is a long-lived process that accumulates memory as it caches
-agent instances, session transcripts, tool schemas, memory providers, MCP
-connections, etc. A slow leak in any of those subsystems is invisible
-in a single log line — you only see it by watching RSS climb over hours.
-
-This module emits a single structured ``[MEMORY] ...`` line every N
-minutes (default 5) so maintainers investigating a suspected leak can
-grep ``agent.log`` / ``gateway.log`` for a time series of RSS + Python
-GC stats. The timer runs in a background thread and shuts down cleanly
-with the gateway.
-
-Design notes (parity with the Cline port):
- * Grep-friendly single-line format beginning ``[MEMORY]``.
- * Final snapshot logged on shutdown so "last RSS before exit" is
- always in the log.
- * Baseline snapshot logged immediately on start.
- * Daemon thread — never blocks process exit.
- * Uses ``resource`` (stdlib, Linux/macOS) first and falls back to
- ``psutil`` when ``resource`` isn't available (Windows). Both are
- optional; when neither works we emit a single WARNING and disable
- the monitor rather than crashing the gateway.
-
-Config: ``logging.memory_monitor`` in ``config.yaml`` — see
-``hermes_cli/config.py`` for the defaults block.
+Ported from cline/cline#10343 (src/standalone/memory-monitor.ts). Emits one
+grep-friendly ``[MEMORY] ...`` line every N seconds (default 300) from a daemon
+thread so slow leaks in the long-lived gateway show up as an RSS time series in
+``agent.log`` / ``gateway.log``. A baseline snapshot is logged on start and a
+final one on stop. Uses stdlib ``resource`` first, ``psutil`` as fallback
+(Windows); if neither works the monitor warns once and stays disabled.
"""
from __future__ import annotations
@@ -46,85 +26,49 @@ _BYTES_TO_MB = 1024 * 1024
_monitor_thread: Optional[threading.Thread] = None
_stop_event: Optional[threading.Event] = None
_start_time: Optional[float] = None
-_interval_seconds: float = 300.0 # 5 minutes
+_interval_seconds: float = 300.0
_lock = threading.Lock()
def _get_rss_mb() -> Optional[int]:
- """Return current process resident set size in MB, or None if unavailable.
-
- Tries ``resource.getrusage`` first (Linux/macOS, no extra deps), then
- falls back to ``psutil`` which is an optional hermes-agent dep.
- """
- # Linux / macOS — resource is stdlib. On Linux ru_maxrss is in KB,
- # on macOS it is in bytes (yes, really). We use it as a cheap
- # "current" RSS — ru_maxrss reports the high-water mark for the
- # process, which is what you actually want for leak detection.
+ """Return process RSS high-water mark in MB, or None if unavailable."""
try:
import resource
+ # ru_maxrss is KB on Linux but bytes on macOS.
maxrss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
- if sys.platform == "darwin":
- return int(maxrss / _BYTES_TO_MB)
- # Linux / other unices: KB
- return int(maxrss / 1024)
+ return int(maxrss / (_BYTES_TO_MB if sys.platform == "darwin" else 1024))
except Exception:
pass
-
- # Fallback: psutil (Windows, or unusual unix without resource).
try:
import psutil # type: ignore
- rss = psutil.Process(os.getpid()).memory_info().rss
- return int(rss / _BYTES_TO_MB)
+ return int(psutil.Process(os.getpid()).memory_info().rss / _BYTES_TO_MB)
except Exception:
return None
def log_memory_usage(prefix: str = "") -> None:
- """Log current memory usage in a grep-friendly ``[MEMORY] ...`` line.
-
- Safe to call on-demand from any thread at important lifecycle
- moments (after shutdown, after context compression, etc.).
+ """Log current memory usage as ``[MEMORY] [<prefix> ]rss=... gc=... threads=... uptime=...``.
- Parameters
- ----------
- prefix
- Optional extra tag inserted after ``[MEMORY]`` — e.g.
- ``"baseline"``, ``"shutdown"``.
+ Safe to call on-demand from any thread at lifecycle moments.
"""
rss = _get_rss_mb()
uptime = int(time.monotonic() - _start_time) if _start_time else 0
- # gc.get_stats() returns per-generation collection counts; the sum
- # is a cheap proxy for "how much garbage have we created".
try:
gc_counts = gc.get_count() # (gen0, gen1, gen2)
except Exception:
gc_counts = (0, 0, 0)
- # Thread count is a handy correlate when diagnosing thread leaks.
try:
thread_count = threading.active_count()
except Exception:
thread_count = 0
tag = f"{prefix} " if prefix else ""
- if rss is None:
- logger.info(
- "[MEMORY] %srss=unavailable gc=%s threads=%d uptime=%ds",
- tag,
- gc_counts,
- thread_count,
- uptime,
- )
- else:
- logger.info(
- "[MEMORY] %srss=%dMB gc=%s threads=%d uptime=%ds",
- tag,
- rss,
- gc_counts,
- thread_count,
- uptime,
- )
+ rss_text = "unavailable" if rss is None else f"{rss}MB"
+ logger.info(
+ "[MEMORY] %srss=%s gc=%s threads=%d uptime=%ds", tag, rss_text, gc_counts, thread_count, uptime
+ )
def _monitor_loop(stop_event: threading.Event, interval: float) -> None:
@@ -133,38 +77,21 @@ def _monitor_loop(stop_event: threading.Event, interval: float) -> None:
try:
log_memory_usage()
except Exception as e:
- # Never let the monitor crash the gateway; just log and carry on.
+ # Never let the monitor crash the gateway.
logger.debug("Memory monitor iteration failed: %s", e)
def start_memory_monitoring(interval_seconds: float = 300.0) -> bool:
- """Start periodic memory usage logging in a daemon thread.
-
- Logs immediately to capture a baseline, then every ``interval_seconds``.
- Safe to call multiple times — subsequent calls are no-ops while the
- first monitor is still running.
-
- Parameters
- ----------
- interval_seconds
- How often to log. Default 300s (5 minutes), matching the
- upstream cline/cline implementation.
-
- Returns
- -------
- bool
- True if a fresh monitor thread was started, False if one was
- already running or if memory introspection isn't available.
+ """Start periodic memory logging in a daemon thread (baseline logged immediately).
+
+ Returns True if a fresh monitor was started; False if one is already running
+ or RSS introspection is unavailable (warned once).
"""
global _monitor_thread, _stop_event, _start_time, _interval_seconds
with _lock:
if _monitor_thread is not None and _monitor_thread.is_alive():
return False
-
- # Sanity-check that we can read RSS at all. If neither resource
- # nor psutil works, no point spinning a thread that can only log
- # "rss=unavailable" forever — warn once and bail.
if _get_rss_mb() is None:
logger.warning(
"[MEMORY] Memory monitoring unavailable: neither resource.getrusage "
@@ -175,10 +102,7 @@ def start_memory_monitoring(interval_seconds: float = 300.0) -> bool:
_start_time = time.monotonic()
_interval_seconds = float(interval_seconds)
_stop_event = threading.Event()
-
- # Baseline snapshot before the loop starts.
log_memory_usage(prefix="baseline")
-
_monitor_thread = threading.Thread(
target=_monitor_loop,
args=(_stop_event, _interval_seconds),
@@ -186,29 +110,19 @@ def start_memory_monitoring(interval_seconds: float = 300.0) -> bool:
daemon=True,
)
_monitor_thread.start()
-
- logger.info(
- "[MEMORY] Periodic memory monitoring started (interval: %ds)",
- int(_interval_seconds),
- )
+ logger.info("[MEMORY] Periodic memory monitoring started (interval: %ds)", int(_interval_seconds))
return True
def stop_memory_monitoring(timeout: float = 2.0) -> None:
- """Stop the monitor thread and log a final snapshot.
-
- Safe to call even if ``start_memory_monitoring()`` was never called.
- """
+ """Stop the monitor thread and log a final ``shutdown`` snapshot. No-op if never started."""
global _monitor_thread, _stop_event
with _lock:
if _stop_event is None or _monitor_thread is None:
return
-
- # Final snapshot before teardown so "last RSS" is always in the log.
with contextlib.suppress(Exception):
log_memory_usage(prefix="shutdown")
-
_stop_event.set()
thread = _monitor_thread
_monitor_thread = None
diff --git a/gateway/mirror.py b/gateway/mirror.py
index 08dc3e74afa..e61c756c88a 100644
--- a/gateway/mirror.py
+++ b/gateway/mirror.py
@@ -1,12 +1,10 @@
"""
Session mirroring for cross-platform message delivery.
-When a message is sent to a platform (via send_message or cron delivery),
-this module appends a "delivery-mirror" record to the target session's
-transcript so the receiving-side agent has context about what was sent.
-
-Standalone -- works from CLI, cron, and gateway contexts without needing
-the full SessionStore machinery.
+When a message is sent to a platform (send_message or cron delivery), append
+a "delivery-mirror" record to the target session's transcript so the
+receiving-side agent knows what was sent. Standalone: works from CLI, cron
+and gateway contexts without the full SessionStore machinery.
"""
import json
@@ -22,139 +20,91 @@ _SESSIONS_DIR = get_hermes_home() / "sessions"
_SESSIONS_INDEX = _SESSIONS_DIR / "sessions.json"
+def _origin_user_id(entry: dict) -> str:
+ return str((entry.get("origin") or {}).get("user_id") or "")
+
+
def mirror_to_session(
- platform: str,
- chat_id: str,
- message_text: str,
- source_label: str = "cli",
- thread_id: Optional[str] = None,
- user_id: Optional[str] = None,
- role: str = "assistant",
- session_id: Optional[str] = None,
+ platform: str, chat_id: str, message_text: str, source_label: str = "cli",
+ thread_id: Optional[str] = None, user_id: Optional[str] = None,
+ role: str = "assistant", session_id: Optional[str] = None,
) -> bool:
- """
- Append a delivery-mirror message to the target session's transcript.
-
- Finds the gateway session that matches the given platform + chat_id,
- then writes a mirror entry to both the JSONL transcript and SQLite DB.
-
- ``session_id``: when the caller already KNOWS the exact session (e.g. the
- cron in_channel seed, which just created the row via
- ``get_or_create_session``), pass it to skip the origin-scan heuristics
- entirely. ``_find_session_id`` matches by origin (chat_id + user
- preference with a multi-candidate bail-out), which is correct for
- "mirror into whatever conversation lives here" callers but WRONG for a
- caller holding the precise target — on a populated chat (flat session +
- N per-message thread sessions sharing one chat_id) the scan can refuse
- to guess and silently drop the mirror (live failure, Alice 2026-08-19:
- 'in_channel seed did NOT land').
-
- ``role`` defaults to ``"assistant"`` — correct for the interactive
- ``send_message`` mirror, where the mirrored text is the agent's own
- outgoing reply (a genuine assistant turn). Callers mirroring text that is
- NOT the agent speaking — e.g. a cron brief delivered out-of-band — must
- pass ``role="user"``: the ``mirror``/``mirror_source`` metadata is dropped
- at the SQLite boundary (only role+content persist), so on replay an
- assistant-role mirror is indistinguishable from a real assistant turn and
- produces ``assistant → assistant`` pairs that break strict-alternation
- providers (issue #2221). A user-role mirror collapses safely via
- ``repair_message_sequence``'s consecutive-user merge on every provider.
-
- Returns True if mirrored successfully, False if no matching session or error.
- All errors are caught -- this is never fatal.
+ """Append a delivery-mirror message to the target session's SQLite transcript.
+
+ ``session_id``: pass it when the caller already holds the exact session
+ (e.g. the cron in_channel seed that just created the row) to skip the
+ origin scan. ``_find_session_id`` refuses to guess on a populated chat
+ (flat session + N thread sessions sharing one chat_id) and would silently
+ drop the mirror.
+
+ ``role`` defaults to ``"assistant"``, correct when the mirrored text is
+ the agent's own outgoing reply. Text that is NOT the agent speaking (e.g.
+ a cron brief) must pass ``role="user"``: ``mirror``/``mirror_source``
+ metadata is dropped at the SQLite boundary, so an assistant-role mirror
+ replays as a real assistant turn and produces assistant→assistant pairs
+ that break strict-alternation providers; a user-role mirror collapses
+ safely via ``repair_message_sequence``'s consecutive-user merge.
+
+ Returns True if mirrored, False if no matching session or error. Never raises.
"""
try:
if not session_id:
- session_id = _find_session_id(
- platform,
- str(chat_id),
- thread_id=thread_id,
- user_id=user_id,
- )
+ session_id = _find_session_id(platform, str(chat_id), thread_id=thread_id, user_id=user_id)
if not session_id:
logger.warning(
"Mirror: no session found for %s:%s thread=%s user=%s "
"(explicit_id=none, origin-scan bailed)",
- platform,
- chat_id,
- thread_id,
- user_id,
+ platform, chat_id, thread_id, user_id,
)
return False
- mirror_msg = {
+ _append_to_sqlite(session_id, {
"role": role,
"content": message_text,
"timestamp": datetime.now().isoformat(),
"mirror": True,
"mirror_source": source_label,
- }
-
- _append_to_sqlite(session_id, mirror_msg)
-
+ })
logger.debug("Mirror: wrote to session %s (from %s)", session_id, source_label)
return True
-
except Exception as e:
- # WARNING with the exception: a silent mirror drop IS the cron
- # continuation-amnesia bug (Alice 2026-08-19 — the seed's own
- # deterministic session_id was in hand and the append STILL failed
- # invisibly at debug level).
+ # WARNING, not debug: a silent mirror drop is the cron continuation-amnesia bug.
logger.warning(
"Mirror failed for %s:%s thread=%s user=%s session=%s: %s",
- platform,
- chat_id,
- thread_id,
- user_id,
- session_id,
- e,
+ platform, chat_id, thread_id, user_id, session_id, e,
)
return False
def _find_session_id(
- platform: str,
- chat_id: str,
- thread_id: Optional[str] = None,
- user_id: Optional[str] = None,
+ platform: str, chat_id: str, thread_id: Optional[str] = None, user_id: Optional[str] = None,
) -> Optional[str]:
- """
- Find the active session_id for a platform + chat_id pair.
+ """Find the active session_id for a platform + chat_id pair.
- Queries state.db gateway session rows (primary source since #9006);
- falls back to scanning sessions.json for pre-migration databases.
- DM session keys don't embed the chat_id (e.g. "agent:main:telegram:dm"),
- so we match on the persisted chat origin, not the key.
+ state.db gateway session rows are primary; sessions.json is the fallback
+ for pre-migration databases. DM session keys don't embed the chat_id
+ (e.g. "agent:main:telegram:dm"), so matching is on the persisted origin.
- When *user_id* is provided, prefer exact sender matches. If multiple
- same-chat candidates exist and none matches the user, return None instead
- of guessing and contaminating another participant's session.
+ With *user_id*, exact sender matches win. If several same-chat candidates
+ exist and none matches the user, return None rather than guess and
+ contaminate another participant's session.
"""
- # Primary: state.db
try:
- from hermes_state import get_shared_session_db
+ from hermes_state import get_shared_session_db, release_or_close
db = get_shared_session_db()
try:
finder = getattr(db, "find_session_by_origin", None)
if callable(finder):
- session_id = finder(
- platform=platform,
- chat_id=chat_id,
- thread_id=thread_id,
- user_id=user_id,
- )
+ session_id = finder(platform=platform, chat_id=chat_id, thread_id=thread_id, user_id=user_id)
if session_id:
return str(session_id)
finally:
- from hermes_state import release_or_close
release_or_close(db)
except Exception as e:
logger.debug("Mirror state.db session lookup failed: %s", e)
- # Fallback: sessions.json (pre-migration databases)
if not _SESSIONS_INDEX.exists():
return None
-
try:
with open(_SESSIONS_INDEX, encoding="utf-8") as f:
data = json.load(f)
@@ -163,65 +113,44 @@ def _find_session_id(
platform_lower = platform.lower()
candidates = []
-
for _key, entry in data.items():
- # Skip documentation/metadata sentinels (keys starting with "_", e.g.
- # the gateway's "_README" note) — they are not session entries.
+ # Keys starting with "_" (e.g. the gateway's "_README") are metadata sentinels.
if str(_key).startswith("_") or not isinstance(entry, dict):
continue
origin = entry.get("origin") or {}
- entry_platform = (origin.get("platform") or entry.get("platform", "")).lower()
-
- if entry_platform != platform_lower:
+ if (origin.get("platform") or entry.get("platform", "")).lower() != platform_lower:
continue
-
- origin_chat_id = str(origin.get("chat_id", ""))
- if origin_chat_id == str(chat_id):
- origin_thread_id = origin.get("thread_id")
- if thread_id is not None and str(origin_thread_id or "") != str(thread_id):
- continue
- candidates.append(entry)
+ if str(origin.get("chat_id", "")) != str(chat_id):
+ continue
+ if thread_id is not None and str(origin.get("thread_id") or "") != str(thread_id):
+ continue
+ candidates.append(entry)
if not candidates:
return None
-
if user_id:
- exact_user_matches = [
- entry for entry in candidates
- if str((entry.get("origin") or {}).get("user_id") or "") == str(user_id)
- ]
+ exact_user_matches = [e for e in candidates if _origin_user_id(e) == str(user_id)]
if exact_user_matches:
candidates = exact_user_matches
elif len(candidates) > 1:
return None
elif len(candidates) > 1:
- distinct_user_ids = {
- str((entry.get("origin") or {}).get("user_id") or "").strip()
- for entry in candidates
- if str((entry.get("origin") or {}).get("user_id") or "").strip()
- }
+ distinct_user_ids = {uid.strip() for uid in map(_origin_user_id, candidates) if uid.strip()}
if len(distinct_user_ids) > 1:
return None
- best_entry = max(candidates, key=lambda entry: entry.get("updated_at", ""))
- return best_entry.get("session_id")
-
+ return max(candidates, key=lambda entry: entry.get("updated_at", "")).get("session_id")
def _append_to_sqlite(session_id: str, message: dict) -> None:
"""Append a message to the SQLite session database."""
db = None
try:
- from hermes_state import get_shared_session_db
+ from hermes_state import get_shared_session_db, release_or_close
db = get_shared_session_db()
- db.append_message(
- session_id=session_id,
- role=message.get("role", "assistant"),
- content=message.get("content"),
- )
+ db.append_message(session_id=session_id, role=message.get("role", "assistant"), content=message.get("content"))
except Exception as e:
logger.debug("Mirror SQLite write failed: %s", e)
finally:
if db is not None:
- from hermes_state import release_or_close
release_or_close(db)
diff --git a/gateway/pairing.py b/gateway/pairing.py
index 693fb917d24..67697dc6cef 100644
--- a/gateway/pairing.py
+++ b/gateway/pairing.py
@@ -1,23 +1,17 @@
"""
DM Pairing System
-Code-based approval flow for authorizing new users on messaging platforms.
-Instead of static allowlists with user IDs, unknown users receive a one-time
-pairing code that the bot owner approves via the CLI.
-
-Security features (based on OWASP + NIST SP 800-63-4 guidance):
- - 8-char codes from 32-char unambiguous alphabet (no 0/O/1/I)
- - Cryptographic randomness via secrets.choice()
- - 1-hour code expiry
- - Max 3 pending codes per platform
- - Rate limiting: 1 request per user per 10 minutes
- - Lockout after 5 failed approval attempts (1 hour)
- - File permissions: chmod 0600 on all data files
- - Codes are never logged to stdout
-
-Storage: ~/.hermes/pairing/
+Code-based approval flow for authorizing new users on messaging platforms:
+unknown users receive a one-time pairing code that the bot owner approves via
+the CLI, instead of maintaining static user-ID allowlists.
+
+Security properties (OWASP + NIST SP 800-63-4): 8-char codes from a 32-char
+unambiguous alphabet via ``secrets``, 1-hour expiry, max 3 pending per
+platform, 1 request per user per 10 min, lockout after 5 failed approvals,
+chmod 0600 data files, codes never logged. Storage: ~/.hermes/pairing/
"""
+import contextlib
import hashlib
import json
import logging
@@ -39,7 +33,6 @@ from hermes_constants import (
get_hermes_home,
)
from utils import atomic_replace
-import contextlib
logger = logging.getLogger(__name__)
@@ -48,55 +41,36 @@ logger = logging.getLogger(__name__)
ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
CODE_LENGTH = 8
-# Timing constants
CODE_TTL_SECONDS = 3600 # Codes expire after 1 hour
RATE_LIMIT_SECONDS = 600 # 1 request per user per 10 minutes
LOCKOUT_SECONDS = 3600 # Lockout duration after too many failures
-
-# Limits
MAX_PENDING_PER_PLATFORM = 3 # Max pending codes per platform
MAX_FAILED_ATTEMPTS = 5 # Failed approvals before lockout
-# Default (non-profile-scoped) pairing directory. Left unresolved (``None``)
-# here rather than computed eagerly: this module is imported once by the
-# long-lived gateway process at container/process boot, and computing the
-# path eagerly freezes it to whatever HERMES_HOME/profile context existed
-# at that exact import moment for the rest of the process's lifetime --
-# even if a context-local override (see hermes_constants.set_hermes_home_override)
-# is established afterward. A freshly-started, short-lived process (e.g. the
-# ``hermes pairing`` CLI) re-imports this module later with the final
-# environment already in place, so it never observes the stale value -- the
-# resulting asymmetry is what made pending pairing codes issued by the
-# gateway unrecoverable while CLI-side writes to the same directory kept
-# working (NousResearch/hermes-agent#93449).
-#
-# ``_default_pairing_dir()`` below resolves this fresh on every call in
-# production. Tests patch this attribute directly to a concrete path for
-# isolation (e.g. ``patch("gateway.pairing.PAIRING_DIR", tmp_path)``); that
-# continues to work unchanged, since a patched (non-``None``) value takes
-# precedence over recomputing.
+# Default (non-profile-scoped) pairing directory. Deliberately ``None``: the
+# long-lived gateway imports this module at boot, and an eagerly computed path
+# would freeze whatever HERMES_HOME/profile context existed then, ignoring later
+# context-local overrides (hermes_constants.set_hermes_home_override) -- so the
+# gateway and the short-lived ``hermes pairing`` CLI ended up writing different
+# directories. ``_default_pairing_dir()`` resolves fresh on every call; tests
+# patch this attribute to a concrete path (``patch("gateway.pairing.PAIRING_DIR", tmp)``)
+# and a non-``None`` value takes precedence.
PAIRING_DIR = None
def _default_pairing_dir() -> Path:
- """Resolve the default (non-profile-scoped) pairing directory.
-
- Recomputed on every call rather than cached at import time -- see the
- ``PAIRING_DIR`` comment above for why. Honors ``PAIRING_DIR`` when a
- caller (typically a test) has explicitly set it to a concrete path.
- """
+ """Resolve the default pairing directory fresh (see ``PAIRING_DIR``)."""
if PAIRING_DIR is not None:
return PAIRING_DIR
return get_hermes_dir("platforms/pairing", "pairing")
-# Platform value -> its per-platform allowlist env var. When an operator has
-# already configured an allowlist for a platform, approving a pairing code also
-# writes the user into that allowlist (and revoking removes them), so the
-# operator's own list stays the single visible/editable source of truth instead
-# of drifting from an opaque approved.json (#23778 consolidation, option i).
-# Platforms absent from this map (or with no allowlist configured) keep the
-# pairing store as the sole grant record, honored by the authz union.
+# Platform value -> per-platform allowlist env var. When an operator already
+# runs an allowlist for a platform, approving a pairing code also writes the
+# user into it (and revoking removes them), so the operator's list stays the
+# single visible source of truth instead of drifting from an opaque
+# approved.json. Platforms absent here (or with no allowlist configured) keep
+# the pairing store as the sole grant record, honored by the authz union.
_PLATFORM_ALLOWLIST_ENV = {
"telegram": "TELEGRAM_ALLOWED_USERS",
"discord": "DISCORD_ALLOWED_USERS",
@@ -120,11 +94,7 @@ _PLATFORM_ALLOWLIST_ENV = {
def _allowlist_env_for_platform(platform: str) -> Optional[str]:
- """Return the per-platform allowlist env var name, or None.
-
- Falls back to the platform registry for plugin platforms so a plugin's
- own ``allowed_users_env`` is honored too.
- """
+ """Allowlist env var name for ``platform`` (plugin registry fallback), or None."""
platform = (platform or "").lower().strip()
env_var = _PLATFORM_ALLOWLIST_ENV.get(platform)
if env_var:
@@ -181,16 +151,12 @@ def _read_allowlist_env(env_var: str) -> str:
"""Read a platform allowlist env var through the profile secret scope.
Under multiplexing the process env may hold ANOTHER profile's allowlist
- (first-writer-wins YAML→env bridges), so reads must honor the installed
- scope's verdict — including a scoped miss returning empty rather than
- borrowing the process value. Unscoped callers (single-profile CLI /
- admin endpoints) keep the legacy ``os.getenv`` read.
-
- The grant mirror below writes through ``hermes_cli.config.save_env_value``
- / ``remove_env_value``: the file target is the active profile's ``.env``
- (``get_env_path()`` honors the profile-home override) and, under
- multiplexing, the in-process publish updates the installed scope mapping
- rather than the shared ``os.environ`` (#88441).
+ (first-writer-wins YAML→env bridges), so a scoped miss must return empty
+ rather than borrow the process value. Unscoped callers (single-profile
+ CLI / admin endpoints) keep the legacy ``os.getenv`` read. Writes go
+ through ``hermes_cli.config.save_env_value`` / ``remove_env_value``, which
+ target the active profile's ``.env`` and, under multiplexing, publish into
+ the installed scope mapping rather than the shared ``os.environ``.
"""
try:
from agent.secret_scope import UnscopedSecretError, get_secret
@@ -204,22 +170,27 @@ def _read_allowlist_env(env_var: str) -> str:
return (os.getenv(env_var) or "").strip()
-def _sync_allowlist_add(platform: str, user_id: str) -> None:
- """Add ``user_id`` to the platform allowlist env var IF one is configured.
+def _configured_allowlist(platform: str):
+ """Return ``(env_var, ids)`` for a platform whose allowlist is configured, else None.
- Option (i): only materialize the grant into the allowlist when the operator
- already runs an allowlist for this platform. On an open gateway (no
- allowlist) we do nothing — the pairing store remains the grant record and
- the authz union honors it, so we never silently convert an open gateway into
- a locked one on first pairing.
+ An unconfigured allowlist means an open gateway: the pairing store stays the
+ sole grant record and we must never lock the gateway by materializing one.
"""
env_var = _allowlist_env_for_platform(platform)
if not env_var:
- return
+ return None
current = _read_allowlist_env(env_var)
if not current:
- return # No allowlist configured — leave the gateway open (option i).
- ids = _split_allowlist(current)
+ return None
+ return env_var, _split_allowlist(current)
+
+
+def _sync_allowlist_add(platform: str, user_id: str) -> None:
+ """Add ``user_id`` to the platform allowlist env var IF one is configured."""
+ configured = _configured_allowlist(platform)
+ if configured is None:
+ return
+ env_var, ids = configured
if "*" in ids or str(user_id) in ids:
return # Already covered.
ids.append(str(user_id))
@@ -228,8 +199,7 @@ def _sync_allowlist_add(platform: str, user_id: str) -> None:
save_env_value(env_var, ",".join(ids))
except Exception:
- # Best-effort: the pairing store grant still authorizes via the union,
- # so a failure here degrades to "grant recorded but not mirrored".
+ # Best-effort: the pairing store grant still authorizes via the union.
pass
@@ -243,60 +213,43 @@ def _iter_live_gateway_adapters():
return
if runner is None:
return
- adapters = getattr(runner, "adapters", None) or {}
- for adapter in adapters.values():
+ for adapter in (getattr(runner, "adapters", None) or {}).values():
if adapter is not None:
yield adapter
- profile_adapters = getattr(runner, "_profile_adapters", None) or {}
- for mapping in profile_adapters.values():
+ for mapping in (getattr(runner, "_profile_adapters", None) or {}).values():
for adapter in (mapping or {}).values():
if adapter is not None:
yield adapter
def _adapter_platform_name(adapter) -> str:
- platform = getattr(adapter, "platform", None)
- if platform is not None:
- value = getattr(platform, "value", None)
- if value:
- return str(value).strip().lower()
- name = getattr(adapter, "name", None)
- return str(name or "").strip().lower()
+ value = getattr(getattr(adapter, "platform", None), "value", None)
+ if value:
+ return str(value).strip().lower()
+ return str(getattr(adapter, "name", None) or "").strip().lower()
def _purge_allowlist_entries(entries, platform: str, user_id: str):
"""Drop alias-equivalent allowlist entries while preserving ``*``."""
- if entries is None:
- return entries
+ def keep(entry) -> bool:
+ entry = str(entry)
+ return entry.strip() == "*" or not _user_ids_match(platform, entry, str(user_id))
+
if isinstance(entries, str):
- parts = _split_allowlist(entries)
- remaining = [
- part for part in parts
- if part == "*" or not _user_ids_match(platform, part, str(user_id))
- ]
- return ",".join(remaining)
+ return ",".join(part for part in _split_allowlist(entries) if keep(part))
if isinstance(entries, (set, frozenset)):
- return {
- entry for entry in entries
- if str(entry).strip() == "*"
- or not _user_ids_match(platform, str(entry), str(user_id))
- }
+ return {entry for entry in entries if keep(entry)}
if isinstance(entries, (list, tuple)):
- return [
- entry for entry in entries
- if str(entry).strip() == "*"
- or not _user_ids_match(platform, str(entry), str(user_id))
- ]
+ return [entry for entry in entries if keep(entry)]
return entries
def _sync_live_adapter_allowlist_remove(platform: str, user_id: str) -> None:
"""Clear revoked principals from in-process adapter allowlist snapshots.
- ``WhatsAppAdapter`` (and Cloud) snapshot ``_allow_from`` at construction.
- Pairing revoke updates ``WHATSAPP_ALLOWED_USERS`` / cloud env, but when the
- revoked principal was the sole entry the env key is removed entirely.
- Intake must not keep authorizing from the stale snapshot until restart.
+ Adapters snapshot ``_allow_from`` at construction; when the revoked
+ principal was the sole entry the env key is removed entirely, so intake
+ must not keep authorizing from the stale snapshot until restart.
"""
platform_name = (platform or "").strip().lower()
if not platform_name or not str(user_id or "").strip():
@@ -320,27 +273,16 @@ def _sync_live_adapter_allowlist_remove(platform: str, user_id: str) -> None:
def _sync_allowlist_remove(platform: str, user_id: str) -> None:
"""Remove ``user_id`` (and WhatsApp alias equivalents) from the allowlist.
- Matching must mirror PairingStore / authz WhatsApp alias rules: approve
- mirrors a normalized phone into ``WHATSAPP_ALLOWED_USERS``, while revoke
- is often invoked with a JID or device-suffix form. Exact-string delete
- would leave the allowlist entry and keep the sender authorized.
-
- Also clears matching entries from any in-process platform adapter
- ``_allow_from`` snapshot so sole-entry revocation is effective without a
- gateway restart.
+ Approve mirrors a normalized phone while revoke is often given a JID or
+ device-suffix form, so matching uses alias rules -- exact-string delete
+ would leave the sender authorized. Also clears in-process adapter
+ snapshots so sole-entry revocation works without a gateway restart.
"""
- env_var = _allowlist_env_for_platform(platform)
- if not env_var:
- return
- current = _read_allowlist_env(env_var)
- if not current:
+ configured = _configured_allowlist(platform)
+ if configured is None:
return # No allowlist configured — do not touch config-only snapshots.
- ids = _split_allowlist(current)
- # Never strip a wildcard grant; drop every entry that aliases-matches.
- remaining = [
- i for i in ids
- if i == "*" or not _user_ids_match(platform, i, str(user_id))
- ]
+ env_var, ids = configured
+ remaining = _purge_allowlist_entries(ids, platform, user_id)
if len(remaining) == len(ids):
return # Not present.
try:
@@ -366,12 +308,10 @@ def _load_json_file(path: Path) -> dict:
def _merge_pairing_dir(active_dir: Path, alternate_dir: Path) -> None:
- """Merge split legacy/new pairing data into the active PairingStore dir.
+ """Merge split legacy (``pairing``) / new (``platforms/pairing``) data into the active dir.
- Older installs use ``{HERMES_HOME}/pairing`` while newer code/docs may
- write ``{HERMES_HOME}/platforms/pairing``. If both directories exist, the
- gateway must not silently ignore approved users sitting in the inactive
- location; otherwise already-paired Feishu users get asked for a fresh code.
+ If both exist, approved users in the inactive location must not be
+ silently ignored (they would be asked for a fresh code).
"""
if not alternate_dir.exists() or active_dir.resolve() == alternate_dir.resolve():
return
@@ -405,11 +345,7 @@ def _migrate_split_pairing_dirs(
def _secure_write(path: Path, data: str) -> None:
- """Write data to file with restrictive permissions (owner read/write only).
-
- Uses a temp-file + atomic rename so readers always see either the old
- complete file or the new one — never a partial write.
- """
+ """Write 0600 via temp file + atomic rename so readers never see a partial file."""
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp_path = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp")
try:
@@ -418,10 +354,8 @@ def _secure_write(path: Path, data: str) -> None:
f.flush()
os.fsync(f.fileno())
atomic_replace(tmp_path, path)
- try:
+ with contextlib.suppress(OSError): # Windows doesn't support chmod the same way
os.chmod(path, 0o600)
- except OSError:
- pass # Windows doesn't support chmod the same way
except BaseException:
with contextlib.suppress(OSError):
os.unlink(tmp_path)
@@ -432,47 +366,32 @@ class PairingStore:
"""
Manages pairing codes and approved user lists.
- Data files per platform:
- - {platform}-pending.json : pending pairing requests
- - {platform}-approved.json : approved (paired) users
- - _rate_limits.json : rate limit tracking
+ Data files per platform: ``{platform}-pending.json``,
+ ``{platform}-approved.json``, plus shared ``_rate_limits.json``.
- When constructed with ``profile="<name>"``, storage resolves from that
- profile's own HERMES_HOME using the same legacy/consolidated layout rules
- as ``hermes -p <name> pairing ...``. This keeps multiplex gateways and
- profile-scoped CLI approvals on one whitelist. Without a profile, storage
- is the global pairing directory for the current HERMES_HOME.
+ With ``profile="<name>"`` storage resolves from that profile's own
+ HERMES_HOME with the same legacy/consolidated layout rules as
+ ``hermes -p <name> pairing ...``, so multiplex gateways and profile-scoped
+ CLI approvals share one whitelist. Without a profile, storage is the global
+ pairing directory for the current HERMES_HOME.
"""
def __init__(self, profile: Optional[str] = None):
- # Resolve storage directory lazily — tests use a temp HERMES_HOME
- # and PairingStore may be constructed before the env is set.
+ # Resolved lazily: tests use a temp HERMES_HOME and may construct the
+ # store before the env is set.
if profile:
root = get_default_hermes_root()
- profile_home = (
- root
- if profile == "default"
- else root / "profiles" / profile
- )
- self._dir = get_hermes_dir(
- "platforms/pairing",
- "pairing",
- home=profile_home,
- )
+ profile_home = root if profile == "default" else root / "profiles" / profile
+ self._dir = get_hermes_dir("platforms/pairing", "pairing", home=profile_home)
else:
+ profile_home = None
self._dir = _default_pairing_dir()
self._dir.mkdir(parents=True, exist_ok=True)
- if profile:
- # Explicit stores must resolve exactly as a standalone
- # ``hermes -p <profile> pairing ...`` process does. Merge the
- # alternate old/new layout so upgrades cannot split approvals.
- _migrate_split_pairing_dirs(home=profile_home, active=self._dir)
- else:
- # Heal installs whose global pairing data ended up split across
- # the legacy and new directories.
- _migrate_split_pairing_dirs()
- # Protects all read-modify-write cycles. The gateway runs multiple
- # platform adapters concurrently in threads sharing one PairingStore.
+ # Merge the alternate old/new layout so upgrades cannot split approvals;
+ # a profile store must resolve exactly as ``hermes -p <profile>`` does.
+ _migrate_split_pairing_dirs(home=profile_home, active=self._dir)
+ # Protects all read-modify-write cycles: platform adapters run
+ # concurrently in threads sharing one PairingStore.
self._lock = threading.RLock()
self._profile = profile # for diagnostics / log lines
@@ -495,20 +414,16 @@ class PairingStore:
try:
return json.loads(path.read_text(encoding="utf-8"))
except PermissionError as e:
- # Surface this loudly: a 0600 file owned by a different user
- # (classic Docker symptom: `docker exec` runs as root and writes
- # the file, then the gateway process — running as `hermes` after
- # gosu drop — can't read it) would otherwise be swallowed by
- # the generic OSError branch below, silently leaving the user
- # marked unauthorized. See issue #10270.
+ # Loud warning: a 0600 file owned by another uid (Docker:
+ # `docker exec` as root writes it, the gosu-dropped gateway
+ # can't read it) would otherwise be swallowed by the OSError
+ # branch and silently leave the user unauthorized.
try:
st = path.stat()
owner_info = f"owner_uid={st.st_uid} mode={oct(st.st_mode)[-4:]}"
except OSError:
owner_info = "<stat failed>"
- # os.geteuid doesn't exist on Windows; the Docker scenario is
- # POSIX-only, but the gateway (and this fallback) runs anywhere.
- euid = os.geteuid() if hasattr(os, "geteuid") else "n/a"
+ euid = os.geteuid() if hasattr(os, "geteuid") else "n/a" # no geteuid on Windows
logger.warning(
"Pairing file %s exists but is not readable as uid=%s (%s; %s). "
"If you ran `docker exec <container> hermes pairing approve ...` as root, "
@@ -525,27 +440,12 @@ class PairingStore:
def _save_json(self, path: Path, data: dict) -> None:
_secure_write(path, json.dumps(data, indent=2, ensure_ascii=False))
- def _normalize_user_id(self, platform: str, user_id: str) -> str:
- """Normalize platform-specific user IDs before persisting them."""
- return _normalize_user_id(platform, user_id)
-
- def _user_id_aliases(self, platform: str, user_id: str) -> set[str]:
- """Return all known equivalent user IDs for auth/rate-limit checks."""
- return _user_id_aliases(platform, user_id)
-
- def _user_ids_match(self, platform: str, left: str, right: str) -> bool:
- """Return True when two user IDs represent the same principal."""
- return _user_ids_match(platform, left, right)
-
# ----- Approved users -----
def is_approved(self, platform: str, user_id: str) -> bool:
"""Check if a user is approved (paired) on a platform."""
approved = self._load_json(self._approved_path(platform))
- for approved_user_id in approved:
- if self._user_ids_match(platform, approved_user_id, user_id):
- return True
- return False
+ return any(_user_ids_match(platform, uid, user_id) for uid in approved)
def list_approved(self, platform: str = None) -> list:
"""List approved users, optionally filtered by platform."""
@@ -560,13 +460,10 @@ class PairingStore:
def _approve_user(self, platform: str, user_id: str, user_name: str = "") -> None:
"""Add a user to the approved list. Must be called under self._lock."""
approved = self._load_json(self._approved_path(platform))
- normalized_user_id = self._normalize_user_id(platform, user_id)
- duplicate_ids = [
- approved_user_id
- for approved_user_id in approved
- if self._user_ids_match(platform, approved_user_id, normalized_user_id)
- ]
- for approved_user_id in duplicate_ids:
+ normalized_user_id = _normalize_user_id(platform, user_id)
+ for approved_user_id in [
+ uid for uid in approved if _user_ids_match(platform, uid, normalized_user_id)
+ ]:
del approved[approved_user_id]
approved[normalized_user_id] = {
@@ -574,10 +471,7 @@ class PairingStore:
"approved_at": time.time(),
}
self._save_json(self._approved_path(platform), approved)
-
- # Mirror the grant into the operator's allowlist when one is configured
- # (option i), so the pairing store and the allowlist stay a single
- # visible source of truth. No-op on open gateways.
+ # Mirror the grant into the operator's allowlist when one is configured.
_sync_allowlist_add(platform, normalized_user_id)
def revoke(self, platform: str, user_id: str) -> bool:
@@ -586,20 +480,16 @@ class PairingStore:
with self._lock:
approved = self._load_json(path)
matching_ids = [
- approved_user_id
- for approved_user_id in approved
- if self._user_ids_match(platform, approved_user_id, user_id)
+ uid for uid in approved if _user_ids_match(platform, uid, user_id)
]
- if matching_ids:
- for approved_user_id in matching_ids:
- del approved[approved_user_id]
- self._save_json(path, approved)
- # Keep the allowlist mirror in sync: revoking a paired user
- # also removes the entry the approval added (option i). No-op if
- # the user was added to the allowlist by other means.
- _sync_allowlist_remove(platform, user_id)
- return True
- return False
+ if not matching_ids:
+ return False
+ for approved_user_id in matching_ids:
+ del approved[approved_user_id]
+ self._save_json(path, approved)
+ # Keep the allowlist mirror in sync (no-op if added by other means).
+ _sync_allowlist_remove(platform, user_id)
+ return True
# ----- Pending codes -----
@@ -616,11 +506,9 @@ class PairingStore:
self._save_json(self._pending_path(platform), pending)
# A successful approval proves the requester is legitimate, so the
- # brute-force failure streak must not carry over. Without this,
- # isolated mistyped codes accumulate across the gateway's lifetime
- # (the counter is persisted in _rate_limits.json and only ever
- # reset when a lockout fires) and eventually trip a spurious
- # lockout on a single fresh typo — rejecting even a valid code.
+ # brute-force streak must not carry over: the counter persists in
+ # _rate_limits.json and would otherwise accumulate isolated typos
+ # until a single fresh typo trips a spurious lockout.
self._reset_failed_attempts(platform)
self._approve_user(
@@ -635,146 +523,97 @@ class PairingStore:
def generate_code(
self, platform: str, user_id: str, user_name: str = ""
) -> Optional[str]:
- """
- Generate a pairing code for a new user.
-
- Returns the code string, or None if:
- - User is rate-limited (too recent request)
- - Max pending codes reached for this platform
- - User/platform is in lockout due to failed attempts
+ """Generate a pairing code for a new user.
- The code is NOT stored in plaintext. Only a salted SHA-256 hash is
- persisted so that reading the pending file does not reveal codes.
+ Returns None if the user is rate-limited, the platform hit
+ MAX_PENDING_PER_PLATFORM, or the platform is locked out. Only a salted
+ SHA-256 hash of the code is persisted, never the plaintext.
"""
with self._lock:
self._cleanup_expired(platform)
- normalized_user_id = self._normalize_user_id(platform, user_id)
+ normalized_user_id = _normalize_user_id(platform, user_id)
- # Check lockout
if self._is_locked_out(platform):
return None
-
- # Check rate limit for this specific user
if self._is_rate_limited(platform, user_id):
return None
-
- # Check max pending
pending = self._load_json(self._pending_path(platform))
if len(pending) >= MAX_PENDING_PER_PLATFORM:
return None
- # Generate cryptographically random code
code = "".join(secrets.choice(ALPHABET) for _ in range(CODE_LENGTH))
-
- # Hash the code with a random salt before storing
salt = os.urandom(16)
- code_hash = self._hash_code(code, salt)
-
- # Use a unique entry id as the key (not the code itself)
- entry_id = secrets.token_hex(8)
-
- # Store pending request with hashed code
- pending[entry_id] = {
- "hash": code_hash,
+ # Keyed by a random entry id, not the code itself.
+ pending[secrets.token_hex(8)] = {
+ "hash": self._hash_code(code, salt),
"salt": salt.hex(),
"user_id": normalized_user_id,
"user_name": user_name,
"created_at": time.time(),
}
self._save_json(self._pending_path(platform), pending)
-
- # Record rate limit
self._record_rate_limit(platform, user_id)
-
return code
def approve_code(self, platform: str, code: str) -> Optional[dict]:
- """
- Approve a pairing code. Adds the user to the approved list.
+ """Approve a pairing code. Adds the user to the approved list.
Returns ``{user_id, user_name}`` on success, ``None`` if the code is
- invalid/expired OR the platform is currently locked out after
- ``MAX_FAILED_ATTEMPTS`` failed approvals (#10195). Callers can
- disambiguate with ``_is_locked_out(platform)``.
-
- Verification: the user-provided code is hashed with each stored
- entry's salt and compared to the stored hash using constant-time
- comparison. Pre-hash entries (legacy plaintext-key format from
- pre-upgrade pending.json files) are silently ignored — they get
- pruned at TTL by ``_cleanup_expired``.
+ invalid/expired OR the platform is locked out after
+ ``MAX_FAILED_ATTEMPTS`` failed approvals (disambiguate with
+ ``_is_locked_out``). The code is hashed with each entry's salt and
+ compared in constant time; legacy plaintext-key entries are ignored
+ and pruned at TTL by ``_cleanup_expired``.
"""
with self._lock:
self._cleanup_expired(platform)
code = code.upper().strip()
- # Lockout check — must run before the pending lookup so a
- # valid code (e.g. one already sitting in pending) cannot be
- # accepted once the lockout fires. Without this, the lockout
- # only blocks `generate_code`, not `approve_code` — nullifying
- # the brute-force protection for any code already issued.
+ # Must run before the pending lookup, or an already-issued valid
+ # code would still be accepted during lockout, nullifying the
+ # brute-force protection.
if self._is_locked_out(platform):
return None
pending = self._load_json(self._pending_path(platform))
-
- # Find the entry whose hash matches the provided code.
- # Tolerate legacy plaintext-key entries (no salt/hash) and
- # malformed entries — skip them rather than KeyError, so an
- # in-place upgrade across an existing pending.json doesn't
- # crash on the first approve call. Legacy entries get pruned
- # at their TTL by _cleanup_expired.
- matched_key = None
- matched_entry = None
+ # Skip legacy/malformed entries rather than KeyError so an in-place
+ # upgrade over an existing pending.json doesn't crash.
for entry_id, entry in pending.items():
- if not isinstance(entry, dict):
- continue
- if "salt" not in entry or "hash" not in entry:
+ if not isinstance(entry, dict) or "salt" not in entry or "hash" not in entry:
continue
try:
salt = bytes.fromhex(entry["salt"])
except ValueError:
continue
- candidate_hash = self._hash_code(code, salt)
- if secrets.compare_digest(candidate_hash, entry["hash"]):
- matched_key = entry_id
- matched_entry = entry
- break
-
- if matched_key is None:
- self._record_failed_attempt(platform)
- return None
+ if secrets.compare_digest(self._hash_code(code, salt), entry["hash"]):
+ return self._finish_approval(platform, pending, entry_id, entry)
- return self._finish_approval(platform, pending, matched_key, matched_entry)
+ self._record_failed_attempt(platform)
+ return None
@staticmethod
def looks_like_request_id(value: str) -> bool:
"""True when ``value`` has the shape of a ``list_pending`` request id.
- Request ids are ``secrets.token_hex(8)`` (16 lowercase hex chars);
- pairing codes are 8 chars from an unambiguous uppercase alphabet that
- excludes every hex letter's ambiguity partner. The two shapes cannot
- collide, so callers accepting either can dispatch on this.
+ Request ids are ``secrets.token_hex(8)`` (16 hex chars); pairing codes
+ are 8 chars from an uppercase alphabet, so the shapes cannot collide
+ and callers accepting either can dispatch on this.
"""
value = str(value or "").strip()
return len(value) == 16 and all(c in "0123456789abcdefABCDEF" for c in value)
def approve_request(self, platform: str, request_id: str) -> Optional[dict]:
- """
- Approve a pending pairing request by its server-side request id.
-
- This is the grant path for authenticated admin surfaces (``hermes
- pairing list``, the dashboard/desktop approve buttons), which show
- pending requests but must never reveal the one-time code DM'd to the
- user. Returns ``{user_id, user_name}`` on success, ``None`` for an
- unknown/expired request id.
-
- Unlike :meth:`approve_code` this does NOT count a miss toward the
- brute-force lockout, and is not itself gated by one. The lockout
- protects the 8-char code space against guessing over a messaging
- channel; a request id is only ever obtained by an admin already
- authenticated to this store, so a stale id means "the row you clicked
- expired", not an attack. Counting it here let a few GUI clicks on a
- stale list lock the operator out of the CLI's code path too.
+ """Approve a pending request by its server-side request id.
+
+ Grant path for authenticated admin surfaces (``hermes pairing list``,
+ dashboard/desktop buttons) that must never reveal the DM'd code.
+ Returns ``{user_id, user_name}`` or ``None`` for an unknown/expired id.
+
+ Unlike :meth:`approve_code` this neither counts toward nor is gated by
+ the brute-force lockout: a request id is only obtainable by an admin
+ already authenticated to this store, so a stale id means "the row you
+ clicked expired", not an attack -- and counting it would let a few GUI
+ clicks lock the operator out of the CLI's code path.
"""
with self._lock:
self._cleanup_expired(platform)
@@ -784,9 +623,7 @@ class PairingStore:
pending = self._load_json(self._pending_path(platform))
for entry_id, entry in pending.items():
- if not isinstance(entry, dict):
- continue
- if "salt" not in entry or "hash" not in entry:
+ if not isinstance(entry, dict) or "salt" not in entry or "hash" not in entry:
continue
if secrets.compare_digest(str(entry_id).lower(), request_id):
return self._finish_approval(platform, pending, entry_id, entry)
@@ -796,10 +633,9 @@ class PairingStore:
def list_pending(self, platform: str = None) -> list:
"""List pending pairing requests, optionally filtered by platform.
- Codes are stored hashed and are never returned. Each entry exposes a
- server-side ``request_id`` that an authenticated admin surface passes
- to :meth:`approve_request`. Legacy pre-hash entries have no approvable
- id — they report an empty ``request_id`` and age out at TTL.
+ Codes are hashed and never returned; each entry exposes a server-side
+ ``request_id`` for :meth:`approve_request`. Legacy pre-hash entries
+ report an empty ``request_id`` and age out at TTL.
"""
results = []
with self._lock:
@@ -813,7 +649,6 @@ class PairingStore:
created_at = info.get("created_at")
if not isinstance(created_at, (int, float)):
continue
- age_min = int((time.time() - created_at) / 60)
is_modern = isinstance(info.get("hash"), str) and isinstance(
info.get("salt"), str
)
@@ -822,7 +657,7 @@ class PairingStore:
"request_id": str(entry_id) if is_modern else "",
"user_id": info.get("user_id", ""),
"user_name": info.get("user_name", ""),
- "age_minutes": age_min,
+ "age_minutes": int((time.time() - created_at) / 60),
})
return results
@@ -840,30 +675,25 @@ class PairingStore:
# ----- Rate limiting and lockout -----
def _is_rate_limited(self, platform: str, user_id: str) -> bool:
- """Check if a user has requested a code too recently."""
+ """Check if a user (under any alias) has requested a code too recently."""
limits = self._load_json(self._rate_limit_path())
- for alias in self._user_id_aliases(platform, user_id):
- key = f"{platform}:{alias}"
- last_request = limits.get(key, 0)
- if (time.time() - last_request) < RATE_LIMIT_SECONDS:
- return True
- return False
+ return any(
+ (time.time() - limits.get(f"{platform}:{alias}", 0)) < RATE_LIMIT_SECONDS
+ for alias in _user_id_aliases(platform, user_id)
+ )
def _record_rate_limit(self, platform: str, user_id: str) -> None:
"""Record the time of a pairing request for rate limiting."""
limits = self._load_json(self._rate_limit_path())
now = time.time()
- for alias in self._user_id_aliases(platform, user_id):
- key = f"{platform}:{alias}"
- limits[key] = now
+ for alias in _user_id_aliases(platform, user_id):
+ limits[f"{platform}:{alias}"] = now
self._save_json(self._rate_limit_path(), limits)
def _is_locked_out(self, platform: str) -> bool:
"""Check if a platform is in lockout due to failed approval attempts."""
limits = self._load_json(self._rate_limit_path())
- lockout_key = f"_lockout:{platform}"
- lockout_until = limits.get(lockout_key, 0)
- return time.time() < lockout_until
+ return time.time() < limits.get(f"_lockout:{platform}", 0)
def _record_failed_attempt(self, platform: str) -> None:
"""Record a failed approval attempt. Triggers lockout after MAX_FAILED_ATTEMPTS."""
@@ -872,20 +702,14 @@ class PairingStore:
fails = limits.get(fail_key, 0) + 1
limits[fail_key] = fails
if fails >= MAX_FAILED_ATTEMPTS:
- lockout_key = f"_lockout:{platform}"
- limits[lockout_key] = time.time() + LOCKOUT_SECONDS
+ limits[f"_lockout:{platform}"] = time.time() + LOCKOUT_SECONDS
limits[fail_key] = 0 # Reset counter
print(f"[pairing] Platform {platform} locked out for {LOCKOUT_SECONDS}s "
f"after {MAX_FAILED_ATTEMPTS} failed attempts", flush=True)
self._save_json(self._rate_limit_path(), limits)
def _reset_failed_attempts(self, platform: str) -> None:
- """Clear the accumulated failed-approval counter after a success.
-
- Called from the ``approve_code`` success path so that a legitimate
- approval resets the brute-force streak (standard lockout semantics:
- the counter tracks *consecutive* failures, not lifetime ones).
- """
+ """Clear the failed-approval counter after a success (it tracks *consecutive* failures)."""
limits = self._load_json(self._rate_limit_path())
fail_key = f"_failures:{platform}"
if limits.get(fail_key):
@@ -895,26 +719,16 @@ class PairingStore:
# ----- Cleanup -----
def _cleanup_expired(self, platform: str) -> None:
- """Remove expired pending codes.
-
- Tolerant of malformed / legacy entries — anything without a numeric
- ``created_at`` is treated as expired (it's effectively unusable
- with the new hash-keyed schema anyway).
- """
+ """Remove expired pending codes; malformed/legacy entries (no numeric ``created_at``) count as expired."""
path = self._pending_path(platform)
pending = self._load_json(path)
now = time.time()
- expired = []
- for entry_id, info in pending.items():
- if not isinstance(info, dict):
- expired.append(entry_id)
- continue
- created_at = info.get("created_at")
- if not isinstance(created_at, (int, float)):
- expired.append(entry_id)
- continue
- if (now - created_at) > CODE_TTL_SECONDS:
- expired.append(entry_id)
+ expired = [
+ entry_id for entry_id, info in pending.items()
+ if not isinstance(info, dict)
+ or not isinstance(info.get("created_at"), (int, float))
+ or (now - info["created_at"]) > CODE_TTL_SECONDS
+ ]
if expired:
for entry_id in expired:
del pending[entry_id]
@@ -922,10 +736,6 @@ class PairingStore:
def _all_platforms(self, suffix: str) -> list:
"""List all platforms that have data files of a given suffix."""
- platforms = []
- for f in self._dir.iterdir():
- if f.name.endswith(f"-{suffix}.json"):
- platform = f.name.replace(f"-{suffix}.json", "")
- if not platform.startswith("_"):
- platforms.append(platform)
- return platforms
+ tail = f"-{suffix}.json"
+ platforms = [f.name.replace(tail, "") for f in self._dir.iterdir() if f.name.endswith(tail)]
+ return [p for p in platforms if not p.startswith("_")]
diff --git a/gateway/readiness.py b/gateway/readiness.py
index 9cffd39cce1..7d4899d3035 100644
--- a/gateway/readiness.py
+++ b/gateway/readiness.py
@@ -29,13 +29,10 @@ def _probe_state_db(home: Path) -> dict[str, Any]:
if not path.exists():
return _check("ok", "not initialized")
try:
- # A readiness probe must never compete with normal state writers. A
- # read-only schema query still catches unreadable/corrupt databases
- # without taking a write reservation on every health poll.
- # ``closing(...)`` is required: sqlite3's connection context manager
- # only commits/rolls back — it never closes, so a bare ``with
- # sqlite3.connect(...)`` leaks one connection (and its fds) per
- # health poll in the long-running gateway (#69678/#69567 bug class).
+ # Read-only schema query: catches unreadable/corrupt DBs without competing
+ # with state writers. ``closing`` is required — sqlite3's connection
+ # context manager only commits/rolls back, never closes, so a bare
+ # ``with connect()`` would leak one connection (and fds) per health poll.
uri = f"file:{path.as_posix()}?mode=ro"
with closing(sqlite3.connect(uri, uri=True, timeout=1.0)) as conn:
conn.execute("PRAGMA query_only = ON")
@@ -71,32 +68,27 @@ def _probe_disk(home: Path) -> dict[str, Any]:
def _probe_gateway(runtime_status: dict[str, Any]) -> dict[str, Any]:
state = str(runtime_status.get("gateway_state") or "unknown")
platforms = runtime_status.get("platforms")
- connected = 0
- configured = 0
- if isinstance(platforms, dict):
- configured = len(platforms)
- connected = sum(
- 1
- for value in platforms.values()
- if isinstance(value, dict)
- and str(value.get("state") or value.get("status") or "").lower()
- in {"connected", "running", "ok"}
- )
+ if not isinstance(platforms, dict):
+ platforms = {}
+ connected = sum(
+ 1
+ for value in platforms.values()
+ if isinstance(value, dict)
+ and str(value.get("state") or value.get("status") or "").lower()
+ in {"connected", "running", "ok"}
+ )
status = "ok" if state in {"running", "draining"} else "degraded"
- return _check(status, state=state, connected_platforms=connected, platforms=configured)
+ return _check(status, state=state, connected_platforms=connected, platforms=len(platforms))
-def _probe_session_store(
- runtime_status: dict[str, Any], state_db_probe: dict[str, Any]
-) -> dict[str, Any]:
+def _probe_session_store(runtime_status: dict[str, Any], state_db_probe: dict[str, Any]) -> dict[str, Any]:
"""Report the running gateway cache state, not an independent reopen."""
runtime_store = runtime_status.get("session_store")
if isinstance(runtime_store, dict):
state = str(runtime_store.get("status") or "unknown")
if state in {"ok", "unavailable", "retrying"}:
return _check(state)
- # Older gateways do not publish a cache state. Preserve their readiness
- # behavior until their process restarts onto a version that does.
+ # Older gateways publish no cache state: fall back to the state_db probe.
return _check("ok" if state_db_probe.get("status") == "ok" else "unavailable")
@@ -110,9 +102,8 @@ def collect_runtime_readiness(
) -> dict[str, Any]:
"""Return bounded readiness diagnostics without mutating runtime state.
- The detailed health endpoint is authenticated. Even there, probes expose
- status and counts only: never config values, credentials, paths, commands,
- queue payloads, or exception messages.
+ Even on the authenticated endpoint, probes expose status and counts only:
+ never config values, credentials, paths, queue payloads, or exception messages.
"""
home = get_hermes_home()
runtime = runtime_status if isinstance(runtime_status, dict) else {}
diff --git a/gateway/relay/adapter.py b/gateway/relay/adapter.py
index f3b4091a62d..e2d3e82a1c6 100644
--- a/gateway/relay/adapter.py
+++ b/gateway/relay/adapter.py
@@ -1,33 +1,37 @@
"""RelayAdapter — one generic gateway adapter fronted by the connector. EXPERIMENTAL.
A single ``BasePlatformAdapter`` subclass that, at handshake, receives a
-``CapabilityDescriptor`` from the connector telling it which platform it is
-fronting and which capabilities to advertise to the ``GatewayStreamConsumer``.
-It implements the four abstract methods (``connect`` / ``disconnect`` / ``send``
-/ ``get_chat_info``) plus the capability surface (``MAX_MESSAGE_LENGTH``,
-``message_len_fn``, ``supports_draft_streaming``) by delegating wire I/O to an
-injected transport and reading capabilities off the descriptor.
-
-There is NO per-platform gateway code: the connector is the only side that knows
-"this chat_id maps to a Discord channel, send it via the Discord websocket."
-The gateway sees an ordinary ``MessageEvent`` in and calls ``adapter.send`` out.
-
-EXPERIMENTAL: the transport protocol and descriptor schema may change without a
-deprecation cycle until >=2 Class-1 platforms validate them.
+``CapabilityDescriptor`` telling it which platform it fronts and which
+capabilities to advertise to the ``GatewayStreamConsumer``. It implements the
+abstract methods (``connect`` / ``disconnect`` / ``send`` / ``get_chat_info``)
+plus the capability surface by delegating wire I/O to an injected transport and
+reading capabilities off the descriptor.
+
+There is NO per-platform gateway code: only the connector knows "this chat_id
+maps to a Discord channel". The gateway sees an ordinary ``MessageEvent`` in and
+calls ``adapter.send`` out. The transport protocol and descriptor schema may
+change without a deprecation cycle until >=2 Class-1 platforms validate them.
"""
from __future__ import annotations
import asyncio
+import json
import logging
import re
import secrets
import time
from collections import OrderedDict
-from typing import Any, Callable, Dict, Optional, Tuple, cast
+from typing import Any, Callable, Dict, Optional, Tuple
from gateway.config import Platform, PlatformConfig
-from gateway.platforms.base import BasePlatformAdapter, MessageEvent, SendResult
+from gateway.platforms.base import (
+ BasePlatformAdapter,
+ MessageEvent,
+ MessageType,
+ ProcessingOutcome,
+ SendResult,
+)
from gateway.relay.descriptor import CapabilityDescriptor
from gateway.relay.media import RelayMediaClient
from gateway.relay.transport import RelayTransport
@@ -35,40 +39,50 @@ from gateway.session import SessionSource
logger = logging.getLogger(__name__)
-# Keep the drain-path going-idle ACK budget strictly under the runner's default
-# adapter disconnect timeout (5s). If go_idle consumes the whole outer budget,
-# cancellation can fire before transport.disconnect() and leave the websocket
-# open. Paired with transport teardown budgets of 1s each for supervisor,
-# reader, and ws.close (~3s), the full drain path stays inside 5s.
+# The drain-path going-idle ACK budget must stay strictly under the runner's
+# default adapter disconnect timeout (5s) or cancellation fires before
+# transport.disconnect() and leaves the websocket open. With transport teardown
+# budgets of 1s each for supervisor, reader and ws.close, the drain stays <5s.
_RELAY_GO_IDLE_ON_DISCONNECT_TIMEOUT_S = 2.0
_RELAY_REVOCATION_MONITOR_TEARDOWN_TIMEOUT_S = 1.0
-# Link detection for the fresh-final unfurl route: raw http(s) URLs, Slack
-# mrkdwn link syntax (<https://...|label>), and markdown links. Cheap and
-# permissive on purpose — a false positive costs one fresh (non-edited)
-# final message; a false negative silently loses the preview.
+# Link detection for the fresh-final unfurl route: raw URLs, Slack mrkdwn links
+# and markdown links. Permissive on purpose — a false positive costs one fresh
+# (non-edited) final; a false negative silently loses the preview.
_URL_RE = re.compile(r"https?://|<https?:|\]\(https?:")
-# How many already-answered prompt ids to remember, so a duplicate answer for
-# one of them (a double tap, or a connector redelivery of the same forward) is
-# recognized as a repeat rather than mistaken for a stale prompt. One short
-# string per entry; sized well above the number of prompts a single gateway can
-# have in flight, and far below anything that matters for memory.
+# Already-answered prompt ids to remember so a duplicate answer (double tap or
+# connector redelivery) reads as a repeat, not a stale prompt.
_RESOLVED_PROMPT_MEMORY = 256
+# Connector promptCodec.decodePromptCallback id alphabet ([A-Za-z0-9_.-], <=32).
+_PROMPT_ID_RE = re.compile(r"^[A-Za-z0-9_.\-]{1,32}$")
+
+_TRUTHY = {"1", "true", "yes", "on"}
+_FALSY = {"0", "false", "no", "off"}
+
+_SLACK = Platform.SLACK.value
+
def _utf16_len(text: str) -> int:
"""Count UTF-16 code units (Telegram's length unit)."""
return len(text.encode("utf-16-le")) // 2
-# Table-driven length-unit selection from the descriptor's ``len_unit``.
_LEN_FNS: Dict[str, Callable[[str], int]] = {
"chars": len,
"utf16": _utf16_len,
}
+def _event_ids(event) -> Tuple[Optional[str], Optional[str]]:
+ """(message_id, chat_id) of an inbound event; message_id lives on the event, falls back to source."""
+ message_id = getattr(event, "message_id", None) or getattr(
+ event.source, "message_id", None
+ )
+ return message_id, getattr(event.source, "chat_id", None)
+
+
class RelayAdapter(BasePlatformAdapter):
"""Generic relay adapter advertising a connector-negotiated capability profile."""
@@ -78,164 +92,95 @@ class RelayAdapter(BasePlatformAdapter):
descriptor: CapabilityDescriptor,
transport: Optional[RelayTransport] = None,
) -> None:
- # The relay adapter fronts many platforms but presents as a single
- # logical platform to the runner; Platform.RELAY identifies it.
+ # Fronts many platforms but presents to the runner as Platform.RELAY.
super().__init__(config, Platform.RELAY)
self.descriptor = descriptor
self._transport = transport
- # Capability surface read by stream_consumer (getattr(..., 4096)).
self.MAX_MESSAGE_LENGTH = descriptor.max_message_length
- # chat_id -> scope_id (server/workspace scope), learned from inbound
- # events. The connector's egress guard resolves the owning tenant from
- # the OUTBOUND action's metadata.scope_id; the gateway's generic delivery
- # path (run.py _thread_metadata_for_source) only carries thread_id, so we
- # re-attach the scope here from what we saw inbound. Keyed by chat_id
- # (channel) since that's what send() receives. See routedEgressGuard.ts.
+ # Per-chat egress routing caches, learned from inbound events (send()
+ # only receives a chat_id). The connector's egress guard resolves the
+ # owning tenant from OUTBOUND metadata.scope_id / metadata.user_id, so
+ # we re-attach them from what we saw inbound (see _capture_scope).
self._scope_by_chat: Dict[str, str] = {}
- # chat_id -> author user_id for DM chats (no scope). A DM reply has
- # no scope discriminator, so the connector resolves its tenant from the
- # recipient's author binding; we re-attach this user_id as
- # metadata.user_id on the outbound action so it can. See _capture_scope.
self._dm_user_by_chat: Dict[str, str] = {}
+ # chat_id -> chat_type; needed to reproduce native Slack's synthetic
+ # DM-thread suppression (a raw reply_to becomes a Slack thread_ts
+ # connector-side, so a plain DM reply would thread under the user).
+ self._chat_type_by_chat: Dict[str, str] = {}
+ # chat_id -> last triggering Slack message ts (typing/status lane's
+ # synthetic thread anchor in thread-per-message mode).
+ self._last_inbound_ts_by_chat: Dict[str, str] = {}
+ # chat_id -> UNDERLYING platform ("discord", ...): one relay adapter
+ # fronts N platforms on one WS and a reply must egress through the
+ # platform the inbound came from. Empty for a single-platform gateway
+ # (the connector falls back to its session default).
+ self._platform_by_chat: Dict[str, str] = {}
# chat_id -> (thread_id, initial_name) of the auto-thread the CONNECTOR
- # created for our most recent send into that chat (auto-thread routing
- # feedback off SendResult — see send()). Consumed by the gateway's
- # semantic thread-rename lane; bounded like the sibling caches.
+ # created for our latest send (SendResult feedback); read by the
+ # semantic thread-rename lane. Bounded like the sibling caches.
self._auto_thread_by_chat: Dict[str, Tuple[str, str]] = {}
- # Bounded FIFO seen-set for inbound replay dedupe (finding #3);
- # dict preserves insertion order, giving cheap oldest-first eviction.
+ # chat_id -> event fired when the entry above lands (wait_for_auto_thread_info).
+ self._auto_thread_waiters: Dict[str, asyncio.Event] = {}
+ # Bounded FIFO seen-set for inbound replay dedupe (insertion-ordered dict).
self._seen_inbound: Dict[str, None] = {}
- # chat_id -> draft_id of the currently OPEN native draft stream
- # (NS-658 live cards). Armed by send_draft on a successful frame;
- # consumed by send() to convert the turn-final delivery into the
- # sealing draft(final=true) frame instead of a duplicate post.
- # Keyed by _draft_key (chat + per-turn identity), NOT bare chat:
- # parallel turns in one DM are distinct streams (live finding #10 —
- # per-chat keying collided three concurrent turns: merged task
- # cards, clobbered seal state, 3x duplicate finals).
+ # Live cards: draft_key -> draft_id of the OPEN native stream. Armed
+ # by send_draft; consumed by send() to convert the turn-final into
+ # draft(final=true) instead of a duplicate post. Keyed by _draft_key
+ # (chat + per-turn identity), NOT bare chat: parallel turns in one DM
+ # are distinct streams (per-chat keying merged three concurrent turns).
self._open_draft_by_chat: Dict[str, int] = {}
- # Strong refs for in-flight fire-and-forget lifecycle acks (asyncio
- # holds tasks weakly; unreferenced tasks can be GC'd mid-flight).
- self._lifecycle_ack_tasks: set = set()
- # Draft keys whose post-seal tombstone swallow has been logged once
- # (observability for the hijacked-live-stream class; bounded FIFO
- # like the sibling caches).
- self._tombstone_swallow_logged: Dict[str, int] = {}
- # chat_id -> draft_id of the most recently SEALED stream (gateway
- # mirror of the connector's sealed-key tombstone): post-seal
- # straggler frames must neither re-arm interception nor re-open a
- # stream. One entry per turn key; a NEW turn's fresh draft_id
- # differs, so it arms normally and writes its own tombstone at its
- # own seal. Bounded like the sibling caches (see send_draft).
+ # draft_key -> draft_id of the most recently SEALED stream (mirror of
+ # the connector's sealed-key tombstone): post-seal stragglers must
+ # neither re-arm interception nor re-open a stream.
self._sealed_draft_by_chat: Dict[str, int] = {}
- # Stream-is-the-message marker (finding #4): the stream consumer
- # checks this to keep ONE draft stream per turn instead of bumping
- # draft_id at tool boundaries (which opens a new Slack message per
- # segment on native streaming — Telegram-shaped adapters want the
- # bump, we don't).
- #
- # SLACK-ONLY semantic, gated on the negotiated descriptor (review
- # B4): the base send_draft contract is Telegram-shaped — the draft
- # clears and the final arrives as a separate real send. Setting
- # this unconditionally made ANY relay connector that advertises
- # the draft op (e.g. a Telegram connector) intercept the turn-final
- # into draft(final=true), so no real history message was ever
- # posted. A future connector platform whose native streaming is
- # also stream-is-the-message should advertise it explicitly
- # (descriptor field within the contract) rather than widening this
- # platform check by guesswork.
+ # Draft keys whose post-seal swallow has been logged once (bounded FIFO).
+ self._tombstone_swallow_logged: Dict[str, int] = {}
+ # Strong refs for fire-and-forget lifecycle acks (asyncio holds tasks weakly).
+ self._lifecycle_ack_tasks: set = set()
+ # Stream-is-the-message marker read by the stream consumer to keep ONE
+ # draft stream per turn instead of bumping draft_id at tool boundaries.
+ # SLACK-ONLY: the base send_draft contract is Telegram-shaped (draft
+ # clears, final arrives as a separate real send); setting this for any
+ # connector advertising "draft" intercepted the turn-final into
+ # draft(final=true) and no history message was ever posted. A future
+ # platform with this semantic should advertise it via the descriptor.
self.draft_stream_is_message = (
str(getattr(descriptor, "platform", "") or "").lower() == "slack"
)
- # chat_id -> event fired when the entry above lands, so a consumer that
- # arrives before the send can wait for it instead of polling. See
- # wait_for_auto_thread_info.
- self._auto_thread_waiters: Dict[str, asyncio.Event] = {}
- # chat_id -> chat_type (e.g. "dm", "channel", "group") learned from the
- # inbound event. Used to reproduce native Slack's synthetic-DM-thread
- # suppression on the relay lane: a DM streaming reply carries
- # reply_to=<triggering message ts> as its edit anchor, but the connector
- # maps a raw reply_to to a Slack thread_ts — so a plain DM reply would be
- # threaded UNDER the user's message (and lose progressive edit streaming)
- # instead of posting flat at the DM root. Native SlackAdapter drops that
- # synthetic reply_to in _resolve_thread_ts; the relay lane needs the same
- # disambiguation, and it needs the chat_type to know a chat is a DM.
- self._chat_type_by_chat: Dict[str, str] = {}
- # chat_id -> last triggering message ts (Slack). The typing/status
- # lane's synthetic thread anchor in thread-per-message mode;
- # see _capture_scope and send_typing.
- self._last_inbound_ts_by_chat: Dict[str, str] = {}
- # chat_id -> the UNDERLYING platform (e.g. "discord", "telegram") this
- # chat belongs to (Phase 1.5 multi-platform-per-agent). One relay adapter
- # fronts N platforms on one WS; an outbound reply must egress through the
- # platform the inbound came from. We remember it per chat_id from the
- # inbound event's source.platform and stamp it on the OutboundFrame so the
- # connector dispatches to the right sender. Empty for a single-platform
- # gateway (the connector falls back to its session default). See
- # _capture_scope / send.
- self._platform_by_chat: Dict[str, str] = {}
self.supports_code_blocks = descriptor.markdown_dialect not in ("", "plain")
- # Cron flat continuable surface — descriptor-advertised (see
- # _apply_descriptor; same bit, constructor path).
self.supports_inchannel_continuable = bool(
getattr(descriptor, "supports_inchannel_continuable", False)
)
- # Phase 7 Unit 7d-B: watches the transport for a terminal auth revocation
- # (a 4401 close after a successful handshake = the operator opted this
- # instance out of the relay). On revocation we surface a clean,
- # non-retryable "relay disabled" fatal so the dashboard stops showing a
- # red "retrying" spin against a dead credential.
+ # Watches the transport for a terminal auth revocation (4401 after a
+ # successful handshake = operator opted this instance out) and surfaces
+ # a clean non-retryable "relay disabled" fatal instead of a retry spin.
self._revocation_monitor: Optional[asyncio.Task[None]] = None
- # Phase 2 media: the authenticated client for the connector's
- # /relay/media routes (upload for send_media source_url; download for
- # inbound re-hosted attachments → local paths the vision/file tools
- # consume). Built lazily from the relay dial URL + per-gateway creds;
- # None when either is absent (media lanes then degrade to the
- # pre-media text fallbacks).
+ # Lazily built client for the connector's /relay/media routes; None when
+ # dial URL or creds are absent (media lanes degrade to text fallbacks).
self._media_client: Optional["RelayMediaClient"] = None
- # Phase 3 interactive: prompt_id -> pending-prompt state. A `prompt`
- # op renders native options; the user's pick comes back inbound as a
- # prompt_response naming this id. The registry maps it back to the
- # waiting primitive (approval / slash-confirm / clarify) so the click
- # resolves EXACTLY like the native adapters' button callbacks.
- # Entries expire lazily (see _pop_prompt) so an unanswered prompt
- # never leaks. Keyed by our own minted ids (see _prompt_owner_nonce).
+ # prompt_id -> pending-prompt state for the interactive `prompt` op; the
+ # user's pick comes back as a prompt_response naming this id and resolves
+ # the waiting primitive exactly like native button callbacks. Entries
+ # expire lazily (_pop_prompt).
self._pending_prompts: Dict[str, Dict[str, Any]] = {}
- # Per-process marker prefixed onto every prompt id this adapter mints,
- # so an answer can be recognized as OURS before it is acted on.
- #
- # WHY: a button press arrives on the passthrough plane, which the
- # connector fans out to EVERY live gateway session of the tenant
- # (relayServer.routeBusMessage delivers `passthrough` via
- # sessionsByTenant, unlike `message`, which narrows to the admitted
- # instance set). The prompt itself went out from exactly one instance,
- # and _pending_prompts is process-local — so every OTHER instance sees
- # an answer for a prompt it never minted. Without this marker those
- # instances cannot tell "a sibling owns this" from "my own prompt
- # expired", and the id-shaped text ("/c1") falls through to chat
- # dispatch, where run.py answers "Unknown command `/c1`" — one copy per
- # sibling gateway. Siblings are the common case in a DM: the connector
- # resolves the invoker's bindings to DISTINCT TENANTS, so several
- # instances of one tenant all receive the forward.
+ # Per-process marker prefixed onto every prompt id we mint. WHY: button
+ # presses ride the passthrough plane, which the connector fans out to
+ # EVERY live gateway session of the tenant, while _pending_prompts is
+ # process-local. Without the marker a sibling cannot tell "someone
+ # else owns this" from "my prompt expired", and the id-shaped text
+ # ("/c1") falls through to chat dispatch as "Unknown command" — once
+ # per sibling. Siblings are the common case in a DM.
self._prompt_owner_nonce: str = secrets.token_hex(3)
- # Prompt ids this process has already resolved, newest last. A repeat
- # answer for the same id (double tap, or a connector redelivery) is
- # then consumed silently instead of being treated as a stale prompt.
+ # Prompt ids this process already resolved, newest last (repeat
+ # answers are consumed silently instead of treated as stale).
self._resolved_prompts: "OrderedDict[str, float]" = OrderedDict()
# ── capability surface (from descriptor) ─────────────────────────────
@property
def authorization_is_upstream(self) -> bool:
- """Relay authorization is enforced by the connector, not locally.
-
- The connector authenticates this gateway's WS (per-instance secret) and
- performs owner-only author-binding resolution before delivering, so any
- inbound relay event was already authorized as THIS instance's bound user
- (``user_instance_binding``, keyed on the connector-observed author id).
- The instance therefore must not default-deny relay users for lack of a
- local ``RELAY_ALLOWED_USERS`` env allowlist. See
- ``BasePlatformAdapter.authorization_is_upstream``.
- """
+ """Authorization is enforced by the connector (owner-only author-binding
+ resolution before delivery), so relay users must not be default-denied
+ for lack of a local ``RELAY_ALLOWED_USERS`` allowlist."""
return True
@property
@@ -246,52 +191,43 @@ class RelayAdapter(BasePlatformAdapter):
def supports_status_text(self) -> bool: # type: ignore[override]
"""Whether the fronted platform renders a TEXT status line.
- Native parity (rich status text): Slack's typing surface is the
- assistant status line ("Finding answers…" next to the bot name), a
- text-rendering indicator. When the relay fronts Slack, advertise it so
- run.py's live-status lane feeds per-tool phrases via
- ``set_status_text()`` — exactly the wiring the native SlackAdapter
- gets (``supports_status_text = True``). Other fronted platforms keep
- textless typing bubbles and must NOT receive phrase traffic.
-
- Property (not class attr) because ONE RelayAdapter class fronts many
- platforms; the answer depends on the handshaked descriptor. On a
- multi-platform relay this scalar reflects the PRIMARY identity's
- platform (same convention as the scalar ``descriptor``); per-chat
- egress paths that need chat-accurate capabilities use
- ``_descriptor_for_chat`` below.
+ Slack's typing surface is the assistant status line, so run.py's
+ live-status lane may feed per-tool phrases (native SlackAdapter parity);
+ other platforms have textless bubbles and must NOT receive phrases.
+ Reflects the PRIMARY identity's platform, like the scalar ``descriptor``.
"""
- return self.descriptor.platform == Platform.SLACK.value
+ return self.descriptor.platform == _SLACK
+
+ # ── per-chat capability resolution (multi-platform) ──────────────────
+ def _negotiated_descriptor(self, platform: Optional[str]) -> Optional[CapabilityDescriptor]:
+ """The transport's negotiated descriptor for ``platform``, or None
+ (unknown platform, no transport, or a transport predating
+ ``descriptor_for_platform``). Never raises — capability lookup must
+ never break a send."""
+ if not platform or self._transport is None:
+ return None
+ resolve = getattr(self._transport, "descriptor_for_platform", None)
+ if not callable(resolve):
+ return None
+ try:
+ return resolve(platform)
+ except Exception: # noqa: BLE001
+ return None
+
+ def _chat_platform(self, chat_id: str) -> Optional[str]:
+ """The chat's underlying platform as seen inbound, else the primary's."""
+ return self._platform_by_chat.get(str(chat_id)) or self.descriptor.platform
- # ── per-chat capability resolution (Phase 1.5 multi-platform) ─────────
def _descriptor_for_chat(self, chat_id: str) -> CapabilityDescriptor:
"""The capability descriptor governing a specific chat.
- A multi-platform gateway fronts N platforms on ONE adapter, but the
- scalar `descriptor`/`MAX_MESSAGE_LENGTH` surface can only carry one
- platform's profile (the primary identity's). Platform caps genuinely
- differ — Discord 2000 / Telegram 4096 / Slack 39000 — so applying the
- primary's cap to every chat either fragments needlessly (small primary)
- or over-sends into a platform 400 (large primary; the live bug: 2,543
- and 2,641-char sends rejected by Discord). Resolve the chat's platform
- from what we saw inbound (`_platform_by_chat`, the same map per-frame
- egress uses) and look up that platform's negotiated descriptor on the
- transport. Falls back to the scalar descriptor when the chat's platform
- is unknown (never saw inbound) or the transport predates the map.
+ Platform caps genuinely differ (Discord 2000 / Telegram 4096 / Slack
+ 39000), so the primary's scalar cap either fragments needlessly or
+ over-sends into a platform 400. Falls back to the scalar descriptor
+ when the chat's platform is unknown (never saw inbound).
"""
- platform = self._platform_by_chat.get(str(chat_id))
- if platform and self._transport is not None:
- resolve = getattr(self._transport, "descriptor_for_platform", None)
- if callable(resolve):
- try:
- per_platform = cast(
- Optional[CapabilityDescriptor], resolve(platform)
- )
- except Exception: # noqa: BLE001 - capability lookup must never break a send
- per_platform = None
- if per_platform is not None:
- return per_platform
- return self.descriptor
+ per_platform = self._negotiated_descriptor(self._platform_by_chat.get(str(chat_id)))
+ return per_platform if per_platform is not None else self.descriptor
def max_message_length_for_chat(self, chat_id: str) -> int:
return self._descriptor_for_chat(chat_id).max_message_length
@@ -305,20 +241,10 @@ class RelayAdapter(BasePlatformAdapter):
metadata: Optional[Dict[str, Any]] = None,
chat_id: Optional[str] = None,
) -> bool:
- # Native draft streaming needs BOTH the descriptor flag and the
- # "draft" op. supported_ops is fail-open for legacy connectors
- # (empty tuple = pre-contract ops only), but "draft" did not exist
- # pre-contract, so it must NOT fail open: an explicit advertisement
- # is required. Without it the stream consumer stays on the
- # edit-based path exactly as today.
- #
- # Per-chat resolution (review r2, finding 2): one adapter fronts N
- # platforms, and the scalar descriptor only reflects the PRIMARY
- # identity — a Telegram primary must not starve a secondary Slack
- # chat of native streaming, nor vice versa. When the caller can
- # name the chat, resolve through its platform's negotiated
- # descriptor; the scalar remains the fallback (chat unknown,
- # single-platform gateways: identical behavior).
+ # Needs BOTH the descriptor flag and an explicit "draft" op: supported_ops
+ # is fail-open for legacy connectors, but "draft" did not exist
+ # pre-contract, so it must NOT fail open. Resolved per chat when the
+ # caller names one (a Telegram primary must not starve a Slack chat).
desc = (
self._descriptor_for_chat(str(chat_id))
if chat_id is not None
@@ -329,15 +255,10 @@ class RelayAdapter(BasePlatformAdapter):
and "draft" in (desc.supported_ops or ())
):
return False
- # Slack chat.*Stream has no unfurl_links / unfurl_media. Native
- # SlackAdapter already refuses streaming when those knobs are set
- # so chat.postMessage can carry them. Mirror that here or a
- # configured true never reaches Slack (bot default = no preview).
- platform = None
- if chat_id is not None:
- platform = self._platform_by_chat.get(str(chat_id))
- if platform is None:
- platform = getattr(desc, "platform", None)
+ # Slack chat.*Stream has no unfurl_links / unfurl_media; like native
+ # SlackAdapter, refuse streaming when those knobs are set so
+ # chat.postMessage can carry them.
+ platform = self._chat_platform(chat_id) if chat_id is not None else desc.platform
return not self._slack_unfurl_hints(platform)
def prefers_fresh_final_streaming(
@@ -348,115 +269,70 @@ class RelayAdapter(BasePlatformAdapter):
) -> bool:
"""Deliver streamed finals as a FRESH send when Slack unfurl is forced on.
- Slack evaluates link previews exactly once, at ``chat.postMessage``
- time (live-probed 2026-08-28: URL at post + ``unfurl_links: true``
- unfurls; a ``chat.update`` that INTRODUCES the URL never does, stamps
- or not). Edit-based streaming posts its first frame before the model
- has produced any URL — a tool-progress card or an early text frame —
- so a configured ``unfurl_links/media: true`` can never surface a
- preview through the edit lane: the only post Slack evaluates has no
- link in it.
-
- Returning True routes the completed reply through the consumer's
- fresh-final path: one new ``send`` carrying the full content, which
- ``send()`` stamps with the unfurl hints — URL and flags present at
- the single moment Slack looks.
-
- Scope: ONLY when the hints contain an explicit True. False-only
- hints (the enterprise fail-closed posture) keep the edit lane —
- suppression rides the placeholder post and an edit can never add a
- preview afterwards, so ``false`` inherits correctly with zero
- streaming-UX cost.
+ Slack evaluates link previews exactly once, at ``chat.postMessage``;
+ a ``chat.update`` that INTRODUCES the URL never unfurls. Edit-based
+ streaming posts its first frame before any URL exists, so a configured
+ ``unfurl_*: true`` can only surface via a fresh final that ``send()``
+ stamps with the hints. ONLY when the hints contain an explicit True:
+ false-only hints (fail-closed posture) ride the placeholder post fine.
+ Only link-bearing finals qualify — the relay has no delete op in
+ contract v1, so a linkless fresh final would just be a duplicate.
"""
platform = None
if chat_id is not None:
platform = self._platform_by_chat.get(str(chat_id))
- # The stream consumer's hook call passes (content, metadata=...) only
- # — no chat_id — so resolve through the turn metadata's platform when
- # present before falling back to the primary descriptor.
+ # The stream consumer's hook passes (content, metadata=...) only.
if platform is None and isinstance(metadata, dict):
platform = metadata.get("platform")
if platform is None:
- platform = getattr(self.descriptor, "platform", None)
+ platform = self.descriptor.platform
hints = self._slack_unfurl_hints(platform)
- if not hints:
- return False
- if not any(v is True for v in hints.values()):
+ if not hints or not any(v is True for v in hints.values()):
return False
- # Only link-bearing finals benefit: without a URL there is nothing to
- # unfurl, and the relay has no delete op (connector contract v1), so
- # the streamed preview stays behind the fresh final. Keep the edit
- # lane for linkless replies to avoid a pointless duplicate message.
return bool(_URL_RE.search(content or ""))
def stream_is_message_for_chat(self, chat_id: str) -> bool:
- """Per-chat stream-is-the-message semantic (review r2, finding 2).
-
- The class-level ``draft_stream_is_message`` can only reflect the
- primary identity's platform. On a multi-platform relay, a Slack
- primary must not impose seal semantics on a Telegram chat (its
- turn-final would become draft(final=true) — no history message),
- and a Telegram primary must not deny a secondary Slack chat its
- native streaming. Resolve through the chat's own negotiated
- descriptor. Platform-name inference is deliberate for now — a
- descriptor-level field is the eventual contract (gg follow-up)
- so a future platform can advertise the semantic explicitly.
+ """Per-chat stream-is-the-message semantic (see ``draft_stream_is_message``).
+
+ A Slack primary must not impose seal semantics on a Telegram chat (its
+ turn-final would become draft(final=true) — no history message), nor a
+ Telegram primary deny a Slack chat native streaming. Platform-name
+ inference is deliberate; a descriptor field is the eventual contract.
"""
return (
str(self._descriptor_for_chat(str(chat_id)).platform or "").lower()
== "slack"
)
- # ── Live cards: native draft streaming + task cards (NS-658) ─────────
+ # ── Live cards: native draft streaming + task cards ──────────────────
#
- # Additive relay ops within contract v1. The gateway side is dumb: it
- # emits ops when the negotiated descriptor advertises them; the
- # connector owns the platform API mechanics (chat.startStream et al.),
- # per-workspace feature-gate caching, and the send+edit fallback.
- #
- # Semantic bridge: the base send_draft contract is Telegram-shaped —
- # the draft clears and the final answer arrives as a separate send().
- # Slack native streaming makes the stream THE message, sealed once.
- # The adapter tracks the open draft per chat; the turn-final send()
- # for that chat converts to draft(final=true) so the connector seals
- # the stream instead of posting a duplicate message.
+ # Additive relay ops within contract v1. The gateway emits ops when the
+ # negotiated descriptor advertises them; the connector owns the platform
+ # API mechanics, feature-gate caching, and the send+edit fallback.
+ # Semantic bridge: the base send_draft contract is Telegram-shaped (draft
+ # clears, final arrives as a separate send()); Slack native streaming
+ # makes the stream THE message. The adapter tracks the open draft per turn
+ # and converts that turn's final send() into draft(final=true).
def supports_native_task_cards(self) -> bool:
- """Descriptor probe for the TurnRunner's task-card lane.
-
- Explicit advertisement required — same no-fail-open rule as
- "draft" (the op did not exist pre-contract).
- """
+ """Explicit advertisement required — same no-fail-open rule as "draft"."""
return "task_card" in (self.descriptor.supported_ops or ())
def native_task_cards_enabled(self) -> bool:
- """TurnRunner opt-in probe (gateway/run.py) — the card lane calls
- THIS name (same contract as the native Slack adapter's opt-in);
- ``supports_native_task_cards`` is the descriptor-level capability.
- Live-canary finding: without this alias the lane silently stays
- text-mode (hasattr probe fails) even though the connector
- advertises task_card."""
+ """TurnRunner opt-in probe (gateway/run.py calls THIS name, same contract as
+ native Slack); without the alias the card lane silently stays text-mode."""
return self.supports_native_task_cards()
@staticmethod
def _draft_key(chat_id: str, metadata: Optional[Dict[str, Any]]) -> str:
"""Coordination key for one turn's stream.
- Prefers a PER-TURN identity — the triggering inbound message id
- (``message_id`` is stamped by the gateway's Slack thread metadata,
- ``reply_to_message_id`` by the consumer's send path; both carry the
- same event id) — over the thread anchor. Finding #10 keyed on the
- thread anchor alone, which is simultaneously too coarse and too
- fragile (review B2 + flat-DM concern):
-
- - two parallel turns REPLYING INSIDE ONE THREAD share thread_ts,
- so turn A's final sealed turn B's stream with A's content;
- - a flat DM whose metadata carries no anchor at all degraded to
- the bare chat id, re-creating the original #10 collision.
-
- The thread anchor remains the fallback for callers that only have
- placement metadata, and the bare chat is the last resort
- (single-turn semantics).
+ Prefers a PER-TURN identity (the triggering inbound message id, stamped
+ as ``message_id`` or ``reply_to_message_id``) over the thread anchor:
+ two parallel turns replying inside ONE thread share thread_ts (turn A's
+ final sealed turn B's stream), and a flat DM with no anchor degraded to
+ the bare chat id. The anchor remains the fallback for placement-only
+ callers; the bare chat is the last resort.
"""
md = metadata or {}
turn_id = md.get("message_id") or md.get("reply_to_message_id")
@@ -465,15 +341,13 @@ class RelayAdapter(BasePlatformAdapter):
anchor = md.get("thread_ts") or md.get("thread_id") or ""
return f"{chat_id}:{anchor}"
- # Cap for the draft/seal coordination dicts, matching the sibling
- # bounded caches (_auto_thread_by_chat). Entries are per-turn keys;
- # 512 in-flight-or-recent turns per adapter is far beyond any real
- # concurrency, and matches the connector's tombstone store size.
+ # Cap for the draft/seal coordination dicts (per-turn keys); matches the
+ # connector's tombstone store size.
_DRAFT_STATE_CAP = 512
@classmethod
def _evict_oldest(cls, d: Dict[str, int]) -> None:
- """FIFO-bound a coordination dict in place (review M1)."""
+ """FIFO-bound a coordination dict in place."""
while len(d) > cls._DRAFT_STATE_CAP:
d.pop(next(iter(d)), None)
@@ -483,12 +357,8 @@ class RelayAdapter(BasePlatformAdapter):
) -> str:
"""Per-turn task-card identity — same precedence as ``_draft_key``.
- ``reply_to`` (the triggering message id from the TurnRunner) wins;
- metadata message ids cover the flat-DM / resolver lanes; the thread
- anchor is only a fallback because two turns replying inside one
- thread share ``thread_ts`` and must not share a card (review B2).
- One derivation for send AND stop, so the stop always hits the
- stream the send opened.
+ One derivation for send AND stop, so the stop always hits the stream
+ the send opened.
"""
md = metadata or {}
anchor = (
@@ -506,32 +376,16 @@ class RelayAdapter(BasePlatformAdapter):
) -> Optional[str]:
"""Resolve which open stream (if any) a turn-final send belongs to.
- Exact key match first. Callers WITHOUT a per-turn message id fall
- into two classes (review r2, finding 5):
-
- - placement-only metadata (thread_ts/thread_id but no message
- id — legacy resolver lanes): the thread anchor is placement
- info, not turn identity, and streams are keyed per turn — an
- exact match will practically never fire for them. They may
- still absorb the final via the single-open-stream fallback.
- - no metadata at all: same fallback.
-
- The fallback only fires when the chat has EXACTLY one open
- stream. With several open, the send stays a plain send: a
- duplicate message is recoverable, sealing someone else's stream
- with the wrong content is not (review B2). Callers that DO carry
- a message id never fall back — their identity is authoritative,
- and a mismatch means the stream is someone else's.
+ Exact key match first. Callers carrying a per-turn MESSAGE id never
+ fall back — their identity is authoritative. Callers without one
+ (placement-only metadata, or none) may absorb into the chat's single
+ open stream; with several open the send stays plain: a duplicate
+ message is recoverable, sealing someone else's stream is not.
"""
key = self._draft_key(str(chat_id), metadata)
if key in self._open_draft_by_chat:
return key
md = metadata or {}
- # Only a per-turn MESSAGE id is turn identity. Thread anchors are
- # placement info shared by every turn in the thread — treating
- # them as identity made the single-open-stream fallback dead for
- # placement-only callers (probed: plain final beside an open
- # turn-keyed stream).
if md.get("message_id") or md.get("reply_to_message_id"):
return None
prefix = f"{chat_id}:"
@@ -539,10 +393,8 @@ class RelayAdapter(BasePlatformAdapter):
k for k in self._open_draft_by_chat if k.startswith(prefix)
]
if len(candidates) == 1:
- # Absorbing a send into a stream is a significant, previously
- # silent decision — the wrong caller matching here is exactly
- # the prompt-ack-seals-own-stream bug (rc.4 live finding). Say
- # it out loud so the next mismatch is a grep, not a hunt.
+ # Absorbing a send into a stream is a significant decision (the
+ # prompt-ack-seals-own-stream bug); log it so the next mismatch is a grep.
logger.info(
"relay: absorbing identity-less send into the single open "
"stream %s (single-open-stream fallback)",
@@ -551,6 +403,21 @@ class RelayAdapter(BasePlatformAdapter):
return candidates[0]
return None
+ async def _outbound(self, chat_id: str, action: Dict[str, Any]) -> Dict[str, Any]:
+ """Send one outbound frame tagged with the chat's underlying platform."""
+ return await self._transport.send_outbound( # type: ignore[union-attr]
+ action, platform=self._platform_by_chat.get(str(chat_id))
+ )
+
+ def _text_metadata(self, chat_id: str, metadata: Optional[Dict[str, Any]]) -> Dict[str, Any]:
+ """Metadata for a text egress frame: format hints + tenant discriminators.
+
+ Boundary rule (live relay testing): draft, seal, send and edit are all
+ text lanes — a streamed final can only render blocks if every frame
+ carries the hint (a hintless seal is the plain-code-block downgrade).
+ """
+ return self._with_scope(chat_id, self._with_format_hints_for_chat(chat_id, metadata))
+
async def send_draft(
self,
chat_id: str,
@@ -564,26 +431,16 @@ class RelayAdapter(BasePlatformAdapter):
)
if self._transport is None:
return SendResult(success=False, error="no transport")
- # Audit fix G-D1 + regression fix (2026-08-15): arm optimistically
- # BEFORE the transport call (lossy ack: a timeout/WS-drop 'failure'
- # often means delivered), but NEVER for a draft_id that has already
- # been sealed this chat — the gateway-side mirror of the connector's
- # sealed-key tombstone. Without this, a straggler frame arriving
- # after the seal re-armed interception with no live stream, and the
- # next unrelated send (media follow-up, next-turn text) was wrongly
- # converted to draft(final=true) on the tombstoned key — clearing
- # the tombstone, re-opening a stream, and freezing it (the observed
- # escalating-frozen-prefixes regression).
+ # Arm optimistically BEFORE the transport call (a lossy ack often means
+ # delivered), but NEVER for a draft_id already sealed on this key: a
+ # straggler after the seal re-armed interception with no live stream,
+ # and the next unrelated send was wrongly converted into a seal.
chat_key = self._draft_key(str(chat_id), metadata)
if self._sealed_draft_by_chat.get(chat_key) == draft_id:
- # Post-seal straggler: its content is already in the sealed
- # message; report success, send nothing, arm nothing. Log the
- # FIRST swallow per key at WARNING — one straggler is the
- # normal race this tombstone exists for, but a hijacked live
- # stream (something else sealed this draft mid-flight) shows
- # up as a burst of swallows, and silence here cost a full
- # forensic hunt (rc.4: prompt ack sealed the turn's own draft
- # and every later append vanished without a line).
+ # Post-seal straggler: content is already in the sealed message;
+ # report success, send nothing. Log the FIRST swallow per key —
+ # one straggler is the normal race, but a burst means something
+ # sealed a live stream mid-flight (silence here cost a forensic hunt).
if chat_key not in self._tombstone_swallow_logged:
self._tombstone_swallow_logged[chat_key] = draft_id
self._evict_oldest(self._tombstone_swallow_logged)
@@ -596,58 +453,38 @@ class RelayAdapter(BasePlatformAdapter):
draft_id,
)
return SendResult(success=True)
- # Arm seal-interception ONLY for stream-is-the-message chats
- # (review B4, per-chat in r2 finding 2): on a Telegram-shaped
- # connector the draft clears client-side and the final MUST go out
- # as a separate real send — arming here would intercept that final
- # into draft(final=true) and no history message would ever be
- # posted. Resolved per chat: one adapter fronts N platforms.
+ # Arm seal-interception ONLY for stream-is-the-message chats: on a
+ # Telegram-shaped connector the final MUST go out as a real send.
if self.stream_is_message_for_chat(str(chat_id)):
self._open_draft_by_chat[chat_key] = draft_id
self._evict_oldest(self._open_draft_by_chat)
try:
- result = await self._transport.send_outbound(
+ result = await self._outbound(
+ chat_id,
{
"op": "draft",
"chat_id": chat_id,
"draft_id": draft_id,
"content": content,
"final": False,
- # Boundary rule (observed in live relay testing): the draft lane
- # is a text egress lane like send/edit — a streamed final
- # can only render blocks if its frames carry the hint.
- "metadata": self._with_scope(
- chat_id,
- self._with_format_hints_for_chat(
- chat_id, dict(metadata or {})
- ),
- ),
+ "metadata": self._text_metadata(chat_id, dict(metadata or {})),
},
- platform=self._platform_by_chat.get(str(chat_id)),
)
except Exception as e:
- # Ambiguous by definition (stale socket, mid-write drop): the
- # frame may have been delivered. Keep interception armed.
+ # Ambiguous (stale socket, mid-write drop): may have been delivered;
+ # keep interception armed.
return SendResult(success=False, error=f"draft transport error: {e}")
if result.get("success"):
return SendResult(success=True)
if result.get("ambiguous"):
- # Ack lost (transport timeout) — the production ws transport
- # RETURNS this shape rather than raising (PR 85796 review,
- # round 2): the connector may have applied the frame. Same
- # contract as the except branch: keep interception armed.
+ # Ack lost (transport timeout, returned rather than raised): same
+ # contract as the except branch — keep interception armed.
return SendResult(
success=False, error=str(result.get("error") or "draft ack lost")
)
- # DEFINITE connector rejection (an explicit non-ambiguous result):
- # disarm interception for this key. The stream consumer disables
- # the draft transport on this failure and falls back to edit-based
- # streaming — its turn-final must go out as a REAL send, not get
- # converted into a seal on a stream the connector just told us is
- # unusable. (This restores the disarm-on-failure semantics the
- # G-D1 optimistic-arming change silently dropped; the ambiguity
- # that motivated G-D1 lives in the except branch above and the
- # ambiguous-result branch — both keep the key armed.)
+ # DEFINITE connector rejection: disarm. The stream consumer falls back
+ # to edit-based streaming and its turn-final must go out as a REAL
+ # send, not a seal on a stream the connector just declared unusable.
if self._open_draft_by_chat.get(chat_key) == draft_id:
self._open_draft_by_chat.pop(chat_key, None)
return SendResult(
@@ -666,15 +503,10 @@ class RelayAdapter(BasePlatformAdapter):
if draft_key is None:
draft_key = self._draft_key(str(chat_id), metadata)
draft_id = self._open_draft_by_chat.pop(draft_key)
- # Tombstone BEFORE the transport call (regression fix): whatever the
- # ack says, this draft_id's stream must never be re-armed by a
- # straggler frame — the connector-side tombstone handles its half.
+ # Tombstone BEFORE the transport call: whatever the ack says, this
+ # draft_id must never be re-armed by a straggler frame. Bounded FIFO —
+ # the straggler window is seconds, and the key embeds a per-turn identity.
self._sealed_draft_by_chat[draft_key] = draft_id
- # Bounded like the sibling caches (review M1): the key embeds a
- # per-turn identity, so an unbounded dict grows one entry per turn
- # for the life of the process. FIFO eviction matches the
- # straggler window this tombstone exists for (seconds, not days);
- # the connector holds its own 512-entry tombstone store.
self._evict_oldest(self._sealed_draft_by_chat)
if self._transport is None:
return SendResult(success=False, error="no transport")
@@ -684,56 +516,34 @@ class RelayAdapter(BasePlatformAdapter):
"draft_id": draft_id,
"content": content,
"final": True,
- # Same boundary rule as the interim frame: the SEAL frame is the
- # one the connector's block reconcile reads — a hintless seal is
- # exactly the plain-code-block downgrade seen in live relay testing.
- "metadata": self._with_scope(
- chat_id,
- self._with_format_hints_for_chat(chat_id, dict(metadata or {})),
- ),
+ "metadata": self._text_metadata(chat_id, dict(metadata or {})),
}
+
_seal_platform = self._platform_by_chat.get(str(chat_id))
_transport = self._transport # narrowed by the None-guard above
async def _attempt() -> Optional[Dict[str, Any]]:
"""One seal attempt; None means ambiguous (exception or lost ack)."""
try:
- r = await _transport.send_outbound(
- seal_frame, platform=_seal_platform
- )
- except asyncio.CancelledError:
- raise
+ r = await _transport.send_outbound(seal_frame, platform=_seal_platform)
except Exception as e:
logger.warning("relay seal transport error (ambiguous): %s", e)
return None
if r.get("ambiguous"):
- # The production ws transport returns this shape on ack
- # timeout instead of raising (PR 85796 review, round 2):
- # the connector may have sealed and lost only the ack.
logger.warning(
"relay seal ack lost (ambiguous): %s", r.get("error")
)
return None
return r
- # Ambiguous outcomes (exception OR timeout-shaped result) retry the
- # SAME idempotent frame once: the connector's sealed-key tombstone
- # returns the original stream ts for a repeated final and never
- # opens a second stream, so the retry can turn "unknown" into a
- # definite answer for free. Only after BOTH attempts stay ambiguous
- # do we report failure — the caller's fail-open plain send is a
- # possible duplicate, but a silent loss is worse, and two
- # consecutive ack losses on one socket almost always mean the
- # transport is actually down (so the plain send fails too and the
- # gateway's fallback owns delivery).
+ # Ambiguous outcomes retry the SAME idempotent frame once: the
+ # connector's sealed-key tombstone returns the original stream ts for
+ # a repeated final and never opens a second stream. Two consecutive
+ # ack losses on one socket almost always mean the transport is down.
#
- # Cancellation safety (review r2, finding 4): the open entry was
- # popped and the tombstone written BEFORE the await. If the task is
- # cancelled mid-seal, CancelledError bypasses the failure handling
- # and the later abandon pass would find nothing to close — the
- # connector-side stream stays visibly live until eviction. Restore
- # the open entry (and drop our premature tombstone) before
- # re-raising so the abandon path can seal it.
+ # Cancellation safety: the open entry was popped and the tombstone
+ # written BEFORE the await. Restore both before re-raising so the
+ # later abandon pass can still seal the stream.
try:
result = await _attempt()
if result is None:
@@ -758,6 +568,33 @@ class RelayAdapter(BasePlatformAdapter):
success=False, error=str(result.get("error") or "draft seal failed")
)
+ async def _absorb_into_open_draft(
+ self, chat_id: str, content: str, metadata: Dict[str, Any], interim: bool
+ ) -> Optional[SendResult]:
+ """Seal an open native stream with this turn-final; None = do a plain send.
+
+ An open stream absorbs the turn-final no matter which egress door it
+ arrives through (send / send_for_platform) — otherwise the stream is
+ left frozen mid-word AND the final posts as a duplicate. A failed seal
+ must NOT swallow the final: the consumer already disabled the draft
+ transport, so fall through to a plain send (the orphaned stream is
+ sealed connector-side by recycling / eviction). Interim sends
+ (commentary, tail flush, lifecycle acks) never seal.
+ """
+ if interim:
+ return None
+ key = self._match_open_draft(str(chat_id), metadata)
+ if key is None:
+ return None
+ seal = await self._seal_open_draft(chat_id, content, metadata, draft_key=key)
+ if seal.success:
+ return seal
+ logger.warning(
+ "relay seal failed (%s); delivering turn-final as plain send",
+ seal.error,
+ )
+ return None
+
async def send_native_task_card_progress(
self,
chat_id: str,
@@ -768,21 +605,12 @@ class RelayAdapter(BasePlatformAdapter):
metadata: Optional[Dict[str, Any]] = None,
fallback_text: Optional[str] = None,
) -> SendResult:
- """Relay leg of the #85476 task-card lane: emit one card frame.
-
- SIGNATURE CONTRACT (live-canary finding): the TurnRunner calls this
- with the NATIVE Slack adapter's keyword contract (tasks/title/
- reply_to/metadata/fallback_text) — not a card_id. The card stream
- key is derived per (chat, reply_to-thread): one card per turn
- thread, matching the connector's (channel, card_id) keying.
- ``fallback_text``/``title`` are accepted for contract parity; the
- connector's plan-mode stream renders task chunks, so they are not
- forwarded.
-
- ``tasks`` are the TurnRunner's normalized task dicts (id/title/
- status/details/output); the connector maps them onto its
- workspace-scoped card stream (task_update chunks, 256-char field
- limits enforced connector-side where the API lives).
+ """Relay leg of the task-card lane: emit one card frame.
+
+ SIGNATURE CONTRACT: the TurnRunner calls this with the NATIVE Slack
+ adapter's keyword contract, not a card_id. ``fallback_text``/``title``
+ are accepted for parity but not forwarded (the connector's plan-mode
+ stream renders task chunks; field limits are enforced connector-side).
"""
if not self.supports_native_task_cards():
return SendResult(
@@ -790,20 +618,14 @@ class RelayAdapter(BasePlatformAdapter):
)
if self._transport is None:
return SendResult(success=False, error="no transport")
- # Finding #10 + review B2: one card per TURN. reply_to (the
- # triggering message id) is already per-turn; when it is absent
- # (flat DM, resolver lanes) fall back to the same per-turn
- # identity the draft lane keys on — metadata message ids first,
- # thread anchor only after that (two turns replying inside one
- # thread share thread_ts and must not share a card).
card_id = self._card_key(reply_to, metadata)
merged_meta = dict(metadata or {})
if reply_to and "thread_ts" not in merged_meta:
- # Slack card streams are thread replies (same rule as draft):
- # anchor on the triggering message when the runner gave us one.
+ # Slack card streams are thread replies anchored on the trigger.
merged_meta["thread_ts"] = str(reply_to)
try:
- result = await self._transport.send_outbound(
+ result = await self._outbound(
+ chat_id,
{
"op": "task_card",
"chat_id": chat_id,
@@ -811,12 +633,10 @@ class RelayAdapter(BasePlatformAdapter):
"chunks": [dict(t) for t in tasks],
"metadata": self._with_scope(chat_id, merged_meta),
},
- platform=self._platform_by_chat.get(str(chat_id)),
)
except Exception as e:
- # Progress is advisory: a transport drop must degrade to the
- # TurnRunner's text fallback (failed SendResult), never raise
- # into the progress loop / turn-cleanup path (review B7 — an
+ # Progress is advisory: degrade to the TurnRunner's text fallback,
+ # never raise into the progress loop / turn-cleanup path (an
# escaping card exception in cleanup skipped final delivery).
return SendResult(
success=False, error=f"task_card transport error: {e}"
@@ -834,36 +654,27 @@ class RelayAdapter(BasePlatformAdapter):
reply_to: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
- """Seal the card stream at turn end (idempotent connector-side).
-
- Same NATIVE-contract signature as send (canary finding above);
- card key derived identically so the stop hits the open stream.
- """
+ """Seal the card stream at turn end (idempotent connector-side); same key derivation as send."""
if not self.supports_native_task_cards():
return SendResult(
success=False, error="connector does not advertise task_card"
)
if self._transport is None:
return SendResult(success=False, error="no transport")
- # Same per-turn key derivation as send (shared helper) so the stop
- # hits the open stream.
- card_id = self._card_key(reply_to, metadata)
try:
- result = await self._transport.send_outbound(
+ result = await self._outbound(
+ chat_id,
{
"op": "task_card_stop",
"chat_id": chat_id,
- "card_id": card_id,
+ "card_id": self._card_key(reply_to, metadata),
"metadata": self._with_scope(chat_id, dict(metadata or {})),
},
- platform=self._platform_by_chat.get(str(chat_id)),
)
except Exception as e:
- # Best-effort by contract: the stop runs in the progress loop's
- # finally block on the turn-cleanup path — an escaping transport
- # exception there skipped final delivery (review B7). The
- # connector seals orphaned card streams on its own (recycling /
- # eviction), so a lost stop is cosmetic.
+ # Runs in the progress loop's finally block: an escaping exception
+ # there skipped final delivery. A lost stop is cosmetic (the
+ # connector seals orphaned card streams on its own).
return SendResult(
success=False, error=f"task_card_stop transport error: {e}"
)
@@ -875,19 +686,12 @@ class RelayAdapter(BasePlatformAdapter):
content: str,
metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
- """Seal an orphaned stream when its turn dies (review B8).
-
- A stopped (/stop, /new) or superseded turn previously left its
- native stream open forever: the Slack message kept the live
- streaming indicator and the adapter kept armed interception state,
- which the NEXT turn's key could inherit. Seal in place with
- ``content`` — the text already on screen (the consumer passes its
- last delivered frame), so the seal adds nothing and claims
- nothing: it only ends the stream. Delivery flags are the
- consumer's business; this never sets any.
-
- Best-effort by contract: failure is reported, never raised — the
- connector reaps truly orphaned streams via recycling/eviction.
+ """Seal an orphaned stream when its turn dies (/stop, /new, supersede).
+
+ Seals in place with ``content`` (the text already on screen) so the
+ seal adds and claims nothing; otherwise the live indicator stays
+ forever and the NEXT turn could inherit the armed interception state.
+ Best-effort: failure is reported, never raised.
"""
draft_key = self._match_open_draft(str(chat_id), metadata)
if draft_key is None:
@@ -901,67 +705,44 @@ class RelayAdapter(BasePlatformAdapter):
success=False, error=f"abandon seal transport error: {e}"
)
-
# ── abstract methods (delegated to the transport) ────────────────────
async def connect(self, *, is_reconnect: bool = False) -> bool:
- # ``is_reconnect`` is part of the BasePlatformAdapter.connect contract:
- # the gateway's reconnect watcher (gateway/run.py) re-establishes a
- # platform after a fatal adapter error by building a fresh adapter and
- # calling ``connect(is_reconnect=True)``. Relay MUST accept the kwarg or
- # that recovery path raises TypeError and the relay platform can never
- # come back through the watcher.
- #
- # Relay deliberately IGNORES the flag. The flag exists so adapters with a
- # server-side update queue (e.g. Telegram's Bot API) preserve that queue
- # across an outage instead of dropping it (#46621). Relay has no such
- # gateway-side queue: messages buffered during a gap live in the
- # CONNECTOR's durable buffer and are replayed when the transport
- # re-handshakes. Routine WS drops are handled entirely by the transport's
- # own reconnect supervisor (WebSocketRelayTransport, reconnect=True);
- # a watcher-driven reconnect builds a fresh transport from scratch (the
- # fatal-error handler disconnect()s the old adapter first, cancelling its
- # supervisor), so there is nothing at the adapter layer to preserve.
+ # ``is_reconnect`` is part of the BasePlatformAdapter.connect contract
+ # (the reconnect watcher calls connect(is_reconnect=True); refusing the
+ # kwarg would break that recovery path). Relay IGNORES it: messages
+ # buffered during a gap live in the CONNECTOR's durable buffer and
+ # replay on re-handshake; routine WS drops are handled by the
+ # transport's own reconnect supervisor.
if self._transport is None:
raise RuntimeError("RelayAdapter has no transport configured")
self._transport.set_inbound_handler(self._on_inbound)
- # Inbound interrupts (connector -> owning gateway) arrive as
- # interrupt_inbound frames over the SAME outbound WS; bridge them to the
- # adapter's interrupt path. WS-only: there is no inbound HTTP receiver.
+ # Interrupts and passthrough-plane forwards (Discord interactions,
+ # Twilio, …) ride the SAME outbound WS — there is no inbound HTTP
+ # receiver, so a hosted gateway needs no public port.
set_interrupt = getattr(self._transport, "set_interrupt_inbound_handler", None)
if callable(set_interrupt):
set_interrupt(self.on_interrupt)
- # Passthrough-plane forwards (Discord interactions, Twilio, …) also ride
- # the SAME outbound WS (Phase 5 §5.1) — the connector edge-ACKed and
- # forwards the real request here, so a hosted gateway needs no public
- # inbound port. Bridge them to the adapter's passthrough handler.
set_passthrough = getattr(self._transport, "set_passthrough_handler", None)
if callable(set_passthrough):
set_passthrough(self._on_passthrough)
ok = await self._transport.connect()
if not ok:
return False
- # Negotiate the real capability descriptor from the connector and adopt
- # it — the placeholder passed at construction is replaced by what the
- # connector advertises for the platform this gateway actually fronts.
+ # Adopt the connector-advertised descriptor in place of the
+ # construction-time placeholder.
try:
descriptor = await self._transport.handshake()
except Exception as exc: # noqa: BLE001 - a failed handshake = a failed connect
logger.warning("relay handshake failed: %s", exc)
return False
self._apply_descriptor(descriptor)
- # Inbound (messages + interrupts) is delivered over the outbound WS via
- # the connector's relay bus — there is NO inbound HTTP endpoint (hosted
- # gateways have no public IP). The transport's reader already dispatches
- # `inbound` / `interrupt_inbound` frames to the handlers wired above.
- # Phase 7 Unit 7d-B: start watching for a terminal auth revocation
- # (opt-out). Only meaningful when the transport exposes `auth_revoked`
- # (the production WebSocket transport); the test/stub transports don't.
+ # Only the production WebSocket transport exposes `auth_revoked`.
if hasattr(self._transport, "auth_revoked"):
self._start_revocation_monitor()
return True
def _start_revocation_monitor(self) -> None:
- """Spawn (once) the task that turns a transport auth-revocation into a
+ """Spawn (once) the task turning a transport auth-revocation into a
clean non-retryable 'relay disabled' fatal. Idempotent."""
if self._revocation_monitor is not None and not self._revocation_monitor.done():
return
@@ -970,32 +751,22 @@ class RelayAdapter(BasePlatformAdapter):
self._watch_for_revocation(), name="relay-revocation-monitor"
)
except RuntimeError:
- # No running loop (e.g. a unit test calling connect() synchronously
- # via a stub) — nothing to monitor.
+ # No running loop (a unit test calling connect() via a stub).
self._revocation_monitor = None
async def _watch_for_revocation(self, poll_interval_s: float = 1.0) -> None:
- """Poll the transport for a terminal 4401 revocation (opt-out). On
- revocation, surface a non-retryable `relay_disabled` fatal so the
- dashboard renders a clean 'Relay disabled' state instead of a red
- 'retrying' spin, and notify the gateway's fatal-error handler so the
- adapter is cleanly removed (it is NOT queued for reconnection, because
- the credential is dead until the instance is recreated)."""
+ """Poll for a terminal 4401 revocation (opt-out); then surface a
+ non-retryable `relay_disabled` fatal so the adapter is cleanly removed
+ rather than queued for reconnection (the credential is dead until the
+ instance is recreated)."""
transport = self._transport
- try:
- while True:
- if transport is None or getattr(transport, "auth_revoked", False):
- break
- await asyncio.sleep(poll_interval_s)
- except asyncio.CancelledError:
- raise
- if transport is None or not getattr(transport, "auth_revoked", False):
+ if transport is None:
return
+ while not getattr(transport, "auth_revoked", False):
+ await asyncio.sleep(poll_interval_s)
logger.warning(
"relay credential revoked (opt-out) — marking the relay adapter disabled"
)
- # Non-retryable: a revoked secret never comes back without a recreate, so
- # _handle_adapter_fatal_error must NOT queue it for reconnection.
self._set_fatal_error(
"relay_disabled",
"Relay disabled (opted out — recreate the instance to re-enable)",
@@ -1011,24 +782,18 @@ class RelayAdapter(BasePlatformAdapter):
self.descriptor = descriptor
self.MAX_MESSAGE_LENGTH = descriptor.max_message_length
self.supports_code_blocks = descriptor.markdown_dialect not in ("", "plain")
- # Cron in_channel continuable surface (D6 gate in cron/scheduler.py):
- # the scheduler reads this off the adapter; the connector advertises it
- # per platform at handshake. Class default is False (BasePlatformAdapter),
- # so only an explicit descriptor bit turns the flat surface on.
+ # Cron in_channel continuable surface (D6 gate in cron/scheduler.py);
+ # class default is False, so only an explicit descriptor bit turns it on.
self.supports_inchannel_continuable = bool(
getattr(descriptor, "supports_inchannel_continuable", False)
)
async def _on_inbound(self, event) -> None:
"""Bridge a connector-delivered MessageEvent into the normal adapter path."""
- # Inbound replay dedupe (live-canary finding #3, Alice staging): the
- # relay leg is at-least-once — on WS re-handshake the connector
- # replays its durable per-instance buffer, and a long multi-tool turn
- # (60-100s) straddling a quiet socket drop gets its ORIGINAL inbound
- # replayed after the turn completes, re-running the whole turn (user
- # saw the final answer 2-5x). Platform message identity (chat_id +
- # message_id/ts) is stable across replays, so a bounded seen-set
- # drops them. Consumer-side idempotency; no wire change.
+ # Inbound replay dedupe: the relay leg is at-least-once — on WS
+ # re-handshake the connector replays its durable buffer, and a long
+ # turn straddling a quiet socket drop got re-run (final answer 2-5x).
+ # Platform message identity is stable across replays.
dedupe_key = self._inbound_dedupe_key(event)
if dedupe_key is not None:
if dedupe_key in self._seen_inbound:
@@ -1041,10 +806,9 @@ class RelayAdapter(BasePlatformAdapter):
self._seen_inbound.pop(next(iter(self._seen_inbound)))
self._capture_scope(event)
self._stamp_slack_session_thread(event)
- # Phase 3: a structured prompt answer resolves its waiting primitive
- # (approval/confirm/clarify) and is CONSUMED — it must not also
- # dispatch as a chat message. Unknown/expired prompt ids fall through
- # (the command-shaped text then behaves like a typed reply).
+ # A structured prompt answer resolves its waiting primitive and is
+ # CONSUMED — never also dispatched as chat. Unknown/expired ids fall
+ # through (command-shaped text then behaves like a typed reply).
if await self._consume_prompt_response(event):
return
await self._localize_inbound_media(event)
@@ -1055,28 +819,18 @@ class RelayAdapter(BasePlatformAdapter):
def _inbound_dedupe_key(self, event) -> Optional[str]:
"""Stable replay identity: (platform, chat, platform message id).
- Chat identity lives on ``event.source`` (MessageEvent has no top-level
- ``chat_id``), and this adapter can front SEVERAL platforms over one
- relay socket (Phase 1.5 multiplex), so the underlying platform joins
- the key — two platforms' numeric chat/message ids must never collide
- into one identity.
-
- Returns None when the event carries no platform message id (synthetic
- events, some prompt responses) — those never dedupe, fail-open by
- design: dropping a real user message is strictly worse than rerunning
- one, so only dedupe when identity is certain.
+ The platform joins the key because one relay socket can front several
+ platforms whose numeric ids may collide. Returns None when the event
+ carries no platform message id — those never dedupe (fail-open:
+ dropping a real message is worse than rerunning one).
"""
source = getattr(event, "source", None)
message_id = getattr(event, "message_id", None)
chat_id = getattr(source, "chat_id", None)
if not message_id or not chat_id:
return None
- # Normalize the platform component: production wire decoding always
- # yields a Platform enum (unknowns canonicalize to Platform.RELAY),
- # but alternate constructors may carry the plain string. Use the
- # enum's value when present, the string itself otherwise — both
- # spellings of one platform must produce ONE key, and two different
- # string platforms must not collapse into the same empty component.
+ # Enum value when present, plain string otherwise: both spellings of
+ # one platform must produce ONE key.
raw_platform = getattr(source, "platform", None)
platform = getattr(raw_platform, "value", raw_platform) or ""
return f"{platform}:{chat_id}:{message_id}"
@@ -1084,18 +838,10 @@ class RelayAdapter(BasePlatformAdapter):
def _relay_slack_extra(self) -> Dict[str, Any]:
"""The Slack-behavior subset of the RELAY platform config.
- Enterprise knob shape (Hermes-config directed, relay-namespaced):
-
- platforms:
- relay:
- extra:
- slack: # supported subset of native Slack fields
- reply_in_thread: true
-
- The native ``platforms.slack`` block keeps meaning "native adapter
- settings"; relay-fronted Slack reads its subset here. Legacy fallback:
- a flat key on the relay extra (``extra.reply_in_thread``) still wins
- when no ``slack`` object exists, preserving current staging configs.
+ ``platforms.relay.extra.slack.*`` (relay-namespaced mirror of the
+ native Slack knobs; ``platforms.slack`` keeps meaning native settings).
+ Legacy fallback: flat keys on the relay extra still win when no
+ ``slack`` object exists, preserving existing staging configs.
"""
extra = getattr(self.config, "extra", None) or {}
sub = extra.get("slack")
@@ -1105,113 +851,76 @@ class RelayAdapter(BasePlatformAdapter):
def _coerce_flag(raw: Any, default: bool) -> bool:
"""Coerce an operator-supplied boolean exactly as native Slack does.
- Native SlackAdapter reads its behavior flags with
- ``str(raw).strip().lower() in {"1","true","yes","on"}``, so a
- YAML-quoted ``"false"`` — a shape operators write routinely — turns
- the flag OFF. A bare ``bool()`` would read that same string as True
- (non-empty string), silently ignoring the off switch. These knobs are
- documented as native-parity mirrors, so they must coerce identically
- or the parity claim only holds for unquoted YAML booleans.
+ A YAML-quoted ``"false"`` must turn the flag OFF; a bare ``bool()``
+ would read that non-empty string as True and silently ignore the switch.
"""
if raw is None:
return default
if isinstance(raw, bool):
return raw
- return str(raw).strip().lower() in {"1", "true", "yes", "on"}
+ return str(raw).strip().lower() in _TRUTHY
- def _effective_reply_in_thread(self) -> bool:
- """Resolve the thread-per-message vs flat-DM mode for fronted Slack."""
+ def _slack_flag(self, knob: str, default: bool) -> bool:
+ """A coerced boolean knob from the relay Slack extra; ``default`` on any config-shape error."""
try:
- return self._coerce_flag(
- self._relay_slack_extra().get("reply_in_thread"), True
- )
+ return self._coerce_flag(self._relay_slack_extra().get(knob), default)
except Exception: # noqa: BLE001 - config shape is operator-owned
- return True
+ return default
+
+ def _effective_reply_in_thread(self) -> bool:
+ """Resolve the thread-per-message vs flat-DM mode for fronted Slack."""
+ return self._slack_flag("reply_in_thread", True)
def _dm_top_level_threads_as_sessions(self) -> bool:
"""Native-parity escape hatch: per-message DM sessions on/off.
- Mirrors native SlackAdapter._dm_top_level_threads_as_sessions
- (platforms.slack.extra.dm_top_level_threads_as_sessions). Default
- True: in thread-per-message mode each top-level DM message keys its
- own session (parallel turns). Set
- platforms.relay.extra.slack.dm_top_level_threads_as_sessions: false
- to keep threaded reply PLACEMENT but ONE rolling DM session — the
- legacy steer/queue posture, decoupled from reply_in_thread.
+ Default True: in thread-per-message mode each top-level DM message keys
+ its own session. False keeps threaded PLACEMENT but ONE rolling DM
+ session (the legacy steer/queue posture), decoupled from reply_in_thread.
"""
- try:
- return self._coerce_flag(
- self._relay_slack_extra().get("dm_top_level_threads_as_sessions"),
- True,
- )
- except Exception: # noqa: BLE001 - config shape is operator-owned
- return True
+ return self._slack_flag("dm_top_level_threads_as_sessions", True)
def _slack_unfurl_hints(self, platform: Optional[str]) -> Optional[Dict[str, bool]]:
- """Slack-only outbound link-preview suppression, relay-namespaced.
-
- Mirrors the native SlackAdapter's unfurl controls
- (``platforms.slack.extra.unfurl_links`` / ``unfurl_media``) but reads
- the relay namespace (``platforms.relay.extra.slack.*``) per the
- ``reply_in_thread`` seam: relay-fronted Slack reads its subset here;
- the native ``platforms.slack`` block keeps meaning native-adapter
- settings. Only explicitly-configured booleans are returned — omitted
- keys preserve Slack's default unfurling. Non-Slack platforms return
- None so the metadata is never polluted for other fronted platforms.
+ """Slack-only outbound link-preview knobs (``unfurl_links``/``unfurl_media``).
+
+ Reads the relay namespace like ``reply_in_thread``. Only explicitly
+ configured booleans are returned (omitted keys preserve Slack's
+ default); YAML strings ("true"/"false") are coerced, junk is dropped.
+ Non-Slack platforms return None so their metadata is never polluted.
"""
- if str(platform or "").lower() != Platform.SLACK.value:
+ if str(platform or "").lower() != _SLACK:
return None
extra = self._relay_slack_extra()
hints: Dict[str, bool] = {}
for knob in ("unfurl_links", "unfurl_media"):
val = extra.get(knob)
- if val is None:
- continue
- # Railway / `hermes config set` write YAML strings ("true"/"false").
- # A Slack bot that omits the fields does NOT get human-default
- # previews — so a string "true" that we drop looks like
- # suppression. Coerce the same way as reply_in_thread; still drop
- # junk (empty, 0, "maybe") so omitted stays omitted.
if isinstance(val, bool):
hints[knob] = val
- continue
- if isinstance(val, str) and val.strip().lower() in {
- "1",
- "0",
- "true",
- "false",
- "yes",
- "no",
- "on",
- "off",
- }:
- hints[knob] = val.strip().lower() in {"1", "true", "yes", "on"}
+ elif isinstance(val, str) and val.strip().lower() in (_TRUTHY | _FALSY):
+ hints[knob] = val.strip().lower() in _TRUTHY
return hints or None
+ def _stamp_slack_unfurl(self, platform: Optional[str], metadata: Dict[str, Any]) -> None:
+ unfurl = self._slack_unfurl_hints(platform)
+ if unfurl:
+ metadata.update(unfurl)
+
def _stamp_slack_session_thread(self, event) -> None:
"""Native session-keying parity for fronted Slack DMs.
- Native SlackAdapter's inbound handler stamps ``thread_ts =
- event.thread_ts or ts`` — every TOP-LEVEL message carries its own ts
- as ``source.thread_id``, so build_session_key appends it and each
- top-level message gets a FRESH session (per-message threads ⇒
- per-message sessions; a 2nd message runs parallel instead of steering
- the in-flight turn). The connector normalizes a top-level message
- with thread_id=null, so without this stamp every top-level DM
- collapses into ONE session key and message 2 pre-empts message 1
- ("Redirected current run", 2026-07-27 report).
-
- Only in thread-per-message mode: flat mode keeps the shared rolling
- DM session on purpose (steer/queue there is the intended UX). Never
- overwrites a real thread_id (an in-thread reply must keep resolving
- to its thread's session).
+ Native Slack stamps ``thread_ts = event.thread_ts or ts``, so each
+ TOP-LEVEL message keys a FRESH session (parallel turns). The connector
+ normalizes top-level messages with thread_id=null, so without this every
+ top-level DM collapsed into ONE session and message 2 pre-empted
+ message 1. Only in thread-per-message mode (flat mode keeps the shared
+ rolling session on purpose); never overwrites a real thread_id.
"""
try:
src = getattr(event, "source", None)
if not src:
return
platform = getattr(src, "platform", None)
- if getattr(platform, "value", platform) != Platform.SLACK.value:
+ if getattr(platform, "value", platform) != _SLACK:
return
if getattr(src, "thread_id", None):
return # real thread — its session key is already correct
@@ -1231,27 +940,19 @@ class RelayAdapter(BasePlatformAdapter):
async def _localize_inbound_media(self, event) -> None:
"""Download connector re-hosted attachments to local temp paths.
- The wire's ``media_urls`` name connector re-hosts
- (``{connector}/relay/media/{id}``, per-gateway-bearer-authenticated) or
- public platform CDN URLs (Discord pass-through). Every NATIVE adapter
- presents inbound media to the agent as LOCAL FILE PATHS (the vision /
- file tools consume paths, and an authenticated URL would be useless in
- the agent's context anyway) — so mirror that here: fetch each URL and
- swap the list entries for temp paths. Best-effort per entry: a failed
- download drops that entry (never the message); no client ⇒ only
- re-host URLs are dropped (they'd 401 for every consumer downstream),
- public URLs stay.
+ Every NATIVE adapter presents inbound media as LOCAL FILE PATHS (the
+ vision/file tools consume paths), so mirror that. Best-effort per
+ entry: a failed download drops that entry, never the message; with no
+ client only re-host URLs are dropped (they'd 401 downstream), public
+ URLs stay.
"""
try:
urls = list(getattr(event, "media_urls", None) or [])
if not urls:
return
# media_types is INDEXED IN PARALLEL with media_urls by every
- # downstream classifier (_event_media_type_at). Any URL we drop or
- # rewrite here must carry its MIME with it, or the surviving
- # attachments inherit a neighbour's type and get mis-routed (an
- # image classified by a PDF's mime is not treated as an image).
- # Carry (url, mime) as PAIRS through the whole loop.
+ # downstream classifier: carry (url, mime) PAIRS through the loop
+ # or surviving attachments inherit a neighbour's type.
types = list(getattr(event, "media_types", None) or [])
pairs = [
(u, types[i] if i < len(types) else "") for i, u in enumerate(urls)
@@ -1262,7 +963,6 @@ class RelayAdapter(BasePlatformAdapter):
if not isinstance(url, str) or not url:
continue
if client is None:
- # No authenticated client: keep public URLs, drop re-hosts.
if "/relay/media/" not in url:
localized.append((url, mime))
continue
@@ -1270,14 +970,9 @@ class RelayAdapter(BasePlatformAdapter):
if path:
localized.append((path, mime))
elif "/relay/media/" not in url:
- # A public URL that failed to download still has value as
- # a URL (native adapters pass URLs to vision in some
- # lanes); a dead re-host reference does not.
+ # A public URL still has value as a URL; a dead re-host does not.
localized.append((url, mime))
event.media_urls = [u for u, _ in localized]
- # Keep the parallel-array invariant: one mime slot per surviving
- # url, always. A short/stale media_types would shift entries onto
- # the wrong url the moment anything indexes or merges them.
event.media_types = [m for _, m in localized]
except Exception: # noqa: BLE001 - media localization must never break inbound
logger.debug("relay inbound media localization failed", exc_info=True)
@@ -1285,43 +980,24 @@ class RelayAdapter(BasePlatformAdapter):
def prime_routing_cache(self, event) -> None:
"""Warm the per-chat egress routing caches from a SYNTHETIC event.
- The caches (_scope_by_chat/_dm_user_by_chat/...) are normally warmed
- only by the inbound path (_on_inbound -> _capture_scope). A synthetic
- completion turn injected right after a restart (durable
+ A synthetic completion turn injected right after a restart (durable
async-delegation replay) reaches handle_message with the caches COLD,
- so every reply it produces egresses without metadata.scope_id /
- metadata.user_id and is declined by the connector's fail-closed
- tenant guard ("target not routed to an onboarded tenant" — staging
- 2026-08-09, defect #4). The synthetic event's session-store origin
- already carries the discriminators; feed it through the same capture
- used for real inbound. Never raises.
+ so its replies egress without scope_id/user_id and the connector's
+ fail-closed tenant guard declines them. Never raises.
"""
if event is None or getattr(event, "source", None) is None:
return
self._capture_scope(event)
def _capture_scope(self, event) -> None:
- """Remember a chat_id's egress discriminator from an inbound event so our
- outbound (the agent's reply) can re-assert it for the connector's egress
- tenant resolution. Never raises — scope tracking must not break inbound.
-
- Two discriminators, captured independently (a scoped message has BOTH):
- - scope_id: for a scoped (guild/channel) message. The connector's
- primary path resolves the tenant from metadata.scope_id (routing
- table).
- - user_id: the authentic author id, captured for EVERY message (DM
- and scoped alike). The connector resolves the tenant from the
- recipient's author binding (resolveByUser) when a route lookup
- misses. This is the sole discriminator for a DM (no scope), AND the
- author-first FALLBACK for a scoped reply whose guild has no route
- row — a managed agent joins guilds dynamically, so a provision-time
- guild route is not guaranteed. Re-attaching user_id on scoped
- replies too lets the connector's guild-route-miss fallback resolve
- the tenant the same way inbound already does (SharedSocketRouter
- targets()). Without a resolvable discriminator the connector's
- egress guard declines the reply as 'target not routed to an
- onboarded tenant'. See gateway-gateway routedEgressGuard.ts /
- discordTenant.ts (makeDiscordTenantOf).
+ """Remember a chat's egress discriminators from an inbound event. Never raises.
+
+ - scope_id: scoped (guild/channel) message → routing-table resolution.
+ - user_id: authentic author id, captured for EVERY message. Sole
+ discriminator for a DM AND the author-first fallback for a scoped
+ reply whose guild has no route row (managed agents join guilds
+ dynamically). Without a resolvable discriminator the connector
+ declines egress as 'target not routed to an onboarded tenant'.
"""
try:
src = getattr(event, "source", None)
@@ -1330,43 +1006,23 @@ class RelayAdapter(BasePlatformAdapter):
chat = getattr(src, "chat_id", None)
if not chat:
return
- # Phase 1.5: remember the underlying platform for this chat so the
- # reply egresses through the right sender (one relay adapter fronts N
- # platforms). source.platform is a Platform enum (e.g. Platform.DISCORD,
- # mapped from the connector's "discord" by ws_transport _frame_to_event);
- # record its string VALUE, skipping the generic RELAY fallback (a
- # single-platform connector that didn't tag a concrete platform — the
- # connector's session default handles egress then).
+ # Underlying platform's string VALUE, skipping the generic RELAY
+ # fallback (the connector's session default handles egress then).
platform = getattr(src, "platform", None)
platform_value = getattr(platform, "value", platform)
if platform_value and platform_value != "relay":
self._platform_by_chat[str(chat)] = str(platform_value)
- # Author id for outbound author-binding resolution. Captured for BOTH
- # DM and scoped messages: it's the sole discriminator for a DM and
- # the guild-route-miss fallback for a scoped reply. (Formerly captured
- # for DMs only, which left managed-agent guild replies with no
- # resolvable tenant when the guild had no route row.)
user_id = getattr(src, "user_id", None)
if user_id:
self._dm_user_by_chat[str(chat)] = str(user_id)
scope = getattr(src, "scope_id", None)
if scope:
self._scope_by_chat[str(chat)] = str(scope)
- # Remember the chat_type so send() can suppress the synthetic-DM
- # thread anchor on Slack (native _resolve_thread_ts parity). send()
- # only receives a chat_id, so it needs this per-chat cache to know a
- # chat is a DM.
chat_type = getattr(src, "chat_type", None)
if chat_type:
self._chat_type_by_chat[str(chat)] = str(chat_type)
- # Triggering message ts: the typing/status lane's metadata
- # (base.py _thread_metadata_for_source) carries NO thread anchor
- # for a top-level DM, but in thread-per-message mode the status
- # must target the per-message thread (its root = this ts). Cache
- # it per chat so send_typing can synthesize the anchor, mirroring
- # native send_typing's _resolve_thread_ts(metadata.message_id).
- # NOTE: message_id lives on the EVENT (MessageEvent), not the
- # source — fall back to source for defensive coverage.
+ # Triggering message ts for the typing/status lane's synthetic
+ # thread anchor (message_id lives on the EVENT; source is a fallback).
message_id = getattr(event, "message_id", None) or getattr(
src, "message_id", None
)
@@ -1378,34 +1034,17 @@ class RelayAdapter(BasePlatformAdapter):
def _with_scope(
self, chat_id: str, metadata: Optional[Dict[str, Any]]
) -> Dict[str, Any]:
- """Ensure the outbound metadata carries the discriminator(s) the connector's
- egress guard needs to resolve the owning tenant.
-
- - scope_id: re-attached for a scoped reply (guild/channel) →
- routing-table resolution (the primary path).
- - user_id: the authentic author id we saw inbound, re-attached for
- EVERY reply we know it for. It is the sole discriminator for a DM
- (no scope), AND the author-first FALLBACK the connector uses when a
- scoped reply's guild has no route row (a managed agent joins guilds
- dynamically — the guild route may not be provisioned). Carrying both
- on a scoped reply is harmless: the connector tries scope_id first and
- only falls back to user_id on a route miss. Without a resolvable
- discriminator egress is declined as 'target not routed to an
- onboarded tenant'. See gateway-gateway routedEgressGuard.ts /
- discordTenant.ts.
-
- No-op when the relevant value is already present or unknown for this chat.
+ """Outbound metadata carrying the tenant discriminators (see _capture_scope).
+
+ Both scope_id and user_id are attached when known and not already set;
+ the connector tries scope_id first and only falls back to user_id on a
+ route miss, so carrying both never overrides routing-table resolution.
"""
meta: Dict[str, Any] = dict(metadata or {})
if not meta.get("scope_id"):
scope = self._scope_by_chat.get(str(chat_id))
if scope:
meta["scope_id"] = scope
- # Author-binding discriminator. Attached whenever we know the author for
- # this chat and it isn't already set — for DMs (the sole discriminator)
- # AND scoped replies (the connector's guild-route-miss fallback). It is
- # only consulted by the connector when the scope/route lookup misses, so
- # carrying it alongside scope_id never overrides routing-table resolution.
if not meta.get("user_id"):
author = self._dm_user_by_chat.get(str(chat_id))
if author:
@@ -1415,9 +1054,8 @@ class RelayAdapter(BasePlatformAdapter):
def fronts_platform(self, platform: Any) -> bool:
"""Whether the authenticated relay transport advertises ``platform``.
- This is the restart-safe delivery ownership signal: it comes from the
- configured identity set sent during handshake, not from an inbound
- chat cache learned only after a user sends another message.
+ Restart-safe delivery ownership signal: comes from the identity set
+ sent at handshake, not from an inbound chat cache.
"""
platform_value = getattr(platform, "value", platform)
if not platform_value:
@@ -1427,78 +1065,32 @@ class RelayAdapter(BasePlatformAdapter):
return False
return any(p == str(platform_value) for p, _ in ids)
- def _platform_is_fronted(self, platform: str) -> bool:
- """Backward-compatible internal alias for follow-up routing."""
- return self.fronts_platform(platform)
-
def supports_inchannel_continuable_for_platform(self, platform: Any) -> bool:
- """Whether ONE fronted logical platform can host the flat continuable
- cron surface (the D6 gate in cron/scheduler.py).
-
- The scalar ``supports_inchannel_continuable`` carries only the PRIMARY
- identity's bit, but one RelayAdapter fronts N platforms and the
- connector advertises the capability per platform at handshake. On a
- multi-platform relay the scalar both leaks the primary's True onto
- platforms whose own descriptor never advertised it and suppresses a
- non-primary platform's advertised True. Resolve the platform's own
- negotiated descriptor off the transport; fall back to the scalar only
- when the per-platform descriptor is unavailable (single-platform
- transport, or a transport predating descriptor_for_platform).
- """
- platform_value = str(getattr(platform, "value", platform) or "")
- if platform_value and self._transport is not None:
- resolve = getattr(self._transport, "descriptor_for_platform", None)
- if callable(resolve):
- try:
- per_platform = resolve(platform_value)
- except Exception: # noqa: BLE001 - capability lookup must never break delivery
- per_platform = None
- if per_platform is not None:
- return bool(
- getattr(
- per_platform, "supports_inchannel_continuable", False
- )
- )
+ """Whether ONE fronted platform can host the flat continuable cron
+ surface (D6 gate). The scalar bit is the PRIMARY's only, so resolve the
+ platform's own negotiated descriptor; fall back to the scalar when
+ unavailable."""
+ per_platform = self._negotiated_descriptor(
+ str(getattr(platform, "value", platform) or "")
+ )
+ if per_platform is not None:
+ return bool(getattr(per_platform, "supports_inchannel_continuable", False))
return bool(self.supports_inchannel_continuable)
async def on_interrupt(self, session_key: str, chat_id: str) -> None:
- """Bridge a connector-delivered /stop into the adapter's interrupt path.
-
- The connector forwards a mid-turn interrupt down the socket owned by
- the gateway instance running ``session_key``; this routes it to the
- existing per-session interrupt mechanism (sets the
- ``_active_sessions[session_key]`` Event and clears typing), cancelling
- the right turn without touching sibling sessions.
- """
+ """Bridge a connector-delivered /stop into the per-session interrupt path."""
await self.interrupt_session_activity(session_key, chat_id)
async def _on_passthrough(self, forward, buffer_id: Optional[str] = None) -> None:
- """Handle a connector-forwarded passthrough request (Phase 5 §5.1).
-
- The passthrough plane (Discord interactions, Twilio webhooks, …) answers
- the provider's latency-critical ACK at the connector EDGE, then forwards
- the real, ALREADY-SANITIZED request to this gateway over the outbound WS.
- The connector is the trust boundary: it verified the provider signature
- at the edge and stripped any shared-identity credential (e.g. a Discord
- interaction follow-up token) into its vault — so this body carries no
- token, and the agent later acts on it via the token-less ``follow_up``
- path (``send_follow_up``), never holding the credential.
-
- For a Discord interaction we decode the (JSON) body and convert it to a
- normalized ``MessageEvent`` so it flows through the SAME agent path as a
- chat message (``handle_message``); the agent's reply egresses over the
- normal outbound/follow_up path. Non-JSON or non-interaction forwards are
- logged and dropped for now (Twilio/SMS over the relay is a later unit).
-
- NEVER raises: a malformed forward must not kill the read loop.
-
- Interaction -> MessageEvent command mapping (formerly flagged here as an
- open sub-design, now implemented): an APPLICATION_COMMAND interaction is
- normalized to a leading-slash COMMAND event ("/name arg…", mirroring the
- connector's Slack slash-command lane, normalizeSlackCommand), so the
- dispatcher routes it as a command instead of plain chat. Component
- interactions (custom_id) still surface as best-effort TEXT; the
- deferred-vs-immediate response UX remains connector-side.
+ """Handle a connector-forwarded passthrough request.
+
+ The connector answered the provider's latency-critical ACK at the
+ edge, verified the signature and stripped any shared-identity
+ credential into its vault; the agent later acts via the token-less
+ ``send_follow_up`` path. A Discord interaction becomes a normalized
+ ``MessageEvent`` on the SAME agent path as chat; other forwards are
+ logged and dropped. NEVER raises: a malformed forward must not kill
+ the read loop.
"""
try:
platform = getattr(forward, "platform", "") or ""
@@ -1506,9 +1098,8 @@ class RelayAdapter(BasePlatformAdapter):
event = self._discord_interaction_to_event(forward)
if event is not None:
self._capture_scope(event)
- # Phase 3: a component press carrying a Hermes prompt token
- # resolves its waiting primitive and is consumed (same
- # gate as _on_inbound's prompt_response arm).
+ # A component press carrying a Hermes prompt token resolves
+ # its waiting primitive and is consumed (same gate as _on_inbound).
if await self._consume_prompt_response(event):
return
await self.handle_message(event)
@@ -1525,37 +1116,24 @@ class RelayAdapter(BasePlatformAdapter):
def _discord_interaction_to_event(self, forward):
"""Convert a forwarded Discord interaction body to a MessageEvent, or None.
- Builds the session source the same way the connector does for an
- interaction (``interactionSessionSource`` on the connector side), so the
- agent's session key matches the one the connector bound the follow-up
- capability under. Returns None when the body isn't a usable interaction
- (e.g. a PING, which the connector already answers at the edge and never
- forwards).
+ The session source is built the way the connector builds it for an
+ interaction (``interactionSessionSource``) so the session key matches
+ the one the follow-up capability was bound under. None for an unusable
+ body (a PING is answered at the edge and never forwarded).
"""
- import json
-
- from gateway.platforms.base import MessageType
-
try:
payload = json.loads(bytes(getattr(forward, "body", b"")).decode("utf-8"))
except Exception: # noqa: BLE001
return None
if not isinstance(payload, dict):
return None
- # type 1 = PING (answered at the edge, never forwarded); 2 = APPLICATION_COMMAND;
- # 3 = MESSAGE_COMPONENT; 5 = MODAL_SUBMIT. Surface a best-effort text.
+ # type 2 = APPLICATION_COMMAND; 3 = MESSAGE_COMPONENT; 5 = MODAL_SUBMIT.
itype = payload.get("type")
data = payload.get("data") or {}
message_type = MessageType.TEXT
if itype == 2:
- # Normalize a real slash-command interaction to a leading-slash
- # command string — the shape the dispatcher (MessageEvent.is_command:
- # text.startswith("/")) and the native Discord adapter's
- # _run_simple_slash lane (f"/model {name}".strip()) both expect.
- # Options render space-separated: scalar options contribute their
- # value; SUB_COMMAND/SUB_COMMAND_GROUP (types 1/2) contribute their
- # name then their nested options. Mirrors the connector's Slack
- # slash lane (normalizeSlackCommand: `${command} ${args}`.trim()).
+ # Normalize to a leading-slash command string ("/name arg…"), the
+ # shape the dispatcher and the connector's Slack slash lane expect.
text = ("/" + str(data.get("name") or "")).rstrip("/") or ""
if text:
parts = [text] + self._render_interaction_options(data.get("options"))
@@ -1572,32 +1150,16 @@ class RelayAdapter(BasePlatformAdapter):
or {}
)
channel_id = str(payload.get("channel_id") or "")
- guild_id = payload.get("guild_id") # real Discord interaction wire field
+ guild_id = payload.get("guild_id")
source = SessionSource(
- # The LOGICAL platform, not Platform.RELAY. This lane parses a
- # Discord interaction wire payload, so the underlying platform is
- # known statically — and it must be stamped for three consumers:
- # 1. Session keys: the connector binds the interaction's
- # follow-up capability under buildSessionKey with
- # platform="discord" (interactionSessionSource); the relay
- # TEXT lane (ws_transport._event_from_wire) also maps to the
- # logical platform. RELAY here forked interaction sessions
- # away from both.
- # 2. /sethome: with platform=RELAY the handler filed the home
- # channel under platforms.relay.home_channel (invisible to
- # cron delivery, which looks up the logical platform) and
- # mirrored it into the dead RELAY_HOME_CHANNEL env var.
- # 3. Egress: _capture_scope records _platform_by_chat from this
- # value and deliberately skips the generic "relay".
+ # The LOGICAL platform, not RELAY: session keys must match the
+ # connector's capability binding (platform="discord"), /sethome
+ # must file under the logical platform, and _capture_scope skips
+ # the generic "relay" for egress routing.
platform=Platform.DISCORD,
chat_id=channel_id,
- # "group", not "channel": the session key embeds chat_type, and
- # BOTH the connector's capability binding (interactionSessionSource
- # → buildSessionKey, chat_type "group") and the native Discord
- # adapter's channel events key guild channels as "group". A
- # "channel" slot here forked the interaction session from the
- # chat's message session AND from the vault key the connector
- # bound the follow-up capability under.
+ # "group", not "channel": both the connector's capability binding
+ # and the native Discord adapter key guild channels as "group".
chat_type="group" if guild_id else "dm",
user_id=str(user.get("id"))
if isinstance(user, dict) and user.get("id")
@@ -1605,35 +1167,20 @@ class RelayAdapter(BasePlatformAdapter):
user_name=str(user.get("username"))
if isinstance(user, dict) and user.get("username")
else None,
- scope_id=str(guild_id)
- if guild_id
- else None, # Discord guild → generic scope slot
+ scope_id=str(guild_id) if guild_id else None,
message_id=str(payload.get("id")) if payload.get("id") else None,
- # Same upstream-trust marker the relay text lane stamps
- # (ws_transport._event_from_wire): this interaction arrived over
- # the per-instance-authenticated relay WS after the connector
- # verified Discord's edge signature and resolved the tenant.
- # Without it, authz treated the event as unauthenticated relay
- # traffic — and /sethome's via_relay guard never engaged, which is
- # how platform=RELAY home channels slipped through in the first
- # place. Set locally, never read off the wire.
+ # Same upstream-trust marker the relay text lane stamps: arrived
+ # over the authenticated relay WS after edge verification. Set
+ # locally, never read off the wire (engages /sethome's via_relay guard).
delivered_via_upstream_relay=True,
- # The HERMES profile this interaction is routed to (multiplex
- # mode) — mirrors _event_from_wire's profile stamping for plain
- # relayed messages (#60586). Without this, a Team-Gateway's
- # Discord slash-command/button/modal always fell back to the
- # legacy agent:main namespace even when the connector resolved
- # a specific profile for it.
+ # Profile routing (multiplex mode), mirroring _event_from_wire.
profile=getattr(forward, "profile", None),
)
event = MessageEvent(text=text, message_type=message_type, source=source)
if itype == 3:
- # Phase 3: a component press whose custom_id is a Hermes prompt
- # token (hp1:<prompt_id>:<option_id>) becomes a STRUCTURED prompt
- # answer — _on_inbound's _consume_prompt_response then resolves
- # the waiting approval/confirm/clarify, replacing the bare-
- # custom_id-as-text stub. Foreign custom_ids keep the legacy
- # best-effort TEXT shape.
+ # A component press whose custom_id is a Hermes prompt token
+ # (hp1:<prompt_id>:<option_id>) becomes a STRUCTURED prompt answer;
+ # foreign custom_ids keep the best-effort TEXT shape.
decoded = self._decode_prompt_token(text)
if decoded:
prompt_id, option_id = decoded
@@ -1654,21 +1201,13 @@ class RelayAdapter(BasePlatformAdapter):
@staticmethod
def _decode_prompt_token(token: str):
- """Decode an hp1:<prompt_id>:<option_id> callback token, or None.
-
- Mirrors the connector's promptCodec.decodePromptCallback (the token
- alphabet is [A-Za-z0-9_.-], ≤32 per id) so both ends agree on what is
- — and is not — a Hermes prompt answer.
- """
- import re
-
+ """Decode an hp1:<prompt_id>:<option_id> callback token, or None (mirrors the connector's promptCodec)."""
if not token:
return None
parts = token.split(":")
if len(parts) != 3 or parts[0] != "hp1":
return None
- id_re = re.compile(r"^[A-Za-z0-9_.\-]{1,32}$")
- if not id_re.match(parts[1]) or not id_re.match(parts[2]):
+ if not _PROMPT_ID_RE.match(parts[1]) or not _PROMPT_ID_RE.match(parts[2]):
return None
return parts[1], parts[2]
@@ -1676,13 +1215,9 @@ class RelayAdapter(BasePlatformAdapter):
def _render_interaction_options(options) -> list:
"""Render Discord interaction options to space-separated text parts.
- Discord's `data.options` is a list of {name, value, type}. Scalar
- options (STRING/INTEGER/BOOLEAN/…) contribute just their value —
- matching the native adapter's `f"/model {name}".strip()` shape, where
- only the value follows the command. SUB_COMMAND (1) and
- SUB_COMMAND_GROUP (2) contribute their *name* then recurse into their
- nested `options` list (one level of nesting per Discord's schema:
- group -> subcommand -> scalars).
+ Scalar options contribute just their value (native ``f"/model {name}"``
+ shape); SUB_COMMAND (1) / SUB_COMMAND_GROUP (2) contribute their name
+ then recurse into their nested options.
"""
parts: list = []
if not isinstance(options, list):
@@ -1690,7 +1225,7 @@ class RelayAdapter(BasePlatformAdapter):
for opt in options:
if not isinstance(opt, dict):
continue
- if opt.get("type") in (1, 2): # SUB_COMMAND / SUB_COMMAND_GROUP
+ if opt.get("type") in (1, 2):
sub_name = str(opt.get("name") or "").strip()
if sub_name:
parts.append(sub_name)
@@ -1704,19 +1239,16 @@ class RelayAdapter(BasePlatformAdapter):
return parts
async def disconnect(self) -> None:
- # Budget accounting: the runner wraps this whole call in
- # asyncio.wait_for(_adapter_disconnect_timeout_secs()). Everything we
- # spend on monitor teardown and go_idle below eats into what the
- # transport can spend on its outbound drain, so measure from the top
- # and thread the REMAINDER down — otherwise worst-case
- # monitor(1s) + go_idle(2s) + drain + 3×teardown(1s) can blow the 5s
- # budget, cancelling teardown mid-drain and skipping the transport's
- # fail-pending loop (callers then block on _OUTBOUND_TIMEOUT_S).
+ # The runner wraps this call in wait_for(adapter disconnect budget).
+ # Monitor teardown and go_idle eat into the transport's drain time, so
+ # measure from the top and thread the REMAINDER down — otherwise
+ # teardown is cancelled mid-drain and the transport's fail-pending
+ # loop is skipped (callers then block on _OUTBOUND_TIMEOUT_S).
from gateway.relay.ws_transport import _env_disconnect_budget_s
_started = time.monotonic()
_budget = _env_disconnect_budget_s()
- # Phase 7 Unit 7d-B: stop the revocation monitor first so it can't fire a
- # spurious fatal during/after a deliberate teardown.
+ # Stop the revocation monitor first so it can't fire a spurious fatal
+ # during/after a deliberate teardown.
if self._revocation_monitor is not None:
self._revocation_monitor.cancel()
try:
@@ -1728,21 +1260,14 @@ class RelayAdapter(BasePlatformAdapter):
pass
self._revocation_monitor = None
if self._transport is not None:
- # Phase 5 §5.3: emit going_idle as part of the gateway's EXISTING
- # drain/shutdown transition (the runner calls adapter.disconnect()
- # when the gateway enters `draining`). Asking the connector to flip
- # this instance to buffered-only BEFORE we tear down the socket means
- # inbound that arrives while we're asleep buffers durably and replays
- # on reconnect, instead of being pushed at a closing socket. The
- # connector is authoritative (it acks the flip); we stay serving until
- # the ack (Q-5.3c). Best-effort + guarded: a transport without go_idle
- # (the stub) or a failed/timed-out ack must not block shutdown — we
- # proceed to disconnect exactly as before, no regression.
+ # Ask the connector to flip this instance to buffered-only BEFORE
+ # tearing down the socket, so inbound arriving while asleep buffers
+ # durably and replays on reconnect. Best-effort: a transport
+ # without go_idle (the stub) or a failed ack must not block shutdown.
#
# transport.disconnect() runs in finally so an outer cancellation
- # during go_idle (runner default adapter budget is 5s) still closes
- # the socket/supervisor instead of leaking them. shield() keeps the
- # teardown await itself from being cancelled mid-flight.
+ # during go_idle still closes the socket/supervisor; shield() keeps
+ # the teardown await itself from being cancelled mid-flight.
try:
go_idle = getattr(self._transport, "go_idle", None)
if callable(go_idle):
@@ -1760,12 +1285,9 @@ class RelayAdapter(BasePlatformAdapter):
try:
_remaining = max(0.0, _budget - (time.monotonic() - _started))
try:
- _td = cast(Any, self._transport).disconnect(
- budget_s=_remaining
- )
+ _td = self._transport.disconnect(budget_s=_remaining) # type: ignore[call-arg]
except TypeError:
- # Transports without the budget_s keyword (stubs,
- # older implementations) keep the legacy signature.
+ # Transports without the budget_s keyword (stubs).
_td = self._transport.disconnect()
await asyncio.shield(_td)
except Exception: # noqa: BLE001 - teardown must not block outer cancel propagation
@@ -1775,17 +1297,12 @@ class RelayAdapter(BasePlatformAdapter):
)
async def go_dormant(self) -> bool:
- """Quiesce the relay for a scale-to-zero suspend (D12 / Phase 0).
-
- Unlike ``disconnect()`` (terminal teardown for shutdown/restart), this
- keeps the adapter's reconnect path armed so the gateway re-dials and
- drains its buffered backlog when the machine wakes. Delegates to the
- transport's ``go_dormant()`` when available; a transport without it (the
- stub) is a no-op that returns False, so callers degrade safely.
+ """Quiesce the relay for a scale-to-zero suspend.
- NOTE: deliberately does NOT stop the revocation monitor — going dormant
- is not a teardown; the monitor stays live so a real opt-out/revocation
- during dormancy is still surfaced on wake.
+ Unlike ``disconnect()`` this keeps the reconnect path armed so the
+ gateway re-dials and drains its backlog on wake. A transport without
+ ``go_dormant`` (the stub) is a no-op returning False. Deliberately
+ does NOT stop the revocation monitor — dormancy is not a teardown.
"""
if self._transport is None:
return False
@@ -1812,9 +1329,8 @@ class RelayAdapter(BasePlatformAdapter):
"""Send to an explicitly advertised logical platform over Relay.
Scheduled and persisted-home deliveries have no fresh inbound event to
- populate ``_platform_by_chat``. The shared delivery resolver calls this
- method only after ``fronts_platform`` succeeds, and this method repeats
- that check fail-closed before stamping the outbound frame.
+ populate ``_platform_by_chat``. The delivery resolver calls this only
+ after ``fronts_platform`` succeeds; repeated here fail-closed.
"""
platform_value = getattr(logical_platform, "value", logical_platform)
if not self.fronts_platform(platform_value):
@@ -1823,46 +1339,24 @@ class RelayAdapter(BasePlatformAdapter):
error=f"relay does not front platform {platform_value}",
)
_sfp_metadata = dict(metadata or {})
- # Gateway-internal interim marker (see send()): strip before the
- # wire; an interim send through this door also skips interception.
+ # Gateway-internal interim marker (see send()): strip before the wire.
_interim = bool(_sfp_metadata.pop("_interim_send", False))
- # Finding #7 (live canary): the delivery resolver calls THIS method
- # directly (gateway/delivery.py), bypassing send() — an open native
- # stream must absorb the turn-final here too, or the stream is left
- # unsealed (frozen live indicator) and the final posts as a separate
- # duplicate message.
- if not _interim:
- _sfp_key = self._match_open_draft(str(chat_id), _sfp_metadata)
- else:
- _sfp_key = None
- if _sfp_key is not None:
- seal = await self._seal_open_draft(
- chat_id, content, _sfp_metadata, draft_key=_sfp_key
- )
- if seal.success:
- return seal
- # Failed seal falls through to the plain send below (review
- # finding, PR 85796 point 1): never swallow the turn-final.
- logger.warning(
- "relay seal failed (%s); delivering turn-final as plain send",
- seal.error,
- )
+ # The delivery resolver calls THIS method directly, bypassing send()
+ # — an open native stream must absorb the turn-final here too.
+ seal = await self._absorb_into_open_draft(chat_id, content, _sfp_metadata, _interim)
+ if seal is not None:
+ return seal
if self._transport is None:
return SendResult(success=False, error="no transport")
- _sfp_unfurl = self._slack_unfurl_hints(str(platform_value))
- if _sfp_unfurl:
- _sfp_metadata.update(_sfp_unfurl)
+ self._stamp_slack_unfurl(str(platform_value), _sfp_metadata)
result = await self._transport.send_outbound(
{
"op": "send",
"chat_id": chat_id,
"content": content,
"reply_to": reply_to,
- # format_hints on the explicit-platform lane too: this is the
- # scheduled/cron delivery path — the in_channel brief itself —
- # and it must render blocks exactly like an interactive send.
- # Stamps _sfp_metadata (the interim-marker-stripped copy, per
- # the seal path above), composing both sides of the merge.
+ # format_hints on the explicit-platform lane too: the cron
+ # brief must render blocks exactly like an interactive send.
"metadata": self._with_scope(
chat_id,
self._with_format_hints_for_platform(
@@ -1884,25 +1378,15 @@ class RelayAdapter(BasePlatformAdapter):
) -> Optional[Dict[str, bool]]:
"""Block-formatting hints for one outbound text frame, or None.
- Native Slack reads ``platforms.slack.extra.rich_blocks`` /
- ``markdown_blocks`` and renders Block Kit locally; on the relay lane
- the CONNECTOR owns the platform API call, so the gateway can only
- signal intent. Hints are stamped ONLY when (a) the DESTINATION
- platform's negotiated descriptor advertises
- ``supports_block_formatting`` — an old connector never receives dead
- metadata — and (b) the operator enabled at least one knob under the
- relay's per-logical-platform sub-block
- (``platforms.relay.extra.<platform>.rich_blocks`` /
- ``markdown_blocks``, same seam and same _coerce_flag semantics as
- reply_in_thread). Both knobs default OFF, matching native's opt-in
- posture.
-
- ``descriptor``/``platform`` are the DESTINATION's, not the adapter's
- scalar primary identity: one RelayAdapter fronts N platforms, and
- gating on the primary descriptor both leaked hints onto platforms
- that never advertised the bit (Slack-primary, Discord chat) and
- suppressed them for platforms that did (Discord-primary, Slack chat).
- Same seam as ``_descriptor_for_chat`` / max_message_length.
+ On the relay lane the CONNECTOR owns the platform API call, so the
+ gateway only signals intent. Stamped ONLY when (a) the DESTINATION
+ platform's negotiated descriptor advertises ``supports_block_formatting``
+ (an old connector never receives dead metadata) and (b) the operator
+ enabled ``platforms.relay.extra.<platform>.rich_blocks`` /
+ ``markdown_blocks`` (both default OFF, same ``_coerce_flag`` semantics
+ as reply_in_thread). ``descriptor``/``platform`` are the DESTINATION's,
+ never the scalar primary: gating on the primary both leaked hints onto
+ platforms that never advertised the bit and suppressed them for ones that did.
"""
if descriptor is None or not getattr(
descriptor, "supports_block_formatting", False
@@ -1920,59 +1404,38 @@ class RelayAdapter(BasePlatformAdapter):
hints[knob] = True
return hints or None
- def _with_format_hints_for_chat(
- self, chat_id: str, metadata: Optional[Dict[str, Any]]
+ @staticmethod
+ def _stamp_format_hints(
+ hints: Optional[Dict[str, bool]], metadata: Optional[Dict[str, Any]]
) -> Optional[Dict[str, Any]]:
- """Metadata with ``format_hints`` stamped for a chat-addressed send.
-
- Resolves the chat's platform from what we saw inbound
- (``_platform_by_chat``) and that platform's negotiated descriptor
- (``_descriptor_for_chat``) — falling back to the primary identity for
- chats we never saw inbound, matching every other per-chat capability.
- """
- platform = self._platform_by_chat.get(str(chat_id)) or getattr(
- self.descriptor, "platform", None
- )
- hints = self._format_hints(self._descriptor_for_chat(chat_id), platform)
if not hints:
return metadata
merged = dict(metadata or {})
merged.setdefault("format_hints", hints)
return merged
+ def _with_format_hints_for_chat(
+ self, chat_id: str, metadata: Optional[Dict[str, Any]]
+ ) -> Optional[Dict[str, Any]]:
+ """Metadata with ``format_hints`` stamped for a chat-addressed send
+ (chat's platform as seen inbound, falling back to the primary)."""
+ hints = self._format_hints(
+ self._descriptor_for_chat(chat_id), self._chat_platform(chat_id)
+ )
+ return self._stamp_format_hints(hints, metadata)
+
def _with_format_hints_for_platform(
self, platform_value: str, metadata: Optional[Dict[str, Any]]
) -> Optional[Dict[str, Any]]:
- """Metadata with ``format_hints`` stamped for an explicit-platform send.
-
- ``send_for_platform`` is the scheduled/persisted-home lane — the cron
- delivery path, i.e. the flagship consumer of the in_channel brief —
- and it has no inbound event to populate ``_platform_by_chat``, so the
- destination platform is the caller-supplied logical platform.
- Resolves that platform's negotiated descriptor off the transport;
- falls back to the scalar descriptor only when it IS that platform's
- (fail closed: never stamp from another platform's capability bit).
- """
- descriptor: Optional[CapabilityDescriptor] = None
- if self._transport is not None:
- resolve = getattr(self._transport, "descriptor_for_platform", None)
- if callable(resolve):
- try:
- descriptor = cast(
- Optional[CapabilityDescriptor], resolve(str(platform_value))
- )
- except Exception: # noqa: BLE001 - capability lookup must never break a send
- descriptor = None
- if descriptor is None and getattr(
- self.descriptor, "platform", None
- ) == str(platform_value):
+ """Metadata with ``format_hints`` stamped for an explicit-platform send
+ (the scheduled/persisted-home lane). Falls back to the scalar
+ descriptor only when it IS that platform's — never stamp from another
+ platform's capability bit."""
+ descriptor = self._negotiated_descriptor(str(platform_value))
+ if descriptor is None and self.descriptor.platform == str(platform_value):
descriptor = self.descriptor
hints = self._format_hints(descriptor, str(platform_value))
- if not hints:
- return metadata
- merged = dict(metadata or {})
- merged.setdefault("format_hints", hints)
- return merged
+ return self._stamp_format_hints(hints, metadata)
async def send(
self,
@@ -1984,40 +1447,15 @@ class RelayAdapter(BasePlatformAdapter):
send_metadata = dict(metadata or {})
explicit_platform = send_metadata.pop("_relay_logical_platform", None)
# Consumer-declared interim send (commentary, tail flush): NOT the
- # turn-final, so it must never trigger seal-interception — sealing
- # the live stream with interim text orphans the true final into a
- # plain-send duplicate (live finding, 2026-08-16 canary). The
- # marker is gateway-internal; strip before the wire.
+ # turn-final, so it must never trigger seal-interception (sealing the
+ # live stream with interim text orphans the true final into a plain
+ # duplicate). Gateway-internal marker; strip before the wire.
_interim = bool(send_metadata.pop("_interim_send", False))
- # NS-658 seal-interception — checked BEFORE the explicit-platform
- # branch (finding #7, live canary): the delivery-resolver lane
- # (follow-up queue, media-accompanied finals, scheduled sends) routes
- # through send_for_platform, which posted a plain send while the
- # native stream stayed open — the user got the stream frozen
- # mid-word (live indicator, never sealed) PLUS the final as a
- # separate message. An open stream absorbs the turn-final send no
- # matter which egress door it arrives through; the stream IS the
- # message.
- if not _interim:
- _send_key = self._match_open_draft(str(chat_id), send_metadata)
- else:
- _send_key = None
- if _send_key is not None:
- seal = await self._seal_open_draft(
- chat_id, content, send_metadata, draft_key=_send_key
- )
- if seal.success:
- return seal
- # Review finding (PR 85796, point 1): a failed seal must NOT
- # swallow the turn-final — the stream consumer has already
- # disabled the draft transport, so returning failure here means
- # the user never gets the answer. Fall through to a plain send
- # (the orphaned stream is sealed connector-side by recycling /
- # MAX_OPEN_STREAMS eviction).
- logger.warning(
- "relay seal failed (%s); delivering turn-final as plain send",
- seal.error,
- )
+ # Seal-interception is checked BEFORE the explicit-platform branch:
+ # an open stream absorbs the turn-final whichever door it arrives through.
+ seal = await self._absorb_into_open_draft(chat_id, content, send_metadata, _interim)
+ if seal is not None:
+ return seal
if explicit_platform:
return await self.send_for_platform(
explicit_platform,
@@ -2028,38 +1466,26 @@ class RelayAdapter(BasePlatformAdapter):
)
if self._transport is None:
return SendResult(success=False, error="no transport")
- # Native _resolve_thread_ts parity: a Slack DM reply must post flat at
- # the DM root, not threaded under the triggering message. One shared
- # helper resolves the anchor for EVERY egress lane (see
- # _apply_slack_thread_anchor) so the text and media lanes cannot drift.
+ # Slack DM replies post flat at the DM root (native _resolve_thread_ts
+ # parity); one shared helper for the text and media lanes.
effective_reply_to = self._apply_slack_thread_anchor(
chat_id, reply_to, send_metadata
)
- _unfurl = self._slack_unfurl_hints(
- self._platform_by_chat.get(str(chat_id))
- or getattr(self.descriptor, "platform", None)
- )
- if _unfurl:
- send_metadata.update(_unfurl)
- result = await self._transport.send_outbound(
+ self._stamp_slack_unfurl(self._chat_platform(chat_id), send_metadata)
+ result = await self._outbound(
+ chat_id,
{
"op": "send",
"chat_id": chat_id,
"content": content,
"reply_to": effective_reply_to,
- "metadata": self._with_scope(
- chat_id, self._with_format_hints_for_chat(chat_id, send_metadata)
- ),
+ "metadata": self._text_metadata(chat_id, send_metadata),
},
- platform=self._platform_by_chat.get(str(chat_id)),
)
- # Auto-thread routing feedback (contract §SendResult): when the
- # connector's auto-thread egress policy routed this send into a
- # thread it just created, the result carries thread_id (+ the
- # initial name). The conversation was keyed on the PARENT channel —
- # the thread didn't exist at ingest — so this is the only place the
- # gateway learns where the reply landed. The semantic-rename lane
- # (auto session title) reads it via auto_thread_info_for_chat.
+ # Auto-thread routing feedback: when the connector's auto-thread policy
+ # routed this send into a thread it just created, the result carries
+ # thread_id (+ initial name). The conversation was keyed on the PARENT
+ # channel, so this is the only place the gateway learns where the reply landed.
try:
_at_thread = result.get("thread_id")
_at_name = result.get("auto_thread_name")
@@ -2074,10 +1500,8 @@ class RelayAdapter(BasePlatformAdapter):
)
except Exception: # noqa: BLE001 - feedback capture must never break send
pass
- # Wake the rename lane on EVERY send into this chat, not only the ones
- # that auto-threaded. It is waiting to learn where this turn's reply
- # landed, and "nowhere new" is an answer — one it should get now rather
- # than by outlasting a timeout.
+ # Wake the rename lane on EVERY send into this chat: "nowhere new" is
+ # an answer it should get now rather than by outlasting a timeout.
waiter = self._auto_thread_waiters.get(str(chat_id))
if waiter is not None:
waiter.set()
@@ -2090,9 +1514,8 @@ class RelayAdapter(BasePlatformAdapter):
def auto_thread_info_for_chat(
self, chat_id: str
) -> Optional[Tuple[str, str]]:
- """(thread_id, initial_name) of the auto-thread the connector created
- for the most recent send into *chat_id*, if any. Consumed by the
- gateway's semantic thread-rename lane (auto session title)."""
+ """(thread_id, initial_name) of the connector-created auto-thread for the
+ most recent send into *chat_id*, if any (semantic thread-rename lane)."""
return self._auto_thread_by_chat.get(str(chat_id))
async def wait_for_auto_thread_info(
@@ -2100,16 +1523,10 @@ class RelayAdapter(BasePlatformAdapter):
) -> Optional[Tuple[str, str]]:
"""``auto_thread_info_for_chat``, but willing to wait for the send.
- The rename lane asks where the reply landed as soon as the session is
- titled, and the session is titled from the user's opening message —
- before the model has answered, let alone before we've sent anything. So
- the question arrives a whole turn early, and a turn is a one-liner or
- twenty minutes of tool calls.
-
- Waits for the next send into this chat and then answers, so a reply the
- connector didn't auto-thread reports its miss as soon as it's sent
- instead of holding until *timeout* — which is only a backstop for a turn
- that never sends at all.
+ The rename lane asks as soon as the session is titled — a whole turn
+ early. Waits for the next send into this chat, so a reply the connector
+ didn't auto-thread reports its miss immediately; *timeout* is only a
+ backstop for a turn that never sends.
"""
info = self.auto_thread_info_for_chat(chat_id)
if info is not None:
@@ -2124,9 +1541,8 @@ class RelayAdapter(BasePlatformAdapter):
except asyncio.TimeoutError:
return None
finally:
- # Only the waiter we may have installed, and only if no later call
- # replaced it; a fired event must not be left behind to make the
- # next turn's wait return instantly on stale feedback.
+ # Only the waiter we installed, and only if no later call replaced
+ # it; a fired event must not make the next turn's wait return instantly.
if self._auto_thread_waiters.get(key) is waiter:
self._auto_thread_waiters.pop(key, None)
return self.auto_thread_info_for_chat(chat_id)
@@ -2139,61 +1555,30 @@ class RelayAdapter(BasePlatformAdapter):
) -> Optional[str]:
"""Suppress the synthetic-DM thread anchor for a Slack DM reply.
- A DM turn's streaming reply is sent with ``reply_to`` = the triggering
- message's ts (the stream consumer's ``initial_reply_to_id``, used as the
- edit anchor and, on threading platforms, the reply target). The
- connector's slackRestSender maps a raw ``reply_to`` to a Slack
- ``thread_ts``, so a plain DM reply would be posted THREADED under the
- user's message instead of flat at the DM root — and a threaded first
- send loses the progressive edit-streaming the user sees in a real
- thread (the reported symptom: DM/home replies arrive flat, no
- progressive edits).
-
- Native Slack Hermes already suppresses this synthetic DM thread anchor:
- ``SlackAdapter._resolve_thread_ts`` returns ``None`` for a top-level /
- DM message when ``reply_in_thread`` is off. The relay lane has no such
- disambiguation, so we reproduce it here. run.py already encodes the
- real-thread decision in ``metadata["thread_id"]`` (it is set only when
- progress threading is active — a real thread, or channel autoThread);
- for a DM with no real thread that key is absent. So the rule is:
-
- Slack DM + no real ``thread_id`` in metadata ⇒ drop ``reply_to``.
-
- This posts the reply flat at the DM root and lets the consumer edit its
- own first-send ts — streaming works exactly as in a thread. It does NOT:
- * reintroduce a synthetic DM thread_id (#18859 / the /sethome
- landmine) — it removes an anchor, never adds one;
- * regress real-thread streaming — a real thread carries a distinct
- ``thread_id`` in metadata, so the guard leaves ``reply_to`` alone;
- * regress channel autoThread — a channel/group top-level reply carries
- ``thread_id`` (the message's own ts) in metadata when threading is
- on, so it is left alone; and a non-DM chat is never matched here.
+ The stream consumer sends a DM reply with ``reply_to`` = the triggering
+ ts (its edit anchor); the connector maps a raw reply_to to a Slack
+ thread_ts, so the reply would thread under the user's message and lose
+ progressive edit streaming. Native ``_resolve_thread_ts`` drops that
+ anchor only when ``reply_in_thread`` is off; mirror it:
+
+ Slack DM + no real ``thread_id``/``thread_ts`` + flat mode ⇒ drop.
+
+ In thread-per-message mode the triggering ts IS the thread anchor and
+ the final reply's ONLY threading signal (dropping it unconditionally
+ exiled finals to the DM root while progress stayed threaded). Removes
+ an anchor, never adds one; real threads and channel autoThread carry
+ ``thread_id`` and are left alone.
"""
if reply_to is None:
return None
- if self._platform_by_chat.get(str(chat_id)) != Platform.SLACK.value:
+ if self._platform_by_chat.get(str(chat_id)) != _SLACK:
return reply_to
if self._chat_type_by_chat.get(str(chat_id)) != "dm":
return reply_to
md = metadata or {}
if md.get("thread_id") or md.get("thread_ts"):
- # A real thread was resolved by run.py — honour it.
- return reply_to
- # Mode gate (native _resolve_thread_ts parity). The final-reply lane
- # (gateway/platforms/base.py) builds metadata from source.thread_id
- # ONLY — for a top-level DM that is None, so in thread-per-message
- # mode the triggering-ts reply_to here is the final reply's ONLY
- # threading signal (run.py's synthetic root feeds just the
- # progress/status lane). Dropping it unconditionally exiled the final
- # message to the DM root while progress stayed threaded (2026-07-27
- # report, same class as the prompt-placement bug). Native SlackAdapter only
- # suppresses the anchor when reply_in_thread=false; mirror that.
- reply_in_thread = self._effective_reply_in_thread()
- if reply_in_thread:
- # Thread-per-message: the triggering ts is the thread anchor.
return reply_to
- # Flat mode: synthetic DM self-anchor — post flat at the DM root.
- return None
+ return reply_to if self._effective_reply_in_thread() else None
def _apply_slack_thread_anchor(
self,
@@ -2205,24 +1590,15 @@ class RelayAdapter(BasePlatformAdapter):
) -> Optional[str]:
"""Resolve the outbound Slack thread anchor for ONE egress frame.
- The single choke point every send lane goes through — text (``send``)
- and media (``send_media``) alike. It does three things that must always
- happen together, and previously only happened on the text lane:
-
- 1. Mode gate: ``_resolve_reply_to_for_send`` drops the synthetic DM
- self-anchor in flat mode, keeps it in thread-per-message mode.
+ The single choke point for text (``send``) and media (``_send_media``):
+ 1. Mode gate: ``_resolve_reply_to_for_send``.
2. Mirror strip: when the anchor is dropped, remove the mirrored
- ``metadata.reply_to_message_id`` too, so the connector cannot
- thread on the copy we forgot about.
+ ``metadata.reply_to_message_id`` too, or the connector threads on it.
3. Anchor promotion: the connector's Slack sender THREADS ON METADATA
- ONLY — ``threadTs()`` reads ``metadata.thread_id``/``thread_ts``
- and never looks at the frame's ``reply_to``. A surviving anchor is
- promoted into ``metadata.thread_id`` or the message silently lands
- in the home channel instead of the per-message thread.
-
- ``metadata`` is mutated in place; the effective ``reply_to`` is
- returned. Non-Slack and non-DM chats are untouched by (1), and (3) is
- Slack-only, so other fronted platforms keep their existing behaviour.
+ ONLY (``threadTs()`` never reads the frame's ``reply_to``), so a
+ surviving anchor is promoted into ``metadata.thread_id``.
+
+ ``metadata`` is mutated in place; the effective ``reply_to`` is returned.
"""
effective_reply_to = self._resolve_reply_to_for_send(
chat_id, reply_to, metadata
@@ -2231,7 +1607,7 @@ class RelayAdapter(BasePlatformAdapter):
metadata.pop(mirror_key, None)
if (
effective_reply_to is not None
- and self._platform_by_chat.get(str(chat_id)) == Platform.SLACK.value
+ and self._platform_by_chat.get(str(chat_id)) == _SLACK
and not (metadata.get("thread_id") or metadata.get("thread_ts"))
):
metadata["thread_id"] = str(effective_reply_to)
@@ -2242,26 +1618,16 @@ class RelayAdapter(BasePlatformAdapter):
) -> Dict[str, Any]:
"""Copy ``metadata`` with the typing/status thread anchor applied.
- Slack's status line is THREAD-scoped: the connector's typing case
- no-ops without a thread anchor, and the typing lane's metadata
- (base.py ``_thread_metadata_for_source``) carries none for a top-level
- DM (``source.thread_id`` is None). Synthesize it from the per-chat
- inbound-ts cache, exactly as native ``send_typing`` resolves
- ``thread_ts`` from ``metadata.message_id``.
-
- Unconditional across both modes: in flat mode the send lane strips its
- own anchors (see ``_apply_slack_thread_anchor``), so the status anchor
- cannot leak into reply placement, and ``setStatus`` clears without
- leaving a message artifact.
-
- Shared by ``send_typing`` and ``stop_typing`` — the clear MUST target
- the same thread the heartbeat set, or the status line sticks until
- Slack's own timeout. Keeping one implementation is what guarantees it.
+ Slack's status line is THREAD-scoped and the typing lane's metadata
+ carries no anchor for a top-level DM, so synthesize it from the
+ per-chat inbound-ts cache (native ``send_typing`` parity). Shared by
+ ``send_typing`` and ``stop_typing`` — the clear MUST target the same
+ thread the heartbeat set or the status sticks until Slack's timeout.
"""
md = dict(metadata or {})
if (
not (md.get("thread_id") or md.get("thread_ts"))
- and self._platform_by_chat.get(str(chat_id)) == Platform.SLACK.value
+ and self._platform_by_chat.get(str(chat_id)) == _SLACK
and self._chat_type_by_chat.get(str(chat_id)) == "dm"
):
anchor = self._last_inbound_ts_by_chat.get(str(chat_id))
@@ -2281,21 +1647,15 @@ class RelayAdapter(BasePlatformAdapter):
"""Edit a relayed message through the connector-owned platform API."""
if self._transport is None:
return SendResult(success=False, error="no transport")
- result = await self._transport.send_outbound(
+ result = await self._outbound(
+ chat_id,
{
"op": "edit",
"chat_id": chat_id,
"message_id": message_id,
"content": content,
- # Same format_hints as send: a streamed reply's FINAL edit is
- # the frame that carries the finished markdown, so the edit
- # lane must signal block rendering too or streams would seal
- # as plain text (boundary rule: every text egress lane).
- "metadata": self._with_scope(
- chat_id, self._with_format_hints_for_chat(chat_id, metadata)
- ),
+ "metadata": self._text_metadata(chat_id, metadata),
},
- platform=self._platform_by_chat.get(str(chat_id)),
)
return SendResult(
success=bool(result.get("success")),
@@ -2308,18 +1668,10 @@ class RelayAdapter(BasePlatformAdapter):
chat_id: str,
message_id: str,
) -> bool:
- """Delete a relayed message through the connector-owned platform API.
-
- Consumer: the stream consumer's fresh-final cleanup — on the Slack
- unfurl force-on route the completed reply is re-delivered as a new
- stamped post and the sealed streamed preview must go away, or the
- user sees the answer twice.
-
- Gated on the negotiated descriptor advertising the ``delete`` op
- (additive within contract_version 1): older connectors never receive
- an op they can't dispatch, and this returns False so the consumer's
- best-effort cleanup degrades to leaving the preview in place —
- exactly the pre-delete behavior.
+ """Delete a relayed message (the stream consumer's fresh-final cleanup).
+
+ Gated on the descriptor advertising ``delete``: older connectors return
+ False so cleanup degrades to leaving the preview in place.
"""
if self._transport is None:
return False
@@ -2327,14 +1679,14 @@ class RelayAdapter(BasePlatformAdapter):
if "delete" not in (desc.supported_ops or ()):
return False
try:
- result = await self._transport.send_outbound(
+ result = await self._outbound(
+ chat_id,
{
"op": "delete",
"chat_id": chat_id,
"message_id": message_id,
"metadata": self._with_scope(chat_id, {}),
},
- platform=self._platform_by_chat.get(str(chat_id)),
)
except Exception:
logger.debug("relay delete_message failed", exc_info=True)
@@ -2344,54 +1696,19 @@ class RelayAdapter(BasePlatformAdapter):
async def send_typing(self, chat_id: str, metadata=None) -> None:
"""Egress a typing indicator through the connector.
- The base class spawns ``_keep_typing`` for every adapter (a 2s refresh
- loop for the life of the turn), but the relay adapter inherited the
- base no-op ``send_typing`` — so hosted/relay chats never showed
- "is typing…" even though the wire contract (``OutboundOp "typing"``)
- and every connector-side sender (Discord ``POST /channels/{id}/typing``,
- Telegram ``sendChatAction``, Signal ``sendTyping``, Slack assistant
- status) already implement it. This bridges the loop's tick onto the
- existing outbound frame.
-
- Two details are load-bearing, mirroring ``send()``:
- - ``_with_scope``: the connector's egress guard wraps ALL ops
- (routedEgressGuard), so a typing frame without a resolvable tenant
- discriminator (metadata.scope_id, or user_id for DMs) is declined
- exactly like a bare send would be.
- - the per-frame ``platform`` tag (Phase 1.5): a multi-platform
- gateway must egress typing through the platform the chat lives on.
-
- Best-effort: failures are swallowed (``_keep_typing`` already treats
- send_typing errors as non-fatal, and an older connector that rejects
- the op just returns an unsuccessful result we ignore). Each call is
- one-shot — Discord/Telegram indicators self-expire and need no cleanup;
- Slack Assistant status persists, so ``stop_typing`` below sends an
- explicit clear for Slack only.
+ Bridges the base ``_keep_typing`` tick onto the ``typing`` op. Carries
+ ``_with_scope`` (the egress guard wraps ALL ops) and the per-frame
+ platform tag. Best-effort and one-shot: Discord/Telegram indicators
+ self-expire; Slack Assistant status persists, so ``stop_typing``
+ sends an explicit clear for Slack only.
"""
if self._transport is None:
return
- # Thread anchor for the status surface. Slack's status line
- # ("is thinking…" in the thread's replies footer — works with plain
- # chat:write, confirmed on native no-assistant bots) is THREAD-only:
- # the connector's typing case no-ops without a thread_ts. But the
- # typing lane's metadata (base.py _thread_metadata_for_source) has no
- # anchor for a top-level DM — source.thread_id is None — so every
- # heartbeat was silently dropped. In thread-per-message mode the
- # turn's thread root IS the triggering message ts (run.py's synthetic
- # root); synthesize it here from the per-chat inbound cache, exactly
- # like native send_typing resolves thread_ts from metadata.message_id.
- # Flat mode (reply_in_thread=false) keeps the no-anchor no-op: there
- # is no thread and must not be one (#18859).
md = self._with_status_thread_anchor(chat_id, metadata)
- # Rich status parity: run.py's live-status lane stashes the
- # current per-tool phrase via set_status_text() (base class store).
- # Carry it as the typing frame's content so the connector's Slack
- # sender renders it on assistant.threads.setStatus — the same phrase
- # the native adapter shows ("is running pytest…", "Finding answers…").
- # Absent (None/empty) => omit content; the connector falls back to its
- # default "is typing…" heartbeat, preserving pre-phrase behaviour on
- # every platform. Never send empty-string content here: on Slack that
- # is the explicit CLEAR request reserved for stop_typing.
+ # Rich status parity: carry run.py's per-tool phrase as the frame's
+ # content (rendered on assistant.threads.setStatus). Absent => omit
+ # content and the connector uses its default heartbeat. NEVER send
+ # empty-string content here: on Slack that is the CLEAR request.
frame: Dict[str, Any] = {
"op": "typing",
"chat_id": chat_id,
@@ -2401,10 +1718,7 @@ class RelayAdapter(BasePlatformAdapter):
if phrase:
frame["content"] = str(phrase)
try:
- await self._transport.send_outbound(
- frame,
- platform=self._platform_by_chat.get(str(chat_id)),
- )
+ await self._outbound(chat_id, frame)
except Exception: # noqa: BLE001 - typing is cosmetic, never breaks a turn
logger.debug("relay send_typing failed for %s", chat_id, exc_info=True)
@@ -2413,48 +1727,34 @@ class RelayAdapter(BasePlatformAdapter):
chat_id: str,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
- """Forward an explicit typing/status clear to the connector.
-
- Slack Assistant status persists until explicitly cleared (empty
- ``content`` on the ``typing`` op). Other relay senders expose only
- one-shot typing heartbeats; sending an empty heartbeat there would
- incorrectly re-trigger typing at completion, so this is Slack-gated.
-
- NOTE (deploy order): a connector older than gateway-gateway #154
- hardcodes ``status: "is typing…"`` for the typing op, so an empty
- clear frame would SET the status instead of clearing it. Deploy the
- connector first. Best-effort like ``send_typing``: status clearing is
- cosmetic and must never break turn completion.
+ """Forward an explicit typing/status clear (empty ``content``) — Slack only.
+
+ Other relay senders have one-shot heartbeats, where an empty heartbeat
+ would re-trigger typing at completion. Deploy-order note: a connector
+ older than gateway-gateway #154 hardcodes the typing status and would
+ SET it on a clear frame — deploy the connector first.
"""
if self._transport is None:
return
- platform = self._platform_by_chat.get(str(chat_id))
- if platform != Platform.SLACK.value:
+ if self._platform_by_chat.get(str(chat_id)) != _SLACK:
return
- # Clear must target the SAME thread the heartbeat set, or the clear
- # frame no-ops threadless and the status line sticks until Slack's own
- # timeout. Shared helper with send_typing so the two guards cannot drift.
md = self._with_status_thread_anchor(chat_id, metadata)
try:
- await self._transport.send_outbound(
+ await self._outbound(
+ chat_id,
{
"op": "typing",
"chat_id": chat_id,
"content": "",
"metadata": self._with_scope(chat_id, md),
},
- platform=platform,
)
except Exception: # noqa: BLE001 - status clear is cosmetic, never breaks a turn
logger.debug("relay stop_typing failed for %s", chat_id, exc_info=True)
async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
- # Proxied to the connector (it owns the platform connection / cache).
- # Gated on op-level capability discovery: a connector that doesn't
- # advertise get_chat_info in supported_ops (including every legacy
- # connector, where supported_ops is empty and the LEGACY_OPS set
- # applies) would only return "unsupported op", so skip the round trip
- # and answer with the same local fallback the error path produced.
+ # Proxied to the connector; op-gated so a legacy connector (which would
+ # only answer "unsupported op") gets the same local fallback without a round trip.
if self._transport is None or not self.descriptor.supports_op("get_chat_info"):
return {"name": chat_id, "type": "dm"}
return await self._transport.get_chat_info(chat_id)
@@ -2466,25 +1766,21 @@ class RelayAdapter(BasePlatformAdapter):
content: str,
metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
- """Send via a shared-identity capability bound to a session (A2 outbound).
+ """Send via a shared-identity capability bound to a session.
- The gateway never holds the credential: it names the session it is
- already in plus the capability ``kind``, and the connector resolves the
- real value from its vault and egresses (enforcing the tenant match). Used
- e.g. to post a Discord interaction follow-up as the shared bot without
- the token ever reaching the gateway. See RelayTransport.send_follow_up.
+ The gateway never holds the credential: it names the session and the
+ capability ``kind``; the connector resolves the value from its vault
+ and egresses (enforcing the tenant match).
"""
if self._transport is None:
return SendResult(success=False, error="no transport")
- # Phase 1.5: the capability `kind` is platform-prefixed (e.g.
- # "discord.interaction_token"), so derive the egress platform from it when
- # it names one we front — that tags the OutboundFrame so a multi-platform
- # gateway routes the follow-up through the right sender. Falls back to the
- # session default (connector-side) when the prefix isn't a fronted platform.
+ # `kind` is platform-prefixed ("discord.interaction_token"): tag the
+ # frame with that platform when we front it; otherwise the connector's
+ # session default routes it.
follow_up_platform = None
if kind and "." in kind:
prefix = kind.split(".", 1)[0]
- if self._platform_is_fronted(prefix):
+ if self.fronts_platform(prefix):
follow_up_platform = prefix
result = await self._transport.send_follow_up(
{
@@ -2505,13 +1801,9 @@ class RelayAdapter(BasePlatformAdapter):
# ── Phase 2 media ─────────────────────────────────────────────────────
def _get_media_client(self) -> Optional[RelayMediaClient]:
- """Lazily build the authenticated /relay/media client.
-
- Uses the SAME connector base URL the WS dials and the SAME per-gateway
- (id, secret) the upgrade authenticates with — no new configuration.
- None when either is unavailable (unenrolled/dev), and every media lane
- then degrades to its pre-media fallback.
- """
+ """Lazily build the authenticated /relay/media client from the SAME
+ dial URL and per-gateway creds the WS uses; None when unavailable
+ (media lanes then degrade to their pre-media fallbacks)."""
if self._media_client is not None:
return self._media_client
try:
@@ -2545,15 +1837,11 @@ class RelayAdapter(BasePlatformAdapter):
) -> Optional[SendResult]:
"""Egress one media object via the connector's ``send_media`` op.
- ``source`` is either a LOCAL file path (uploaded to the connector's
- /relay/media first — the connector cannot reach our filesystem) or an
- already-public URL (fal.media output etc. — passed through; the
- connector downloads it directly).
-
- Returns None when the lane is unavailable (op not advertised, no
- transport, upload failed) so each caller can fall back to its
- pre-media behaviour — media delivery is progressive enhancement,
- never a regression when the connector predates the op.
+ ``source`` is a LOCAL path (uploaded to /relay/media first — the
+ connector cannot reach our filesystem) or an already-public URL
+ (passed through). Returns None when the lane is unavailable (op not
+ advertised, no transport, upload failed, connector decline) so each
+ caller falls back to its pre-media behaviour.
"""
if self._transport is None or not self.descriptor.supports_op("send_media"):
return None
@@ -2566,21 +1854,13 @@ class RelayAdapter(BasePlatformAdapter):
if not uploaded:
return None
source_url = uploaded
- # Same Slack thread-anchor contract as the text lane (send). Media
- # frames egress through the connector's Slack sender too, so an
- # unresolved anchor threads an image under the user's DM message in
- # flat mode, and loses the per-message thread entirely in thread mode
- # (threadTs() reads metadata only). Route through the shared helper.
+ # Same Slack thread-anchor contract as the text lane: media frames go
+ # through the connector's Slack sender too (threadTs() reads metadata only).
media_metadata: Dict[str, Any] = dict(metadata or {})
effective_reply_to = self._apply_slack_thread_anchor(
chat_id, reply_to, media_metadata
)
- _media_unfurl = self._slack_unfurl_hints(
- self._platform_by_chat.get(str(chat_id))
- or getattr(self.descriptor, "platform", None)
- )
- if _media_unfurl:
- media_metadata.update(_media_unfurl)
+ self._stamp_slack_unfurl(self._chat_platform(chat_id), media_metadata)
action: Dict[str, Any] = {
"op": "send_media",
"chat_id": chat_id,
@@ -2593,18 +1873,13 @@ class RelayAdapter(BasePlatformAdapter):
if filename:
action["filename"] = filename
try:
- result = await self._transport.send_outbound(
- action,
- platform=self._platform_by_chat.get(str(chat_id)),
- )
+ result = await self._outbound(chat_id, action)
except Exception: # noqa: BLE001 - transport failure degrades to the caller's fallback
logger.debug("relay send_media transport failure", exc_info=True)
return None
if not result.get("success"):
- # A structured connector decline (size cap, platform rejection).
- # Surface it as a failed lane so the caller's fallback still
- # delivers SOMETHING (the caption/notice), mirroring native
- # adapters' upload-failure paths.
+ # Structured connector decline (size cap, platform rejection): the
+ # caller's fallback still delivers the caption/notice.
logger.warning(
"relay send_media declined for %s: %s",
chat_id,
@@ -2627,13 +1902,8 @@ class RelayAdapter(BasePlatformAdapter):
) -> SendResult:
"""Send an image (public URL) as a native attachment via the connector."""
result = await self._send_media(
- chat_id,
- media_kind="image",
- source=image_url,
- source_is_path=False,
- caption=caption,
- reply_to=reply_to,
- metadata=metadata,
+ chat_id, media_kind="image", source=image_url, source_is_path=False,
+ caption=caption, reply_to=reply_to, metadata=metadata,
)
if result is not None:
return result
@@ -2652,23 +1922,13 @@ class RelayAdapter(BasePlatformAdapter):
) -> SendResult:
"""Send a local image file natively (upload → send_media)."""
result = await self._send_media(
- chat_id,
- media_kind="image",
- source=image_path,
- source_is_path=True,
- caption=caption,
- reply_to=reply_to,
- metadata=metadata,
+ chat_id, media_kind="image", source=image_path, source_is_path=True,
+ caption=caption, reply_to=reply_to, metadata=metadata,
)
if result is not None:
return result
return await super().send_image_file(
- chat_id,
- image_path,
- caption=caption,
- reply_to=reply_to,
- metadata=metadata,
- **kwargs,
+ chat_id, image_path, caption=caption, reply_to=reply_to, metadata=metadata, **kwargs
)
async def send_voice(
@@ -2682,23 +1942,13 @@ class RelayAdapter(BasePlatformAdapter):
) -> SendResult:
"""Send a local audio file as a native voice message (upload → send_media)."""
result = await self._send_media(
- chat_id,
- media_kind="voice",
- source=audio_path,
- source_is_path=True,
- caption=caption,
- reply_to=reply_to,
- metadata=metadata,
+ chat_id, media_kind="voice", source=audio_path, source_is_path=True,
+ caption=caption, reply_to=reply_to, metadata=metadata,
)
if result is not None:
return result
return await super().send_voice(
- chat_id,
- audio_path,
- caption=caption,
- reply_to=reply_to,
- metadata=metadata,
- **kwargs,
+ chat_id, audio_path, caption=caption, reply_to=reply_to, metadata=metadata, **kwargs
)
async def send_video(
@@ -2712,23 +1962,13 @@ class RelayAdapter(BasePlatformAdapter):
) -> SendResult:
"""Send a local video file natively (upload → send_media)."""
result = await self._send_media(
- chat_id,
- media_kind="video",
- source=video_path,
- source_is_path=True,
- caption=caption,
- reply_to=reply_to,
- metadata=metadata,
+ chat_id, media_kind="video", source=video_path, source_is_path=True,
+ caption=caption, reply_to=reply_to, metadata=metadata,
)
if result is not None:
return result
return await super().send_video(
- chat_id,
- video_path,
- caption=caption,
- reply_to=reply_to,
- metadata=metadata,
- **kwargs,
+ chat_id, video_path, caption=caption, reply_to=reply_to, metadata=metadata, **kwargs
)
async def send_document(
@@ -2743,25 +1983,14 @@ class RelayAdapter(BasePlatformAdapter):
) -> SendResult:
"""Send a local file as a downloadable attachment (upload → send_media)."""
result = await self._send_media(
- chat_id,
- media_kind="document",
- source=file_path,
- source_is_path=True,
- caption=caption,
- filename=file_name,
- reply_to=reply_to,
- metadata=metadata,
+ chat_id, media_kind="document", source=file_path, source_is_path=True,
+ caption=caption, filename=file_name, reply_to=reply_to, metadata=metadata,
)
if result is not None:
return result
return await super().send_document(
- chat_id,
- file_path,
- caption=caption,
- file_name=file_name,
- reply_to=reply_to,
- metadata=metadata,
- **kwargs,
+ chat_id, file_path, caption=caption, file_name=file_name,
+ reply_to=reply_to, metadata=metadata, **kwargs,
)
# ── Phase 3 interactive: prompt + react ──────────────────────────────
@@ -2769,29 +1998,21 @@ class RelayAdapter(BasePlatformAdapter):
def _mint_prompt(
self, kind: str, state: Dict[str, Any], timeout_s: float = 3600.0
) -> str:
- """Register a pending prompt and return its id.
-
- ``state`` carries what the resolver needs when the answer comes back
- (session_key, resolver kind, per-kind extras). Expiry is enforced
- gateway-side on consumption (_pop_prompt) — the wire's timeout_s is
- advisory only.
-
- The id is ``<owner nonce>.<8 hex>``: the nonce marks the minting
- process so a sibling gateway that receives the same fanned-out answer
- can tell it is not the owner and stay quiet (see
- ``_prompt_owner_nonce``). Both segments use the callback alphabet the
- connector's prompt codec accepts ([A-Za-z0-9_.-], <=32 chars).
- """
- import time
+ """Register a pending prompt and return its id (``<owner nonce>.<8 hex>``).
+ ``state`` carries what the resolver needs when the answer comes back.
+ Expiry is enforced gateway-side on consumption (_pop_prompt); the
+ wire's timeout_s is advisory. The nonce marks the minting process so a
+ sibling gateway receiving the fanned-out answer stays quiet. Both
+ segments use the connector codec's alphabet ([A-Za-z0-9_.-], <=32).
+ """
prompt_id = f"{self._prompt_owner_nonce}.{secrets.token_hex(4)}"
self._pending_prompts[prompt_id] = {
**state,
"kind": kind,
"expires_at": time.time() + timeout_s,
}
- # Opportunistic sweep so abandoned prompts can't accumulate: drop
- # anything already expired (cheap — dict is small by construction).
+ # Opportunistic sweep so abandoned prompts can't accumulate.
now = time.time()
for stale in [
k for k, v in self._pending_prompts.items() if v.get("expires_at", 0) < now
@@ -2800,19 +2021,14 @@ class RelayAdapter(BasePlatformAdapter):
return prompt_id
def _minted_here(self, prompt_id: str) -> bool:
- """True when this process minted ``prompt_id``.
-
- Ids minted before the owner nonce existed (a prompt still pending
- across an in-place upgrade) carry no ``.`` segment; treat them as ours
- so an in-flight prompt from the previous build still resolves.
- """
+ """True when this process minted ``prompt_id``. Ids without a ``.``
+ segment predate the owner nonce (in-flight across an in-place upgrade)
+ and are treated as ours."""
head, sep, _ = str(prompt_id).partition(".")
return head == self._prompt_owner_nonce if sep else True
def _pop_prompt(self, prompt_id: str) -> Optional[Dict[str, Any]]:
"""Consume a pending prompt: one answer wins, expired entries miss."""
- import time
-
state = self._pending_prompts.pop(str(prompt_id), None)
if not state:
return None
@@ -2821,12 +2037,8 @@ class RelayAdapter(BasePlatformAdapter):
return state
def _note_prompt_resolved(self, prompt_id: str) -> None:
- """Remember that this process already answered ``prompt_id``.
-
- Bounded FIFO: a repeat answer is only interesting for as long as a
- redelivery or a double tap can plausibly arrive, so old ids are
- dropped rather than retained for the process lifetime.
- """
+ """Remember that this process answered ``prompt_id`` (bounded FIFO: a
+ repeat is only interesting while a redelivery/double tap can arrive)."""
self._resolved_prompts[str(prompt_id)] = time.time()
while len(self._resolved_prompts) > _RESOLVED_PROMPT_MEMORY:
self._resolved_prompts.popitem(last=False)
@@ -2843,29 +2055,16 @@ class RelayAdapter(BasePlatformAdapter):
metadata: Optional[Dict[str, Any]] = None,
timeout_s: Optional[int] = None,
) -> Optional[SendResult]:
- """Egress one `prompt` op; None when the lane is unavailable.
+ """Egress one `prompt` op; None when the lane is unavailable (the
+ caller falls back to its numbered-text base behaviour).
- Mirrors _send_media's progressive-enhancement posture: op-gated on the
- descriptor advertising `prompt`, and every failure returns None so the
- caller falls back to its numbered-text base behaviour (which is the
- pre-Phase-3 UX, still fully functional via typed replies).
+ Prompt metadata is forwarded VERBATIM: the threading mode is decided
+ in exactly one place — run.py's _resolve_progress_thread_id (flat mode
+ suppresses the synthetic self-anchor there; thread mode stamps the
+ turn's thread). Boundary pinned by test_run_py_suppresses_self_anchor*.
"""
if self._transport is None or not self.descriptor.supports_op("prompt"):
return None
- # An interactive prompt (approval / clarify / slash-confirm) is emitted
- # mid-turn in reply to the triggering inbound event, so `metadata` carries
- # that event's thread context (run.py _thread_metadata_for_source stamps
- # metadata.thread_id — for a Slack DM the triggering message's own ts,
- # used only as a session-keying fallback). Forwarding it makes the
- # connector thread the prompt card UNDER the triggering message instead
- # of posting it flat at the DM root (the reported bug). Native Slack
- # Hermes suppresses this synthetic DM thread anchor; drop it here for the
- # same Slack-DM-with-no-real-thread case, matching _resolve_reply_to_for_send.
- # Prompt metadata is forwarded VERBATIM. The threading mode is decided
- # in exactly one place — run.py's _resolve_progress_thread_id (flat mode
- # suppresses the synthetic self-anchor there; thread mode stamps the
- # turn's thread). Boundary pinned by test_run_py_suppresses_self_anchor*.
- prompt_metadata = metadata
action: Dict[str, Any] = {
"op": "prompt",
"chat_id": chat_id,
@@ -2873,18 +2072,13 @@ class RelayAdapter(BasePlatformAdapter):
"prompt_kind": prompt_kind,
"prompt_id": prompt_id,
"options": options,
- "reply_to": self._resolve_reply_to_for_send(
- chat_id, reply_to, prompt_metadata
- ),
- "metadata": self._with_scope(chat_id, prompt_metadata),
+ "reply_to": self._resolve_reply_to_for_send(chat_id, reply_to, metadata),
+ "metadata": self._with_scope(chat_id, metadata),
}
if timeout_s is not None:
action["timeout_s"] = int(timeout_s)
try:
- result = await self._transport.send_outbound(
- action,
- platform=self._platform_by_chat.get(str(chat_id)),
- )
+ result = await self._outbound(chat_id, action)
except Exception: # noqa: BLE001 - transport failure degrades to fallback
logger.debug("relay prompt transport failure", exc_info=True)
return None
@@ -2899,6 +2093,31 @@ class RelayAdapter(BasePlatformAdapter):
raw_response=result,
)
+ async def _mint_and_send_prompt(
+ self,
+ kind: str,
+ state: Dict[str, Any],
+ chat_id: str,
+ *,
+ prompt_kind: str,
+ text: str,
+ options: list,
+ metadata: Optional[Dict[str, Any]],
+ ) -> Optional[SendResult]:
+ """Register + egress a prompt; unregisters and returns None when the lane is unavailable."""
+ prompt_id = self._mint_prompt(kind, {**state, "chat_id": str(chat_id)})
+ result = await self._send_prompt(
+ chat_id,
+ prompt_kind=prompt_kind,
+ text=text,
+ prompt_id=prompt_id,
+ options=options,
+ metadata=metadata,
+ )
+ if result is None:
+ self._pending_prompts.pop(prompt_id, None)
+ return result
+
async def send_exec_approval(
self,
chat_id: str,
@@ -2910,25 +2129,17 @@ class RelayAdapter(BasePlatformAdapter):
allow_session: bool = True,
smart_denied: bool = False,
) -> SendResult:
- """Native-button exec approval over the relay (Phase 3).
-
- Renders the same choice set as the native adapters (Allow Once /
- Session / Always / Deny, gated by the same flags) through the
- connector's `prompt` op. The user's press comes back as a
- prompt_response and resolves via tools.approval.resolve_gateway_approval
- — the exact mechanism the native button handlers use. When the lane is
- unavailable the send FAILS (success=False) so gateway/run.py's existing
- button→text fallback takes over (same contract as a native adapter's
- failed button send).
+ """Native-button exec approval over the relay.
+
+ Same choice set as the native adapters; the press resolves via
+ tools.approval.resolve_gateway_approval. When the lane is unavailable
+ the send FAILS (success=False) so run.py's button→text fallback runs.
"""
options: list = [{"id": "once", "label": "Allow Once", "style": "primary"}]
if not smart_denied and allow_session:
options.append({"id": "session", "label": "Allow Session"})
if allow_permanent:
- options.append({
- "id": "always",
- "label": "Always Allow",
- })
+ options.append({"id": "always", "label": "Always Allow"})
options.append({"id": "deny", "label": "Deny", "style": "danger"})
cmd_preview = command if len(command) <= 1500 else command[:1500] + "..."
@@ -2941,23 +2152,17 @@ class RelayAdapter(BasePlatformAdapter):
text += (
"\n\n**Smart DENY:** owner override applies to this one operation only."
)
-
- prompt_id = self._mint_prompt(
+ result = await self._mint_and_send_prompt(
"exec_approval",
- {"session_key": session_key, "chat_id": str(chat_id)},
- )
- result = await self._send_prompt(
+ {"session_key": session_key},
chat_id,
prompt_kind="approval",
text=text,
- prompt_id=prompt_id,
options=options,
metadata=metadata,
)
if result is not None:
return result
- # Lane unavailable: unregister and let run.py's text fallback run.
- self._pending_prompts.pop(prompt_id, None)
return SendResult(success=False, error="relay prompt op unavailable")
async def send_slash_confirm(
@@ -2969,37 +2174,24 @@ class RelayAdapter(BasePlatformAdapter):
confirm_id: str,
metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
- """Three-button slash-command confirmation over the relay (Phase 3).
-
- Resolves via tools.slash_confirm.resolve() — the same primitive the
- native button handlers call. Falls back (success=False) to the
- gateway's text-intercept flow when the prompt lane is unavailable.
- """
+ """Three-button slash-command confirmation over the relay (resolves via
+ tools.slash_confirm.resolve; success=False falls back to text-intercept)."""
options = [
{"id": "once", "label": "Approve Once", "style": "primary"},
{"id": "always", "label": "Always Approve"},
{"id": "cancel", "label": "Cancel", "style": "danger"},
]
- text = f"**{title}**\n\n{message}" if title else message
- prompt_id = self._mint_prompt(
+ result = await self._mint_and_send_prompt(
"slash_confirm",
- {
- "session_key": session_key,
- "confirm_id": confirm_id,
- "chat_id": str(chat_id),
- },
- )
- result = await self._send_prompt(
+ {"session_key": session_key, "confirm_id": confirm_id},
chat_id,
prompt_kind="approval",
- text=text,
- prompt_id=prompt_id,
+ text=f"**{title}**\n\n{message}" if title else message,
options=options,
metadata=metadata,
)
if result is not None:
return result
- self._pending_prompts.pop(prompt_id, None)
return SendResult(success=False, error="relay prompt op unavailable")
async def send_clarify(
@@ -3011,18 +2203,12 @@ class RelayAdapter(BasePlatformAdapter):
session_key: str,
metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
- """Native-button clarify over the relay (Phase 3).
-
- Multiple-choice clarifies render as a `prompt` op (one button per
- choice + Other). A press resolves via
- tools.clarify_gateway.resolve_gateway_clarify with the CHOICE TEXT
- (never the option id); "Other" flips the clarify to text-capture
- exactly like the native adapters. Open-ended clarifies and
- unavailable lanes fall back to the base numbered-text behaviour.
-
- Option ids are positional (c0..cN / other) — choice text can be
- arbitrary UTF-8 and would blow the 64-byte callback budget; the
- registry maps ids back to the real strings on the answer.
+ """Native-button clarify over the relay.
+
+ A press resolves with the CHOICE TEXT (never the option id); "Other"
+ flips to text-capture. Option ids are positional (c0..cN / other) —
+ choice text is arbitrary UTF-8 and would blow the 64-byte callback
+ budget. Open-ended clarifies and unavailable lanes fall back to base.
"""
if choices and self.descriptor.supports_op("prompt"):
options = [
@@ -3030,26 +2216,21 @@ class RelayAdapter(BasePlatformAdapter):
for i, choice in enumerate(choices)
]
options.append({"id": "other", "label": "✏️ Other (type your answer)"})
- prompt_id = self._mint_prompt(
+ result = await self._mint_and_send_prompt(
"clarify",
{
"session_key": session_key,
"clarify_id": clarify_id,
"choices": [str(c) for c in choices],
- "chat_id": str(chat_id),
},
- )
- result = await self._send_prompt(
chat_id,
prompt_kind="clarify",
text=f"❓ {question}",
- prompt_id=prompt_id,
options=options,
metadata=metadata,
)
if result is not None:
return result
- self._pending_prompts.pop(prompt_id, None)
return await super().send_clarify(
chat_id, question, choices, clarify_id, session_key, metadata=metadata
)
@@ -3057,26 +2238,12 @@ class RelayAdapter(BasePlatformAdapter):
async def _consume_prompt_response(self, event) -> bool:
"""Route an inbound prompt_response to its waiting primitive.
- Returns True when the event was a prompt answer (consumed — do NOT
- dispatch it as a chat message), False otherwise.
-
- A prompt answer is ALWAYS consumed, whoever it belongs to. The three
- non-resolving cases each stay silent rather than falling through to
- chat dispatch:
-
- * **A sibling's prompt** (``_minted_here`` false). The connector fans a
- passthrough forward out to every live session of the tenant, so one
- button press reaches every gateway of that tenant while only the
- minting one can resolve it. Falling through here is what produced a
- wall of ``Unknown command `/c1``` — one per sibling — under the
- single ``✅`` from the real owner.
- * **A repeat answer** for an id this process already resolved (a double
- tap, or a redelivered forward). The first answer won; a second must
- not re-run the resolver or re-ack.
- * **Our own expired/unknown prompt.** Answer with a short expiry notice
- instead of a command-not-found error: the option ids a prompt renders
- ("c1", "once", "other") are not commands, so the text lane cannot do
- anything useful with them.
+ Returns True when the event was a prompt answer (consumed — never
+ dispatched as chat). Every prompt answer is consumed, whoever owns it:
+ a sibling's prompt (the connector fans the press to every gateway of
+ the tenant; falling through produced a wall of "Unknown command"), a
+ repeat answer (first one won), or our own expired/unknown prompt
+ (answered with a short expiry notice — option ids are not commands).
"""
pr = getattr(event, "prompt_response", None)
if not isinstance(pr, dict):
@@ -3086,9 +2253,6 @@ class RelayAdapter(BasePlatformAdapter):
if not prompt_id or not option_id:
return False
if not self._minted_here(prompt_id):
- # A sibling gateway of this tenant owns this prompt and is
- # resolving it right now. Consume silently — two gateways must
- # never both answer one press.
logger.debug(
"relay prompt_response %s (option=%s) belongs to another "
"gateway instance — ignoring",
@@ -3117,119 +2281,84 @@ class RelayAdapter(BasePlatformAdapter):
kind = state.get("kind")
chat_id = str(state.get("chat_id") or getattr(event.source, "chat_id", ""))
- session_key = str(state.get("session_key") or "")
+ handler = _PROMPT_RESOLVERS.get(kind)
try:
- if kind == "exec_approval":
- from tools.approval import resolve_gateway_approval
-
- choice = (
- option_id
- if option_id in {"once", "session", "always", "deny"}
- else "deny"
- )
- count = resolve_gateway_approval(session_key, choice)
- label = {
- "once": "✅ Approved once",
- "session": "✅ Approved for session",
- "always": "✅ Approved permanently",
- "deny": "❌ Denied",
- }.get(choice, "Resolved")
- if not count:
- label = "⌛ Approval expired — no command was waiting."
- # Acknowledge in-channel (the connector's prompt message can't
- # be edited cross-platform yet — edit support varies; a short
- # confirmation preserves the audit trail the native edit gives).
- # Fire-and-forget: we are ON the read loop here (see
- # _send_lifecycle_ack) — awaiting the send self-deadlocks the
- # transport for the full outbound timeout.
- self._send_lifecycle_ack(
- chat_id, label, self._prompt_reply_metadata(event)
- )
- if count:
- self.resume_typing_for_chat(chat_id)
- elif kind == "slash_confirm":
- from tools import slash_confirm as slash_confirm_mod
-
- choice = (
- option_id if option_id in {"once", "always", "cancel"} else "cancel"
- )
- result_text = await slash_confirm_mod.resolve(
- session_key, str(state.get("confirm_id") or ""), choice
- )
- label = {
- "once": "✅ Approved once",
- "always": "🔒 Always approve",
- "cancel": "❌ Cancelled",
- }.get(choice, "Resolved")
- # Fire-and-forget (read-loop context — see _send_lifecycle_ack).
- self._send_lifecycle_ack(
- chat_id, label, self._prompt_reply_metadata(event)
- )
- if result_text:
- self._send_lifecycle_ack(
- chat_id,
- str(result_text),
- self._prompt_reply_metadata(event),
- )
- elif kind == "clarify":
- from tools.clarify_gateway import (
- mark_awaiting_text,
- resolve_gateway_clarify,
- )
-
- clarify_id = str(state.get("clarify_id") or "")
- if option_id == "other":
- mark_awaiting_text(clarify_id)
- self._send_lifecycle_ack(
- chat_id,
- "✏️ Type your answer:",
- self._prompt_reply_metadata(event),
- )
- else:
- choices = state.get("choices") or []
- try:
- idx = int(option_id[1:]) if option_id.startswith("c") else -1
- except ValueError:
- idx = -1
- if 0 <= idx < len(choices):
- resolve_gateway_clarify(clarify_id, str(choices[idx]))
- self._send_lifecycle_ack(
- chat_id,
- f"✅ {choices[idx]}",
- self._prompt_reply_metadata(event),
- )
- else:
- # Unmappable option: flip to text capture so the user
- # can answer by typing (never dead-end a clarify).
- mark_awaiting_text(clarify_id)
- else:
+ if handler is None:
logger.warning("relay prompt_response with unknown kind %r", kind)
+ else:
+ # Acks are fire-and-forget: we are ON the read loop here (see
+ # _send_lifecycle_ack) and awaiting a send would self-deadlock.
+ await handler(self, state, option_id, chat_id, self._prompt_reply_metadata(event))
except Exception: # noqa: BLE001 - a resolver failure must not kill the reader
logger.warning("relay prompt_response resolution failed", exc_info=True)
return True
+ async def _resolve_exec_approval(self, state, option_id, chat_id, ack_meta) -> None:
+ from tools.approval import resolve_gateway_approval
+
+ choice = option_id if option_id in {"once", "session", "always", "deny"} else "deny"
+ count = resolve_gateway_approval(str(state.get("session_key") or ""), choice)
+ label = {
+ "once": "✅ Approved once",
+ "session": "✅ Approved for session",
+ "always": "✅ Approved permanently",
+ "deny": "❌ Denied",
+ }.get(choice, "Resolved")
+ if not count:
+ label = "⌛ Approval expired — no command was waiting."
+ # In-channel ack preserves the audit trail the native edit gives (the
+ # connector's prompt message can't be edited cross-platform yet).
+ self._send_lifecycle_ack(chat_id, label, ack_meta)
+ if count:
+ self.resume_typing_for_chat(chat_id)
+
+ async def _resolve_slash_confirm(self, state, option_id, chat_id, ack_meta) -> None:
+ from tools import slash_confirm as slash_confirm_mod
+
+ choice = option_id if option_id in {"once", "always", "cancel"} else "cancel"
+ result_text = await slash_confirm_mod.resolve(
+ str(state.get("session_key") or ""), str(state.get("confirm_id") or ""), choice
+ )
+ label = {
+ "once": "✅ Approved once",
+ "always": "🔒 Always approve",
+ "cancel": "❌ Cancelled",
+ }.get(choice, "Resolved")
+ self._send_lifecycle_ack(chat_id, label, ack_meta)
+ if result_text:
+ self._send_lifecycle_ack(chat_id, str(result_text), ack_meta)
+
+ async def _resolve_clarify(self, state, option_id, chat_id, ack_meta) -> None:
+ from tools.clarify_gateway import mark_awaiting_text, resolve_gateway_clarify
+
+ clarify_id = str(state.get("clarify_id") or "")
+ if option_id == "other":
+ mark_awaiting_text(clarify_id)
+ self._send_lifecycle_ack(chat_id, "✏️ Type your answer:", ack_meta)
+ return
+ choices = state.get("choices") or []
+ try:
+ idx = int(option_id[1:]) if option_id.startswith("c") else -1
+ except ValueError:
+ idx = -1
+ if 0 <= idx < len(choices):
+ resolve_gateway_clarify(clarify_id, str(choices[idx]))
+ self._send_lifecycle_ack(chat_id, f"✅ {choices[idx]}", ack_meta)
+ else:
+ # Unmappable option: flip to text capture (never dead-end a clarify).
+ mark_awaiting_text(clarify_id)
+
def _send_lifecycle_ack(
self, chat_id: str, text: str, metadata: Dict[str, Any]
) -> None:
"""Fire-and-forget a prompt-lifecycle ack from read-loop context.
- Live finding round 2 (rc.4): _consume_prompt_response executes ON
- the transport read loop (inbound frame -> _handle_frame -> the
- _inbound handler). ``await self.send(...)`` there is a
- SELF-DEADLOCK: send() blocks on an outbound_result future that only
- the read loop can resolve — and the read loop is blocked inside
- this very handler. Every button tap wedged the transport for the
- full outbound timeout: draft appends starved (the observed frozen
- stream right after approving), sibling approval-card sends timed
- out into 'possibly-delivered' ambiguity, and the turn's seal timed
- out ambiguous -> plain-send fallback (the duplicate final).
-
- Acks are cosmetic by contract (the audit trail), so they ride a
- background task: the handler returns immediately, the read loop
- keeps consuming, and the ack's own result frame resolves normally.
- Failures are logged at debug — an undelivered ack must never break
- the reader or the turn. The task ref is retained (asyncio only
- weakly references tasks) and dropped on completion.
+ _consume_prompt_response executes ON the transport read loop; an
+ ``await self.send(...)`` there is a SELF-DEADLOCK (send() blocks on an
+ outbound_result future only the read loop can resolve) — every button
+ tap wedged the transport for the full outbound timeout. Acks are
+ cosmetic, so they ride a background task; failures log at debug. The
+ task ref is retained (asyncio only weakly references tasks).
"""
async def _ack() -> None:
@@ -3243,17 +2372,10 @@ class RelayAdapter(BasePlatformAdapter):
task.add_done_callback(self._lifecycle_ack_tasks.discard)
async def _notify_prompt_expired(self, event) -> None:
- """Tell the presser their prompt is no longer waiting.
-
- Only the OWNING gateway reaches this (siblings return earlier), so the
- user sees exactly one notice. Best-effort: a send failure here must
- not break the reader.
- """
+ """Tell the presser their prompt is no longer waiting (owning gateway only, best-effort)."""
chat_id = str(getattr(event.source, "chat_id", "") or "")
if not chat_id:
return
- # Fire-and-forget (read-loop context — see _send_lifecycle_ack):
- # _notify_prompt_expired is called from _consume_prompt_response too.
self._send_lifecycle_ack(
chat_id,
"⌛ That prompt is no longer waiting for an answer. "
@@ -3262,19 +2384,12 @@ class RelayAdapter(BasePlatformAdapter):
)
def _prompt_reply_metadata(self, event) -> Dict[str, Any]:
- """Thread/topic metadata so prompt acks land where the prompt lives.
-
- Marked as an INTERIM send (live finding, rc.4 staging): prompt
- lifecycle acks ("✅ Approved once", slash-confirm acks, expiry
- notices) are system messages that fire while the approval turn's
- OWN draft stream is open. Without the interim marker they carry
- only placement metadata — no per-turn identity — so send()'s
- single-open-stream fallback matched them to the live draft and
- sealed it with the ack text. Every later append then died on the
- post-seal tombstone (silent by design), freezing the visible
- stream mid-word, and the real turn-final fell through to a plain
- send: the observed 100%-reproducible stuck-draft + duplicate-final
- on approval turns. Interim sends bypass draft matching entirely.
+ """Thread metadata so prompt acks land where the prompt lives.
+
+ Marked INTERIM: acks fire while the approval turn's OWN draft stream
+ is open and carry only placement metadata, so send()'s
+ single-open-stream fallback sealed the live draft with the ack text
+ (frozen stream + duplicate final on every approval turn).
"""
meta: Dict[str, Any] = {"_interim_send": True}
thread_id = getattr(event.source, "thread_id", None)
@@ -3292,18 +2407,14 @@ class RelayAdapter(BasePlatformAdapter):
*,
remove: bool = False,
) -> bool:
- """Egress one `react` op; best-effort (False on any failure).
-
- Reactions are cosmetic by contract: a failure is logged at debug and
- never surfaces to the caller's flow (mirrors the native Discord
- adapter's _add_reaction posture).
- """
+ """Egress one `react` op; best-effort (False on any failure, logged at debug)."""
if self._transport is None or not self.descriptor.supports_op("react"):
return False
if not chat_id or not message_id:
return False
try:
- result = await self._transport.send_outbound(
+ result = await self._outbound(
+ chat_id,
{
"op": "react",
"chat_id": chat_id,
@@ -3312,7 +2423,6 @@ class RelayAdapter(BasePlatformAdapter):
"remove": remove,
"metadata": self._with_scope(chat_id, None),
},
- platform=self._platform_by_chat.get(str(chat_id)),
)
return bool(result.get("success"))
except Exception: # noqa: BLE001 - reactions are cosmetic
@@ -3321,21 +2431,13 @@ class RelayAdapter(BasePlatformAdapter):
async def on_processing_start(self, event) -> None:
"""Add the 👀 in-progress reaction (op-gated; silent no-op otherwise)."""
- message_id = getattr(event, "message_id", None) or getattr(
- event.source, "message_id", None
- )
- chat_id = getattr(event.source, "chat_id", None)
+ message_id, chat_id = _event_ids(event)
if message_id and chat_id:
await self._react(str(chat_id), str(message_id), "👀")
async def on_processing_complete(self, event, outcome) -> None:
"""Swap 👀 for ✅/❌ per outcome (op-gated; silent no-op otherwise)."""
- from gateway.platforms.base import ProcessingOutcome
-
- message_id = getattr(event, "message_id", None) or getattr(
- event.source, "message_id", None
- )
- chat_id = getattr(event.source, "chat_id", None)
+ message_id, chat_id = _event_ids(event)
if not (message_id and chat_id):
return
await self._react(str(chat_id), str(message_id), "👀", remove=True)
@@ -3354,24 +2456,21 @@ class RelayAdapter(BasePlatformAdapter):
"""Create a thread/topic under ``parent_chat_id`` via the connector.
One `thread_create` op covers Discord (channel thread), Telegram
- (forum topic), and Slack (named seed root message — threads there are
- message-anchored). Op-gated on the descriptor advertising
- `thread_create`; None on any failure/unavailability so the handoff
- watcher falls back to the parent channel — the same contract as the
- native adapters' create_handoff_thread.
+ (forum topic) and Slack (named seed root message). None on any
+ failure/unavailability so the handoff watcher falls back to the parent.
"""
if self._transport is None or not self.descriptor.supports_op("thread_create"):
return None
thread_name = (str(name or "").strip() or "handoff")[:100]
try:
- result = await self._transport.send_outbound(
+ result = await self._outbound(
+ str(parent_chat_id),
{
"op": "thread_create",
"chat_id": str(parent_chat_id),
"thread_name": thread_name,
"metadata": self._with_scope(str(parent_chat_id), None),
},
- platform=self._platform_by_chat.get(str(parent_chat_id)),
)
except Exception: # noqa: BLE001 - handoff falls back to the parent channel
logger.debug("relay thread_create transport failure", exc_info=True)
@@ -3397,20 +2496,12 @@ class RelayAdapter(BasePlatformAdapter):
) -> bool:
"""Best-effort thread rename via the connector's `thread_rename` op.
- The relay sibling of the native Discord adapter's rename_thread —
- called by the SAME semantic-rename lane (run.py
- _rename_discord_auto_thread_for_session_title), which fires only for
- sources carrying the connector-stamped auto-thread markers.
-
- No-clobber guard: prefer ``prefer_connector_created=True``, which asks
- the CONNECTOR to enforce the guard from ITS OWN created-name memory
- (only_if_connector_created) — the gateway no longer has to reproduce
- the thread's initial name byte-for-byte, which drifted on any
- normalization difference and silently declined every relay rename.
- ``only_if_current_name`` is the legacy string guard, kept for the
- native-marker lane and older connectors. ``parent_chat_id`` is the
- containing chat where the caller knows it (Telegram needs it);
- defaults to the thread id itself (Discord ignores chat_id).
+ Prefer ``prefer_connector_created=True``: the CONNECTOR enforces the
+ no-clobber guard from its own created-name memory, so the gateway need
+ not reproduce the initial name byte-for-byte (any normalization drift
+ silently declined every rename). ``only_if_current_name`` is the legacy
+ string guard for older connectors. ``parent_chat_id`` defaults to the
+ thread id (Telegram needs the containing chat; Discord ignores it).
"""
if self._transport is None or not self.descriptor.supports_op("thread_rename"):
return False
@@ -3446,3 +2537,11 @@ class RelayAdapter(BasePlatformAdapter):
)
return False
return True
+
+
+# prompt kind -> resolver (order-independent: kinds are distinct keys).
+_PROMPT_RESOLVERS = {
+ "exec_approval": RelayAdapter._resolve_exec_approval,
+ "slash_confirm": RelayAdapter._resolve_slash_confirm,
+ "clarify": RelayAdapter._resolve_clarify,
+}
diff --git a/gateway/relay/auth.py b/gateway/relay/auth.py
index b67715e20db..37c92510f8a 100644
--- a/gateway/relay/auth.py
+++ b/gateway/relay/auth.py
@@ -1,32 +1,18 @@
"""Gateway-side relay authentication primitives. EXPERIMENTAL.
-The connector⇄gateway channel is authenticated because a gateway may be
-customer-managed and internet-exposed (see the connector repo
-``docs/connector-gateway-auth-design.md``). This module is the **gateway half**
-of two HMAC schemes whose wire bytes must match the connector's TypeScript
-exactly:
-
-1. **WS upgrade auth** (gateway → connector): the gateway presents
- ``Authorization: Bearer <token>`` on the ``/relay`` WebSocket upgrade, where
- ``token = make_upgrade_token(gateway_id, secret)``. Mirrors the connector's
- ``relayAuthToken.ts`` ``makeToken`` (``src/core/relayAuthToken.ts``):
- ``base64url(f"{payload}:{exp}:{sig}")`` with
- ``sig = HMAC_SHA256(f"{payload}:{exp}", secret).hexdigest()`` and
- ``payload == gateway_id``.
-
-2. **Inbound delivery signature** (connector → gateway): the connector signs
- each inbound POST with the per-tenant *delivery key*, carried as
- ``x-relay-timestamp`` + ``x-relay-signature`` headers; the gateway verifies
- before accepting the event. Mirrors the connector's ``deliverySigning.ts``:
- ``sig = HMAC_SHA256(f"{ts}.{body_json}", key).hexdigest()`` over the EXACT
- request body bytes, with a replay-window skew check.
-
-Both schemes use a **multi-secret verify list** (primary first, then a secondary
-during a rotation window), exactly like ``api/src/handlers/stats_oauth.ts`` — so
-a secret rotation doesn't invalidate outstanding tokens.
-
-EXPERIMENTAL: may change without a deprecation cycle until ≥2 Class-1 platforms
-validate the relay contract.
+Gateway half of two HMAC schemes whose wire bytes must match the connector's
+TypeScript exactly:
+
+1. **WS upgrade auth** (gateway → connector): ``Authorization: Bearer <token>``
+ on the ``/relay`` upgrade, ``token = make_upgrade_token(gateway_id, secret)``.
+ Mirrors ``relayAuthToken.ts`` ``makeToken``: ``base64url(f"{payload}:{exp}:{sig}")``
+ with ``sig = HMAC_SHA256(f"{payload}:{exp}", secret).hexdigest()``.
+2. **Inbound delivery signature** (connector → gateway): ``x-relay-timestamp`` +
+ ``x-relay-signature`` headers, ``sig = HMAC_SHA256(f"{ts}.{body_json}", key)``
+ over the EXACT body bytes, with a replay-window skew check (``deliverySigning.ts``).
+
+Both verify against a multi-secret list (primary first, then a secondary during
+a rotation window) so a rotation doesn't invalidate outstanding tokens.
"""
from __future__ import annotations
@@ -37,31 +23,23 @@ import hmac
import time
from typing import Optional, Sequence
-# Header names the connector uses for inbound delivery signatures
-# (connector ``src/core/deliverySigning.ts`` — DELIVERY_TS_HEADER / SIG_HEADER).
+# Header names used by the connector's deliverySigning.ts.
DELIVERY_TS_HEADER = "x-relay-timestamp"
DELIVERY_SIG_HEADER = "x-relay-signature"
-# Default replay window for an inbound delivery signature (connector default).
-_DEFAULT_MAX_SKEW_SECONDS = 300
-# Default TTL for an upgrade token (connector ``makeUpgradeToken`` default).
-_DEFAULT_UPGRADE_TTL_SECONDS = 300
-
-
-def _hmac_hex(payload: str, secret: str) -> str:
- """HMAC-SHA256 hex digest of ``payload`` under ``secret`` (UTF-8)."""
- return hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest()
+_DEFAULT_MAX_SKEW_SECONDS = 300 # connector default replay window
+_DEFAULT_UPGRADE_TTL_SECONDS = 300 # connector makeUpgradeToken default
def sign(payload: str, secret: str) -> str:
- """HMAC-SHA256 hex digest — the connector's ``sign`` (relayAuthToken.ts)."""
- return _hmac_hex(payload, secret)
+ """HMAC-SHA256 hex digest (UTF-8) — the connector's ``sign``."""
+ return hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest()
def verify_signature(payload: str, sig_hex: str, secrets: Sequence[str]) -> bool:
- """Constant-time check that ``sig_hex`` is a valid HMAC of ``payload`` under
- ANY of ``secrets`` (rotation window). Length-mismatched candidates are
- skipped without a timing leak. Mirrors ``verifySignature``.
+ """Constant-time check of ``sig_hex`` against ANY of ``secrets`` (rotation window).
+
+ Length-mismatched candidates are skipped without a timing leak.
"""
try:
sig_buf = bytes.fromhex(sig_hex)
@@ -72,7 +50,7 @@ def verify_signature(payload: str, sig_hex: str, secrets: Sequence[str]) -> bool
for secret in secrets:
if not secret:
continue
- expected = bytes.fromhex(_hmac_hex(payload, secret))
+ expected = bytes.fromhex(sign(payload, secret))
if len(expected) != len(sig_buf):
continue
if hmac.compare_digest(sig_buf, expected):
@@ -81,40 +59,29 @@ def verify_signature(payload: str, sig_hex: str, secrets: Sequence[str]) -> bool
def make_token(payload: str, secret: str, ttl_seconds: int = 0) -> str:
- """Build a signed, optionally-expiring token — the connector's ``makeToken``.
+ """``base64url(f"{payload}:{exp}:{sig}")``; ``exp`` unix seconds (0 = never).
- ``base64url(f"{payload}:{exp}:{sig}")`` where ``exp`` is a unix-seconds
- expiry (0 = never) and ``sig = HMAC_SHA256(f"{payload}:{exp}", secret)``.
base64url is unpadded to match Node's ``Buffer.toString("base64url")``.
"""
exp = int(time.time()) + ttl_seconds if ttl_seconds > 0 else 0
signed = f"{payload}:{exp}"
- sig = _hmac_hex(signed, secret)
- raw = f"{signed}:{sig}".encode("utf-8")
+ raw = f"{signed}:{sign(signed, secret)}".encode("utf-8")
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
def make_upgrade_token(
gateway_id: str, secret: str, ttl_seconds: int = _DEFAULT_UPGRADE_TTL_SECONDS
) -> str:
- """The WS-upgrade bearer token a gateway sends: ``payload = gateway_id``.
-
- The connector peeks ``gateway_id`` (the payload head) to index its secret
- verify list, then verifies the signature against that gateway's stored
- secret(s). Mirrors the connector's ``makeUpgradeToken``.
- """
+ """WS-upgrade bearer: ``payload = gateway_id`` (the connector peeks it to index its verify list)."""
return make_token(gateway_id, secret, ttl_seconds)
def verify_token(token: str, secrets: Sequence[str]) -> Optional[str]:
- """Verify a token built by ``make_token``; return the payload or None.
+ """Verify a ``make_token`` token; return the payload or None.
- Splits from the right so a payload may itself contain colons (mirrors the
- connector's ``verifyToken``). Rejects an expired token and any signature
- that doesn't match a secret in the verify list.
+ Splits from the right so a payload may itself contain colons.
"""
try:
- # base64url decode with padding restored.
padded = token + "=" * (-len(token) % 4)
decoded = base64.urlsafe_b64decode(padded.encode("ascii")).decode("utf-8")
except (ValueError, TypeError):
@@ -130,13 +97,7 @@ def verify_token(token: str, secrets: Sequence[str]) -> Optional[str]:
payload = ":".join(parts[:-2])
if exp != 0 and int(time.time()) > exp:
return None
- signed = f"{payload}:{exp}"
- return payload if verify_signature(signed, sig, secrets) else None
-
-
-def _delivery_payload(ts: int, body_json: str) -> str:
- """Signed material for an inbound delivery: ``f"{ts}.{body_json}"``."""
- return f"{ts}.{body_json}"
+ return payload if verify_signature(f"{payload}:{exp}", sig, secrets) else None
def verify_delivery_signature(
@@ -150,11 +111,8 @@ def verify_delivery_signature(
) -> bool:
"""Verify a connector→gateway inbound delivery signature.
- ``body_json`` MUST be the exact request body bytes decoded as UTF-8 — the
- connector signs over the literal serialized body, so the gateway verifies
- over the literal received body (no re-serialization). Checks the timestamp
- is within ``max_skew_seconds`` of now and the HMAC matches any key in the
- rotation verify list. Mirrors the connector's ``verifyDeliverySignature``.
+ ``body_json`` MUST be the exact request body bytes decoded as UTF-8 (no
+ re-serialization — the connector signed the literal body).
"""
if not timestamp or not signature:
return False
@@ -165,4 +123,4 @@ def verify_delivery_signature(
current = now if now is not None else int(time.time())
if abs(current - ts) > max_skew_seconds:
return False
- return verify_signature(_delivery_payload(ts, body_json), signature, verify_keys)
+ return verify_signature(f"{ts}.{body_json}", signature, verify_keys)
diff --git a/gateway/relay/command_manifest.py b/gateway/relay/command_manifest.py
index 2a906311e9d..db1c8042bef 100644
--- a/gateway/relay/command_manifest.py
+++ b/gateway/relay/command_manifest.py
@@ -1,28 +1,20 @@
"""Gateway-declared slash-command manifest for the relay lane (Phase 4).
-The native Discord adapter registers its slash commands directly on the
-Discord command tree (`_register_slash_commands`,
-plugins/platforms/discord/adapter.py) — it holds the bot token. Over the
-relay the CONNECTOR holds the token, so the gateway DECLARES the same
-command set on its `hello` frame (`command_manifest`) and the connector
-reconciles Discord's global application-command registration against it
-(gateway-gateway `DiscordCommandRegistrar`: GET → diff → bulk PUT,
-idempotent, best-effort).
-
-This module is that declaration: the single source of truth for what the
-relay lane advertises. It MIRRORS the native tree — same names, same
-descriptions — so a user moving between a native-Discord deployment and a
-hosted/relay one sees the same command palette. Interactions come back over
-the passthrough plane and are normalized by
-RelayAdapter._discord_interaction_to_event into the same "/name args"
-COMMAND events the dispatcher already routes, so declaring a command here
-requires NO new handler — the dispatcher's existing slash surface is the
+Over the relay the CONNECTOR holds the Discord token, so the gateway DECLARES
+its command set on the ``hello`` frame (``command_manifest``) and the connector
+reconciles Discord's global registration against it (GET → diff → bulk PUT,
+idempotent, best-effort). This module is the single source of truth for that
+declaration and MIRRORS the native tree (`_register_slash_commands`,
+plugins/platforms/discord/adapter.py) — same names, same descriptions.
+Interactions come back over the passthrough plane and are normalized by
+RelayAdapter._discord_interaction_to_event into the same "/name args" COMMAND
+events the dispatcher already routes, so declaring a command here needs NO new
handler.
-Wire shape (per entry): {name, description, options?} where options rows are
-Discord option objects passed through verbatim. Names must satisfy
-Discord's CHAT_INPUT rules ([a-z0-9_-]{1,32}); the connector drops invalid
-entries (fail-open per entry, never the whole manifest).
+Wire shape per entry: {name, description, options?}; options rows are Discord
+option objects passed through verbatim. Names must satisfy Discord's CHAT_INPUT
+rules ([a-z0-9_-]{1,32}); the connector drops invalid entries (fail-open per
+entry, never the whole manifest).
"""
from __future__ import annotations
@@ -45,106 +37,61 @@ def _opt(name: str, description: str, *, choices: List[str] | None = None) -> Di
return row
+def _cmd(name: str, description: str, *options: Dict[str, Any]) -> Dict[str, Any]:
+ row: Dict[str, Any] = {"name": name, "description": description}
+ if options:
+ row["options"] = list(options)
+ return row
+
+
+_REASONING_CHOICES = [
+ "none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra",
+ "reset", "show", "hide",
+]
+
+
def build_relay_command_manifest() -> List[Dict[str, Any]]:
"""The relay lane's Discord slash-command manifest (native-tree mirror)."""
return [
- {"name": "new", "description": "Start a new conversation"},
- {"name": "reset", "description": "Reset your Hermes session"},
- {
- "name": "model",
- "description": "Show or change the model",
- "options": [_opt("name", "Model name. Leave empty to see current.")],
- },
- {
- "name": "reasoning",
- "description": "Show/change reasoning effort, or toggle showing it",
- "options": [
- _opt(
- "effort",
- "Level, reset, or show/hide. Leave empty to see current.",
- choices=[
- "none",
- "minimal",
- "low",
- "medium",
- "high",
- "xhigh",
- "max",
- "ultra",
- "reset",
- "show",
- "hide",
- ],
- )
- ],
- },
- {
- "name": "personality",
- "description": "Set a personality",
- "options": [_opt("name", "Personality name. Leave empty to list.")],
- },
- {"name": "retry", "description": "Retry your last message"},
- {"name": "undo", "description": "Remove the last exchange"},
- {"name": "status", "description": "Show Hermes session status"},
- {"name": "sethome", "description": "Set this chat as the home channel"},
- {"name": "stop", "description": "Stop the running Hermes agent"},
- {
- "name": "steer",
- "description": "Inject a message after the next tool call (no interrupt)",
- "options": [_opt("text", "What to tell the agent")],
- },
- {"name": "compress", "description": "Compress conversation context"},
- {
- "name": "title",
- "description": "Set or show the session title",
- "options": [_opt("text", "New title. Leave empty to show.")],
- },
- {
- "name": "resume",
- "description": "Resume a previously-named session",
- "options": [_opt("name", "Session title or id")],
- },
- {"name": "usage", "description": "Show token usage for this session"},
- {"name": "help", "description": "Show available commands"},
- {"name": "insights", "description": "Show usage insights and analytics"},
- {"name": "reload-mcp", "description": "Reload MCP servers from config"},
- {
- "name": "reload-skills",
- "description": "Re-scan skills for new or removed entries",
- },
- {"name": "voice", "description": "Toggle voice reply mode"},
- {"name": "update", "description": "Update Hermes Agent to the latest version"},
- {"name": "restart", "description": "Gracefully restart the Hermes gateway"},
- {
- "name": "approve",
- "description": "Approve a pending dangerous command",
- "options": [
- _opt("scope", "Approval scope", choices=["once", "session", "always", "all"])
- ],
- },
- {
- "name": "deny",
- "description": "Deny a pending dangerous command",
- "options": [_opt("reason", "Why (relayed to the agent)")],
- },
- {
- "name": "thread",
- "description": "Create a new thread and start a Hermes session in it",
- "options": [_opt("name", "Thread name")],
- },
- {
- "name": "queue",
- "description": "Queue a prompt for the next turn (doesn't interrupt)",
- "options": [_opt("text", "The prompt to queue")],
- },
- {
- "name": "bg",
- "description": "Run a prompt in a separate background session",
- "options": [_opt("text", "The prompt to run")],
- },
- {
- "name": "btw",
- "description": "Ask a side question about the current conversation",
- "options": [_opt("text", "The question to answer")],
- },
+ _cmd("new", "Start a new conversation"),
+ _cmd("reset", "Reset your Hermes session"),
+ _cmd("model", "Show or change the model",
+ _opt("name", "Model name. Leave empty to see current.")),
+ _cmd("reasoning", "Show/change reasoning effort, or toggle showing it",
+ _opt("effort", "Level, reset, or show/hide. Leave empty to see current.",
+ choices=_REASONING_CHOICES)),
+ _cmd("personality", "Set a personality",
+ _opt("name", "Personality name. Leave empty to list.")),
+ _cmd("retry", "Retry your last message"),
+ _cmd("undo", "Remove the last exchange"),
+ _cmd("status", "Show Hermes session status"),
+ _cmd("sethome", "Set this chat as the home channel"),
+ _cmd("stop", "Stop the running Hermes agent"),
+ _cmd("steer", "Inject a message after the next tool call (no interrupt)",
+ _opt("text", "What to tell the agent")),
+ _cmd("compress", "Compress conversation context"),
+ _cmd("title", "Set or show the session title",
+ _opt("text", "New title. Leave empty to show.")),
+ _cmd("resume", "Resume a previously-named session",
+ _opt("name", "Session title or id")),
+ _cmd("usage", "Show token usage for this session"),
+ _cmd("help", "Show available commands"),
+ _cmd("insights", "Show usage insights and analytics"),
+ _cmd("reload-mcp", "Reload MCP servers from config"),
+ _cmd("reload-skills", "Re-scan skills for new or removed entries"),
+ _cmd("voice", "Toggle voice reply mode"),
+ _cmd("update", "Update Hermes Agent to the latest version"),
+ _cmd("restart", "Gracefully restart the Hermes gateway"),
+ _cmd("approve", "Approve a pending dangerous command",
+ _opt("scope", "Approval scope", choices=["once", "session", "always", "all"])),
+ _cmd("deny", "Deny a pending dangerous command",
+ _opt("reason", "Why (relayed to the agent)")),
+ _cmd("thread", "Create a new thread and start a Hermes session in it",
+ _opt("name", "Thread name")),
+ _cmd("queue", "Queue a prompt for the next turn (doesn't interrupt)",
+ _opt("text", "The prompt to queue")),
+ _cmd("bg", "Run a prompt in a separate background session",
+ _opt("text", "The prompt to run")),
+ _cmd("btw", "Ask a side question about the current conversation",
+ _opt("text", "The question to answer")),
]
diff --git a/gateway/relay/descriptor.py b/gateway/relay/descriptor.py
index 2412ec94365..47a9d72f720 100644
--- a/gateway/relay/descriptor.py
+++ b/gateway/relay/descriptor.py
@@ -1,31 +1,16 @@
"""CapabilityDescriptor — the relay handshake payload. EXPERIMENTAL.
-The connector hands a ``CapabilityDescriptor`` to the gateway's ``RelayAdapter``
-at handshake time; it tells the adapter which platform it is fronting and which
-capabilities to advertise to the ``GatewayStreamConsumer`` (char limit,
-draft-streaming, edit/threading support, markdown dialect, length unit). It is
-the linchpin of the generalization: one gateway adapter serves Discord,
-Telegram, Matrix, Signal, ... without per-platform branching.
-
-EXPERIMENTAL: this schema MAY CHANGE without a deprecation cycle until at least
-two real Class-1 platforms have validated it. Evolution during the experimental
-phase is additive-only, gated by ``contract_version`` (see
-docs/relay-connector-contract.md).
-
-Field origins (most are a wire-serializable projection of ``PlatformEntry`` plus
-the per-instance capability methods on ``BasePlatformAdapter``):
-
-- ``max_message_length`` -> ``PlatformEntry.max_message_length`` / adapter
- ``MAX_MESSAGE_LENGTH`` attribute (read by stream_consumer).
-- ``len_unit`` -> selects which ``message_len_fn`` the adapter installs
- ("chars" = builtin len; "utf16" = Telegram-style UTF-16 code-unit counting).
-- ``supports_draft_streaming`` -> adapter ``supports_draft_streaming()`` probe.
-- ``supports_edit`` -> whether edit-based streaming is possible (Discord/
- Telegram yes; Signal/SMS no -> consumer degrades to one-message-per-segment).
-- ``supports_threads`` -> ``create_handoff_thread`` capability flag.
-- ``markdown_dialect`` -> presentation hint (e.g. "markdown_v2", "discord").
-- ``emoji`` / ``platform_hint`` / ``pii_safe`` -> ``PlatformEntry`` fields of the
- same name.
+The connector hands one to the gateway's ``RelayAdapter`` at handshake: which
+platform it fronts and which capabilities to advertise to the stream consumer
+(char limit, draft streaming, edit/threading, markdown dialect, length unit).
+One gateway adapter thus serves every platform without per-platform branching.
+
+Schema evolution is additive-only, gated by ``contract_version``
+(docs/relay-connector-contract.md). Most fields are a wire projection of
+``PlatformEntry`` (``max_message_length``, ``emoji``, ``platform_hint``,
+``pii_safe``, ``label``) plus the adapter capability probes
+(``supports_draft_streaming``, ``supports_edit``, ``supports_threads``,
+``len_unit`` → which ``message_len_fn`` the adapter installs).
"""
from __future__ import annotations
@@ -33,18 +18,14 @@ from __future__ import annotations
import json
from dataclasses import asdict, dataclass
-# Bump additively (never reinterpret an existing field) during the experimental
-# phase; a breaking change requires updating both repos in lockstep.
+# Bump additively (never reinterpret an existing field); a breaking change
+# requires updating both repos in lockstep.
CONTRACT_VERSION = 1
@dataclass(frozen=True)
class CapabilityDescriptor:
- """Immutable capability descriptor negotiated at relay handshake.
-
- Frozen so a descriptor cannot be mutated after handshake — the adapter
- advertises a fixed capability profile for the life of the connection.
- """
+ """Immutable capability profile negotiated at relay handshake (frozen: fixed for the connection)."""
contract_version: int
platform: str
@@ -55,92 +36,64 @@ class CapabilityDescriptor:
supports_threads: bool
markdown_dialect: str
len_unit: str # "chars" | "utf16"
- emoji: str = "\U0001f50c" # 🔌 default (matches PlatformEntry default)
+ emoji: str = "\U0001f50c" # 🔌 (matches PlatformEntry default)
platform_hint: str = ""
pii_safe: bool = False
- # Whether the connector can supply surrounding channel/group CONTEXT for an
- # addressed turn (Model A pull / Model B buffer, per platform). Optional +
- # defaults False so an older connector that never sends it is treated as
- # "no context" — additive within contract_version 1. from_json filters
- # unknown keys, so a connector sending this to an older gateway is safe too.
+ # All optional bits below default False/empty so an older connector that
+ # never sends them is treated as "not supported" — additive within
+ # contract_version 1 (from_json also drops unknown keys, so newer connectors
+ # are safe against older gateways).
+ # Connector can supply surrounding channel/group CONTEXT for an addressed turn.
supports_context: bool = False
- # Whether the connector's platform can host a FLAT continuable cron
- # surface (native Slack's ``cron_continuable_surface: in_channel``): the
- # brief posts top-level in the channel/DM and a plain reply continues the
- # job via the flat ``(platform, chat_id, None)`` session. The scheduler
- # fails safe to thread mode when False (D6 gate), so an older connector
- # that never sends this keeps today's thread behavior — additive within
- # contract_version 1.
+ # Platform can host a FLAT continuable cron surface (native Slack's
+ # ``cron_continuable_surface: in_channel``); the scheduler fails safe to
+ # thread mode when False (D6 gate).
supports_inchannel_continuable: bool = False
- # Whether the connector's platform sender can render block-level
- # formatting from raw markdown (Slack: rich_text lists, Block Kit
- # tables/markdown blocks). When True AND the operator enables the
- # rich_blocks/markdown_blocks knobs, the gateway stamps ``format_hints``
- # into outbound send/edit metadata; the connector renders blocks and
- # keeps the plain text as fallback. Default False — old connectors never
- # receive hints, old gateways never send them. Additive within
- # contract_version 1.
+ # Platform sender renders block-level formatting from raw markdown; when
+ # True AND the operator enables rich_blocks/markdown_blocks, the gateway
+ # stamps ``format_hints`` on outbound send/edit metadata.
supports_block_formatting: bool = False
- # Op-level capability discovery (Phase 1 parity): the outbound op names the
- # connector's sender for this platform actually implements (e.g.
- # ["send", "edit", "typing", "follow_up", "get_chat_info"]). Empty tuple =
- # the connector predates the field; callers MUST treat that as "legacy op
- # set" (send/edit/typing/follow_up) rather than "nothing supported", so an
- # old connector keeps working unchanged. Additive within contract_version 1.
- # Stored as a tuple so the frozen dataclass stays hashable/immutable.
+ # Outbound op names the connector implements for this platform. Empty =
+ # the connector predates the field; callers MUST treat that as LEGACY_OPS,
+ # not "nothing supported". Tuple keeps the frozen dataclass hashable.
supported_ops: tuple = ()
- # The op set every connector supported before ``supported_ops`` existed.
- # Used as the assumed capability set when a legacy connector sends no list.
+ # Assumed capability set when a legacy connector sends no supported_ops.
LEGACY_OPS = ("send", "edit", "typing", "follow_up")
def supports_op(self, op: str) -> bool:
- """Whether the connector advertises the outbound op ``op``.
-
- Fail-open for legacy connectors: an empty ``supported_ops`` means the
- connector predates op discovery, so assume the legacy op set (the four
- ops every connector implemented before the field existed). A NEW op
- (e.g. ``get_chat_info``) is therefore only True when explicitly
- advertised — exactly the discovery semantics Phase 1 needs: the gateway
- can probe capability without trying the op and parsing an error.
+ """Whether the connector advertises ``op`` (legacy set when none advertised).
+
+ A NEW op is therefore only True when explicitly advertised — capability
+ can be probed without trying the op and parsing an error.
"""
if not self.supported_ops:
return op in self.LEGACY_OPS
return op in self.supported_ops
def to_json(self) -> str:
- """Serialize to a compact, stable JSON string for the handshake frame."""
+ """Compact, stable JSON for the handshake frame."""
return json.dumps(asdict(self), sort_keys=True, ensure_ascii=False)
@classmethod
def from_json(cls, data: str) -> "CapabilityDescriptor":
- """Deserialize from a handshake JSON string.
+ """Deserialize a handshake JSON string; unknown keys ignored, missing keys default.
- Unknown keys are ignored (forward-compat: a newer connector may send
- fields this gateway does not know yet); missing optional keys fall back
- to dataclass defaults.
+ Trust-boundary normalization (malformed input never breaks the handshake):
+ a non-positive/garbage ``max_message_length`` ("no limit", or hostile)
+ maps to the documented 4096 default so the adapter can always chunk;
+ ``supported_ops`` becomes a tuple of non-empty strings, or () (legacy
+ fallback) when malformed.
"""
raw = json.loads(data)
known = {f for f in cls.__dataclass_fields__} # type: ignore[attr-defined]
filtered = {k: v for k, v in raw.items() if k in known}
- # Normalize the chunking bound at the trust boundary. A connector may
- # advertise max_message_length 0 ("no limit"), and a buggy/hostile one
- # may send 0 or a negative; either is a degenerate value that would flow
- # straight into the adapter's MAX_MESSAGE_LENGTH and truncate_message().
- # Map it to the documented 4096 default (docs/relay-connector-contract.md;
- # mirrors from_platform_entry's `or 4096`) so from_json never yields a
- # descriptor that can't chunk a real message.
if "max_message_length" in filtered:
try:
if int(filtered["max_message_length"]) <= 0:
filtered["max_message_length"] = 4096
except (TypeError, ValueError):
filtered["max_message_length"] = 4096
- # Normalize supported_ops at the trust boundary: JSON carries a list;
- # the frozen dataclass stores a tuple. Non-list/malformed values (or a
- # list holding non-strings) degrade to () — the legacy-op-set fallback —
- # rather than raising, matching the "malformed input never breaks the
- # handshake" posture above.
if "supported_ops" in filtered:
raw_ops = filtered["supported_ops"]
if isinstance(raw_ops, (list, tuple)):
@@ -164,17 +117,9 @@ class CapabilityDescriptor:
) -> "CapabilityDescriptor":
"""Project a ``gateway.platform_registry.PlatformEntry`` into a descriptor.
- Demonstrates the descriptor is a *subset/projection* of what
- ``PlatformEntry`` already encodes, not a parallel concept: ``label``,
- ``max_message_length``, ``emoji``, ``platform_hint``, ``pii_safe`` and
- the platform name come straight off the entry. The runtime capability
- bits that ``PlatformEntry`` does NOT encode (length unit, draft/edit/
- thread/markdown behavior) are supplied by the caller — in production
- the connector fills these from the live adapter's capability methods.
-
- ``max_message_length`` of 0 on a ``PlatformEntry`` means "no limit";
- we map that to the stream_consumer default of 4096 so the descriptor
- always carries a concrete chunking bound.
+ Runtime bits the entry does not encode (length unit, draft/edit/thread/
+ markdown) come from the caller. A ``max_message_length`` of 0 ("no
+ limit") maps to the stream_consumer default of 4096.
"""
max_len = getattr(entry, "max_message_length", 0) or 4096
return cls(
diff --git a/gateway/relay/media.py b/gateway/relay/media.py
index 986e743e815..c7caec87dd5 100644
--- a/gateway/relay/media.py
+++ b/gateway/relay/media.py
@@ -1,36 +1,25 @@
"""Relay media client — gateway↔connector media plane (Phase 2). EXPERIMENTAL.
-The relay wire contract carries media BY REFERENCE, never by value: an inbound
-event's ``media_urls`` name connector re-hosted attachments
-(``{connector}/relay/media/{id}``), and an outbound ``send_media`` op names a
-``source_url`` the connector resolves back to bytes. This module is the
-gateway-side HTTP client for that plane:
-
- - ``download(url)`` → GET a re-hosted attachment to a local temp file (the
- agent's vision/file tools consume LOCAL paths, matching every native
- adapter's inbound media behaviour).
- - ``upload(path)`` → POST local file bytes to ``/relay/media``; returns the
- ``/relay/media/{id}`` reference for a subsequent ``send_media`` op. This is
- how a locally-generated artifact (image_generate output, TTS voice note,
- a document) crosses to the connector WITHOUT the gateway needing a public
- URL.
-
-Both requests present the SAME per-gateway signed bearer the WS upgrade uses
-(``make_upgrade_token``, gateway/relay/auth.py — the channel authenticator; the
-connector authenticates it with ``authenticateGatewayBearer`` on the mirrored
-routes). Uploads are
-per-gateway-owned on the connector (only this gateway can reference the id
-back); downloads accept both this gateway's uploads and connector ingest
-re-hosts.
-
-Transport is stdlib ``urllib`` run in a thread executor (the same dependency
-posture as ``_post_provision`` — the relay lane adds no HTTP client deps).
-EXPERIMENTAL: may change without a deprecation cycle (docs/relay-connector-contract.md).
+The relay wire carries media BY REFERENCE: inbound ``media_urls`` name
+connector re-hosts (``{connector}/relay/media/{id}``) and an outbound
+``send_media`` op names a ``source_url`` the connector resolves back to bytes.
+
+ - ``download(url)`` → GET a re-hosted attachment to a local temp file (the
+ agent's vision/file tools consume LOCAL paths, like every native adapter).
+ - ``upload(path)`` → POST local bytes to ``/relay/media``; returns the
+ ``/relay/media/{id}`` reference for a subsequent ``send_media`` op, so a
+ locally-generated artifact crosses without the gateway needing a public URL.
+
+Both present the same per-gateway signed bearer the WS upgrade uses
+(``make_upgrade_token``). Uploads are per-gateway-owned on the connector;
+downloads accept this gateway's uploads and connector ingest re-hosts.
+Transport is stdlib ``urllib`` in a thread executor (no HTTP client deps).
"""
from __future__ import annotations
import asyncio
+import json
import logging
import mimetypes
import os
@@ -44,19 +33,19 @@ from gateway.relay.auth import make_upgrade_token
logger = logging.getLogger(__name__)
-# Mirror the connector's MEDIA_MAX_BYTES (mediaStore.ts) so an oversized local
-# artifact fails fast here instead of round-tripping to a connector 413.
+# Mirrors the connector's MEDIA_MAX_BYTES (mediaStore.ts): fail fast here
+# instead of round-tripping to a connector 413.
MEDIA_MAX_BYTES = 25 * 1024 * 1024
_REQUEST_TIMEOUT_S = 30.0
+# Discord's CDN (and other public hosts) 403 urllib's default UA, which
+# silently killed every CDN pass-through download. Always send a descriptive UA.
+_MEDIA_USER_AGENT = "HermesAgent-Relay/1.0 (+https://github.com/NousResearch/hermes-agent)"
-def media_base_url(relay_dial_url: str) -> str:
- """Map the ``ws(s)://…/relay`` dial URL to the ``http(s)://…`` base.
- Same host derivation as ``_provision_url`` (gateway/relay/__init__.py):
- scheme ws→http / wss→https, trailing ``/relay`` stripped.
- """
+def media_base_url(relay_dial_url: str) -> str:
+ """Map the ``ws(s)://…/relay`` dial URL to the ``http(s)://…`` base (same derivation as ``_provision_url``)."""
raw = (relay_dial_url or "").strip().rstrip("/")
if raw.startswith("ws://"):
raw = "http://" + raw[len("ws://") :]
@@ -67,14 +56,6 @@ def media_base_url(relay_dial_url: str) -> str:
return raw
-# Discord's CDN (and other public hosts) reject urllib's default
-# ``Python-urllib/x.y`` User-Agent with HTTP 403 — which silently killed EVERY
-# Discord CDN pass-through download (voice notes, images, documents): the
-# localizer kept the raw URL and downstream consumers then tried to open a URL
-# as a file path. Always send a descriptive UA.
-_MEDIA_USER_AGENT = "HermesAgent-Relay/1.0 (+https://github.com/NousResearch/hermes-agent)"
-
-
class RelayMediaClient:
"""Authenticated client for the connector's ``/relay/media`` routes."""
@@ -107,12 +88,7 @@ class RelayMediaClient:
mime: Optional[str] = None,
filename: Optional[str] = None,
) -> Optional[str]:
- """POST local file bytes to ``/relay/media``; return the reference URL.
-
- Returns the ``{base}/relay/media/{id}`` reference for a ``send_media``
- op's ``source_url``, or None on any failure (callers fall back to their
- pre-media behaviour — media delivery is best-effort by design).
- """
+ """POST local file bytes to ``/relay/media``; return the reference URL or None on any failure."""
if not self.enabled:
return None
path = Path(file_path)
@@ -146,8 +122,6 @@ class RelayMediaClient:
req = urllib.request.Request(url, data=data, headers=headers, method="POST")
try:
with urllib.request.urlopen(req, timeout=_REQUEST_TIMEOUT_S) as resp:
- import json
-
body = json.loads(resp.read().decode("utf-8"))
media_id = body.get("id")
if not media_id:
@@ -160,12 +134,10 @@ class RelayMediaClient:
return await asyncio.get_running_loop().run_in_executor(None, _post)
async def download(self, url: str, *, suggested_name: Optional[str] = None) -> Optional[str]:
- """GET a re-hosted attachment to a local temp file; return its path.
+ """GET an attachment to a local temp file; return its path or None on any failure.
- Presents the per-gateway bearer for connector re-host URLs; plain
- public URLs (e.g. a Discord CDN pass-through) are fetched without it.
- Returns None on any failure (the event then keeps the remote URL, and
- downstream consumers that need a local file skip it — best-effort).
+ The bearer is presented only for connector re-host URLs; public URLs
+ (e.g. a Discord CDN pass-through) are fetched without it.
"""
if not url:
return None
@@ -187,9 +159,8 @@ class RelayMediaClient:
data = resp.read(MEDIA_MAX_BYTES + 1)
if not data or len(data) > MEDIA_MAX_BYTES:
return None
- # Extension: prefer the response's content-disposition /
- # suggested name, fall back to the mime type, then .bin —
- # vision/file tools sniff by extension.
+ # Extension matters: vision/file tools sniff by extension.
+ # Prefer suggested/content-disposition name, then mime, then .bin.
name = suggested_name or ""
if not name:
cd = resp.headers.get("Content-Disposition") or ""
diff --git a/gateway/session.py b/gateway/session.py
index b11a83faa65..2c0857ab8c3 100644
--- a/gateway/session.py
+++ b/gateway/session.py
@@ -17,7 +17,7 @@ import threading
import uuid
from pathlib import Path
from datetime import datetime, timedelta
-from dataclasses import dataclass, field, replace
+from dataclasses import dataclass, field, fields, replace
from typing import Dict, List, Optional, Any
logger = logging.getLogger(__name__)
@@ -36,31 +36,41 @@ def _now() -> datetime:
return datetime.now()
-# Default auto-continue freshness window in seconds (1 hour). A session
-# interrupted by a restart is only auto-resumed — and only returned by
-# ``get_or_create_session`` — while it stays within this window of when
-# ``resume_pending`` was marked. ``gateway/run.py`` bridges
-# ``config.yaml`` ``agent.gateway_auto_continue_freshness`` into
-# ``HERMES_AUTO_CONTINUE_FRESHNESS`` at startup.
+def _new_session_id(now: datetime) -> str:
+ return f"{now.strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}"
+
+
+def _iso(dt: Optional[datetime]) -> Optional[str]:
+ return dt.isoformat() if dt else None
+
+
+def _parse_iso(value) -> Optional[datetime]:
+ """``datetime.fromisoformat`` that returns None for empty/malformed input."""
+ if not value:
+ return None
+ try:
+ return datetime.fromisoformat(value)
+ except (TypeError, ValueError):
+ return None
+
+
+# Default auto-continue freshness window (1 hour): a restart-interrupted
+# session is only auto-resumed while within this window of when
+# ``resume_pending`` was marked. ``gateway/run.py`` bridges config.yaml
+# ``agent.gateway_auto_continue_freshness`` into the env var at startup.
_AUTO_CONTINUE_FRESHNESS_SECS_DEFAULT = 60 * 60
def auto_continue_freshness_window() -> float:
- """Return the configured auto-continue freshness window in seconds.
-
- Single source of truth for both the resume scheduler (``gateway/run.py``)
- and the routing-time zombie gate in ``get_or_create_session``. Reads
- ``HERMES_AUTO_CONTINUE_FRESHNESS`` (bridged from ``config.yaml``
- ``agent.gateway_auto_continue_freshness`` at gateway startup) and falls
- back to the module default when unset or malformed. A non-positive value
- disables the freshness gate (restores the pre-fix "always fresh" behaviour
- for users who want to opt out).
+ """Auto-continue freshness window in seconds (single source of truth for
+ the resume scheduler and the routing-time zombie gate).
+
+ Reads ``HERMES_AUTO_CONTINUE_FRESHNESS``; falls back to the default when
+ unset or malformed. Non-positive disables the gate.
"""
raw = os.environ.get("HERMES_AUTO_CONTINUE_FRESHNESS")
- if raw is None or raw == "":
- return float(_AUTO_CONTINUE_FRESHNESS_SECS_DEFAULT)
try:
- return float(raw)
+ return float(raw) if raw else float(_AUTO_CONTINUE_FRESHNESS_SECS_DEFAULT)
except (TypeError, ValueError):
return float(_AUTO_CONTINUE_FRESHNESS_SECS_DEFAULT)
@@ -106,64 +116,36 @@ from utils import atomic_replace
from agent.turn_context import extract_api_content_sidecar
import contextlib
-# Session keys/ids flow into filesystem paths downstream (e.g.
-# ``sessions_dir / f"{session_id}.json"`` in hermes_state, request-dump
-# filenames in agent_runtime_helpers). Any value that could escape the
-# sessions directory as a path must be rejected at the entry boundary.
-# Rejects: parent traversal (``..``), a path separator anywhere (``/`` or
-# ``\``, so a non-leading Windows separator can't slip through), and a
-# leading Windows drive letter (``C:``). Legitimate session keys are
-# colon-delimited multi-segment ids (``agent:main:<platform>:...``) and
-# never contain these, so there are no false positives in practice.
-def _is_path_unsafe(value: object) -> bool:
- """Return True if ``value`` could traverse outside the sessions dir."""
- if not value:
- return False
- s = str(value)
- if ".." in s or "/" in s or "\\" in s:
- return True
- # Leading Windows drive path, e.g. "C:\\..." or "d:/...". A bare "x:"
- # with no following separator isn't a usable absolute path, and the
- # separator forms are already caught above — but keep an explicit guard
- # for the drive-letter prefix in case a separator was normalized away.
- return len(s) >= 2 and s[0].isalpha() and s[1] == ":"
-
+def _is_path_unsafe(value: object, *, strict: bool = True) -> bool:
+ """True if ``value`` could traverse outside the sessions dir.
-def _is_session_key_unsafe(value: object) -> bool:
- """Return True if ``value`` could be a real traversal vector in a session_key.
-
- ``session_key`` is a *logical* routing key (e.g.
- ``agent:main:google_chat:group:spaces/<id>``) — it never touches the
- filesystem, so the strict separator-rejecting guard from
- ``_is_path_unsafe`` is over-broad: it falsely rejects Google Chat
- resource names (``spaces/<id>``, ``spaces/<id>/threads/<id>``) and any
- other platform whose native IDs legitimately contain ``/``.
-
- The relaxed check only blocks genuine traversal: parent-dir ``..``,
- a *leading* path separator (``/``/``\\``, which would make the key
- absolute on disk if it ever were written), and a leading Windows
- drive letter. Interior ``/`` is allowed.
+ Session ids become filenames (``sessions_dir / f"{session_id}.json"``), so
+ the strict form rejects ``..``, ANY path separator, and a leading Windows
+ drive letter. The relaxed form (``strict=False``) is for *logical* session
+ keys, where interior ``/`` is legitimate (Google Chat
+ ``spaces/<id>/threads/<id>``): only a *leading* separator is rejected.
"""
if not value:
return False
s = str(value)
if ".." in s:
return True
- if s.startswith("/") or s.startswith("\\"):
+ if strict and ("/" in s or "\\" in s):
+ return True
+ if not strict and (s.startswith("/") or s.startswith("\\")):
return True
return len(s) >= 2 and s[0].isalpha() and s[1] == ":"
+def _is_session_key_unsafe(value: object) -> bool:
+ """Relaxed traversal check for a logical session_key."""
+ return _is_path_unsafe(value, strict=False)
+
+
@dataclass
class SessionSource:
- """
- Describes where a message originated from.
-
- This information is used to:
- 1. Route responses back to the right place
- 2. Inject context into the system prompt
- 3. Track origin for cron job delivery
- """
+ """Where a message originated: routes responses, feeds the system-prompt
+ context block, and records origin for cron delivery."""
platform: Platform
chat_id: str
chat_name: Optional[str] = None
@@ -176,89 +158,71 @@ class SessionSource:
chat_id_alt: Optional[str] = None # Signal group internal ID
is_bot: bool = False # True when the message author is a bot/webhook (Discord)
# Platform-neutral SCOPE discriminator (Discord guild / Slack workspace /
- # Matrix server). Drives server/workspace isolation + the relay δ/ε/ζ gate.
- # Wire migration (D-Q2.5): `scope_id` is the canonical name; `guild_id` is a
- # deprecated legacy alias kept during the cross-repo dual-read/dual-write
- # overlap. Both are written by to_dict and read by from_dict (scope_id wins);
- # the `guild_id` alias is dropped in a follow-up once both repos deploy.
+ # Matrix server); drives server/workspace isolation. `scope_id` is
+ # canonical; `guild_id` is a deprecated alias kept during the cross-repo
+ # dual-read/dual-write overlap (both written, scope_id wins on read).
scope_id: Optional[str] = None
- guild_id: Optional[str] = None # @deprecated legacy alias for scope_id (D-Q2.5)
+ guild_id: Optional[str] = None # @deprecated legacy alias for scope_id
parent_chat_id: Optional[str] = None # Parent channel when chat_id refers to a thread
message_id: Optional[str] = None # ID of the triggering message (for pin/reply/react)
role_authorized: bool = False # True when adapter granted access via role (not user ID)
- # Profile this inbound message is routed to in a multiplexing gateway
- # (from the /p/<profile>/ URL prefix or per-credential adapter ownership).
- # None => the gateway's active/default profile. Drives both session-key
- # namespacing and the per-turn config/credential scope.
+ # Profile this message is routed to in a multiplexing gateway (None =>
+ # active/default). Drives session-key namespacing and per-turn scope.
profile: Optional[str] = None
# Transport-local fail-closed signal for an explicit profile route whose
# target is not served. Excluded from repr/equality and wire serialization.
profile_route_rejected: bool = field(default=False, repr=False, compare=False)
- # Discord auto-thread metadata. Newly auto-created Discord threads start
- # with a fast placeholder title from the raw message, then the gateway can
- # rename them after the first agent turn using the generated session title.
- # Keep this explicit so pre-existing or human-renamed threads are not
- # mistaken for safe rename targets.
+ # Discord auto-thread metadata: explicit so pre-existing or human-renamed
+ # threads are never mistaken for safe rename targets.
auto_thread_created: bool = False
auto_thread_initial_name: Optional[str] = None
- # Discord auto-thread session-continuity signal. Set by the connector on an
- # inbound CHANNEL message (no thread_id yet) that its auto-thread policy WILL
- # deliver into a newly-created thread. A Discord thread created from a message
- # reuses that message's id as the thread id, so the connector knows the id
- # before the thread exists. The gateway keys the session on this so a
- # channel message and its thread follow-ups share ONE session: the channel
- # message INITIATES it (keyed on the prospective thread id), and later
- # messages arriving in that thread (real thread_id == this value) CONTINUE
- # it. Without this, every channel message collapses into one parent-channel
- # session and only the first auto-thread ever gets an auto-title/rename.
+ # Discord auto-thread continuity: set by the connector on a CHANNEL message
+ # (no thread_id yet) that WILL be delivered into a new thread whose id ==
+ # this message id. Keying the session on it makes the initiating channel
+ # message and later in-thread follow-ups share ONE session.
prospective_thread_id: Optional[str] = None
- # Internal, wire-INVISIBLE trust signal: True when this event was delivered
- # to the gateway over the per-instance-authenticated relay WebSocket (the
- # Team Gateway connector). The connector authenticates the gateway's socket
- # with a per-instance secret and resolves owner-only author bindings BEFORE
- # delivering, so a relay-delivered event is already authorized as this
- # instance's bound user. ``platform`` carries the UNDERLYING platform
- # (e.g. ``discord``) for session-keying/egress, NOT ``relay`` — so authz
- # must key the upstream-trust decision off THIS flag, not off ``platform``.
- # Set locally by the relay transport (``ws_transport._event_from_wire``);
- # deliberately excluded from ``to_dict``/``from_dict`` so a peer can never
- # forge it across the wire or have it restored from persistence.
+ # Wire-INVISIBLE trust signal: True when delivered over the per-instance
+ # authenticated relay WebSocket, whose connector already resolved
+ # owner-only author bindings. ``platform`` carries the UNDERLYING platform
+ # (not ``relay``), so authz must key upstream trust off THIS flag.
+ # Excluded from to_dict/from_dict so a peer can never forge or persist it.
delivered_via_upstream_relay: bool = False
def __post_init__(self) -> None:
- # D-Q2.5 dual-field reconciliation: `scope_id` is canonical, `guild_id`
- # is the deprecated alias. Mirror whichever was provided onto the other
- # (scope_id wins on conflict) so internal readers of EITHER field see the
- # same value during the cross-repo wire migration overlap.
+ # Mirror scope_id/guild_id onto each other (scope_id wins) so readers
+ # of EITHER field agree during the wire migration overlap.
if self.scope_id is None and self.guild_id is not None:
self.scope_id = self.guild_id
elif self.scope_id is not None:
self.guild_id = self.scope_id
+ @staticmethod
+ def _describe(chat_type: str, user_label: str, chat_label: str) -> str:
+ if chat_type == "dm":
+ return f"DM with {user_label}"
+ if chat_type == "group":
+ return f"group: {chat_label}"
+ if chat_type == "channel":
+ return f"channel: {chat_label}"
+ return chat_label
+
@property
def description(self) -> str:
"""Human-readable description of the source."""
if self.platform == Platform.LOCAL:
return "CLI terminal"
-
- parts = []
- if self.chat_type == "dm":
- parts.append(f"DM with {self.user_name or self.user_id or 'user'}")
- elif self.chat_type == "group":
- parts.append(f"group: {self.chat_name or self.chat_id}")
- elif self.chat_type == "channel":
- parts.append(f"channel: {self.chat_name or self.chat_id}")
- else:
- parts.append(self.chat_name or self.chat_id)
-
+ parts = [self._describe(
+ self.chat_type,
+ self.user_name or self.user_id or "user",
+ self.chat_name or self.chat_id,
+ )]
if self.thread_id:
parts.append(f"thread: {self.thread_id}")
-
return ", ".join(parts)
-
+
def to_dict(self) -> Dict[str, Any]:
d = {
"platform": self.platform.value,
@@ -270,30 +234,22 @@ class SessionSource:
"thread_id": self.thread_id,
"chat_topic": self.chat_topic,
}
- if self.user_id_alt:
- d["user_id_alt"] = self.user_id_alt
- if self.chat_id_alt:
- d["chat_id_alt"] = self.chat_id_alt
- # D-Q2.5 dual-write: emit BOTH the canonical `scope_id` and the
- # deprecated `guild_id` alias (mirrored in __post_init__) so a connector
- # on either side of the migration resolves the scope. Drop `guild_id`
- # in the follow-up once both repos are on `scope_id`.
+ def _optional(*names: str) -> None:
+ for name in names:
+ value = getattr(self, name)
+ if value:
+ d[name] = value
+
+ _optional("user_id_alt", "chat_id_alt")
+ # Dual-write scope_id + deprecated guild_id alias during the migration.
scope = self.scope_id if self.scope_id is not None else self.guild_id
if scope:
d["scope_id"] = scope
d["guild_id"] = scope
- if self.parent_chat_id:
- d["parent_chat_id"] = self.parent_chat_id
- if self.message_id:
- d["message_id"] = self.message_id
- if self.profile:
- d["profile"] = self.profile
+ _optional("parent_chat_id", "message_id", "profile")
if self.auto_thread_created:
d["auto_thread_created"] = True
- if self.auto_thread_initial_name:
- d["auto_thread_initial_name"] = self.auto_thread_initial_name
- if self.prospective_thread_id:
- d["prospective_thread_id"] = self.prospective_thread_id
+ _optional("auto_thread_initial_name", "prospective_thread_id")
return d
@classmethod
@@ -309,8 +265,6 @@ class SessionSource:
chat_topic=data.get("chat_topic"),
user_id_alt=data.get("user_id_alt"),
chat_id_alt=data.get("chat_id_alt"),
- # D-Q2.5 dual-read: prefer the canonical `scope_id`, fall back to the
- # deprecated `guild_id` alias (a peer not yet migrated still sends it).
scope_id=data.get("scope_id", data.get("guild_id")),
parent_chat_id=data.get("parent_chat_id"),
message_id=data.get("message_id"),
@@ -324,14 +278,7 @@ class SessionSource:
@dataclass
class SessionContext:
- """
- Full context for a session, used for dynamic system prompt injection.
-
- The agent receives this information to understand:
- - Where messages are coming from
- - What platforms are available
- - Where it can deliver scheduled task outputs
- """
+ """Full session context for dynamic system prompt injection."""
source: SessionSource
connected_platforms: List[Platform]
home_channels: Dict[Platform, HomeChannel]
@@ -353,8 +300,8 @@ class SessionContext:
"shared_multi_user_session": self.shared_multi_user_session,
"session_key": self.session_key,
"session_id": self.session_id,
- "created_at": self.created_at.isoformat() if self.created_at else None,
- "updated_at": self.updated_at.isoformat() if self.updated_at else None,
+ "created_at": _iso(self.created_at),
+ "updated_at": _iso(self.updated_at),
}
@@ -364,33 +311,19 @@ _PII_SAFE_PLATFORMS = frozenset({
Platform.TELEGRAM,
Platform.BLUEBUBBLES,
})
-"""Platforms where user IDs can be safely redacted (no in-message mention system
-that requires raw IDs). Discord is excluded because mentions use ``<@user_id>``
-and the LLM needs the real ID to tag users."""
+"""Platforms where user IDs can be redacted (no ``<@user_id>``-style mention
+system that needs raw IDs — which is why Discord is excluded)."""
def _slack_tools_loaded() -> bool:
"""True iff the agent will actually have Slack tools this session.
- Two independent paths grant Slack capability:
- 1. Native `slack` toolset enabled via `hermes tools` (opt-in, default
- OFF) AND `SLACK_BOT_TOKEN` set — the tool's `check_fn` gates on it
- at registry time, so config alone isn't enough.
- 2. An MCP server that has ACTUALLY registered tools into the live
- registry (tools/mcp_tool.get_registered_mcp_server_names()), whose
- name suggests Slack. This is the real, availability-filtered
- signal (post-connection, post include/exclude filtering) rather
- than just what's listed in config.yaml -- a configured-but-
- unconnected or zero-tool MCP server must not claim capability.
- Named MCP servers are process-wide (one gateway connects each MCP
- server once, not per-session), so this check is intentionally NOT
- scoped further per-session -- unlike the earlier get_all_tool_names()
- approach this replaces, which conflated ALL built-in tool names
- process-wide, this only inspects the small, purpose-built MCP
- server-name map.
-
- Returns False (safe default — keeps the stale-API disclaimer) on any
- error so a bad config can never silently promise tools the agent lacks.
+ Either (1) the native `slack` toolset is enabled for the platform AND
+ `SLACK_BOT_TOKEN` is set (the tool's `check_fn` gates on it), or (2) an
+ MCP server whose name suggests Slack has ACTUALLY registered tools into
+ the live registry (configured-but-unconnected servers don't count; MCP
+ servers are process-wide, so this is intentionally not per-session).
+ Returns False on any error so a bad config never promises missing tools.
"""
try:
from tools.mcp_tool import get_registered_mcp_server_names
@@ -400,16 +333,12 @@ def _slack_tools_loaded() -> bool:
pass
# Presence check through the profile secret scope: under multiplex the
- # process env may carry another profile's token (Slack pattern for the
- # unscoped default-profile path).
+ # process env may carry another profile's token.
try:
- from agent.secret_scope import UnscopedSecretError, get_secret
+ from agent.secret_scope import get_secret
- try:
- _slack_token = get_secret("SLACK_BOT_TOKEN") or ""
- except UnscopedSecretError:
- _slack_token = os.environ.get("SLACK_BOT_TOKEN") or ""
- except Exception:
+ _slack_token = get_secret("SLACK_BOT_TOKEN") or ""
+ except Exception: # includes UnscopedSecretError
_slack_token = os.environ.get("SLACK_BOT_TOKEN") or ""
if not _slack_token.strip():
return False
@@ -417,10 +346,8 @@ def _slack_tools_loaded() -> bool:
from hermes_cli.config import load_config
from hermes_cli.tools_config import _get_platform_tools
cfg = load_config()
- # include_default_mcp_servers=True (the default) so a Slack MCP
- # server that's enabled by default for this platform (not
- # explicitly listed) is also counted, in addition to the native
- # 'slack' toolset.
+ # include_default_mcp_servers defaults True so a default-enabled Slack
+ # MCP server counts too.
enabled = _get_platform_tools(cfg, "slack")
return "slack" in enabled
except Exception:
@@ -428,18 +355,9 @@ def _slack_tools_loaded() -> bool:
def _discord_tools_loaded() -> bool:
- """True iff the agent will actually have Discord tools this session.
-
- Two conditions must hold:
- 1. The `discord` or `discord_admin` toolset is enabled for the
- Discord platform via `hermes tools` (opt-in, default OFF).
- 2. `DISCORD_BOT_TOKEN` is set — the tool's `check_fn` gates on it
- at registry time, so the toolset being enabled in config is not
- enough if the token isn't configured.
-
- Returns False (safe default — keeps the stale-API disclaimer) on any
- error so a bad config can't silently promise tools the agent lacks.
- """
+ """True iff the agent will actually have Discord tools this session:
+ `discord`/`discord_admin` toolset enabled AND `DISCORD_BOT_TOKEN` set
+ (the tool's `check_fn` gates on it). False on any error."""
try:
from agent.secret_scope import get_secret
from hermes_cli.config import load_config
@@ -469,16 +387,11 @@ def _format_untrusted_prompt_value(value: Any, *, max_chars: int = _MAX_PROMPT_M
def neutralize_untrusted_inline_text(value: Any, *, max_chars: int = _MAX_PROMPT_METADATA_CHARS) -> str:
"""Collapse untrusted text to a single inert line, unquoted.
- Sibling of :func:`_format_untrusted_prompt_value` for call sites that must
- preserve the surrounding format (e.g. an inline ``[Name] message turn``
- prefix) instead of a standalone ``**Label:** "value"`` line — JSON-quoting
- would visibly change a well-behaved value's rendering there.
-
- Embedded newlines are the injection vector both helpers guard against:
- they let an untrusted display name masquerade as a new markdown section
- (a fake heading, an "## Override" block) inside content the model reads
- every turn. Collapsing them to a single space keeps a normal value
- byte-identical while making a hostile one visually inert.
+ Sibling of :func:`_format_untrusted_prompt_value` for inline call sites
+ (e.g. a ``[Name]`` turn prefix) where JSON-quoting would visibly change
+ rendering. Embedded newlines are the injection vector: they let a display
+ name masquerade as a new markdown section. Collapsing them keeps a normal
+ value byte-identical while making a hostile one inert.
"""
text = str(value).replace("\r\n", "\n").replace("\r", "\n").replace("\n", " ")
text = "".join(ch if ch >= " " or ch == "\t" else " " for ch in text)
@@ -493,22 +406,12 @@ def build_session_context_prompt(
*,
redact_pii: bool = False,
) -> str:
+ """Build the "Current Session Context" system prompt section.
+
+ With *redact_pii* and a PII-safe platform (builtin set or plugin registry
+ ``pii_safe``), user/chat IDs are replaced with deterministic hashes for the
+ LLM only; routing keeps the originals in SessionSource.
"""
- Build the dynamic system prompt section that tells the agent about its context.
-
- This is injected into the system prompt so the agent knows:
- - Where messages are coming from
- - What platforms are connected
- - Where it can deliver scheduled task outputs
-
- When *redact_pii* is True **and** the source platform is in
- ``_PII_SAFE_PLATFORMS``, phone numbers are stripped and user/chat IDs
- are replaced with deterministic hashes before being sent to the LLM.
- Platforms like Discord are excluded because mentions need real IDs.
- Routing still uses the original values (they stay in SessionSource).
- """
- # Only apply redaction on platforms where IDs aren't needed for mentions.
- # Check both the hardcoded set (builtins) and the plugin registry.
_is_pii_safe = context.source.platform in _PII_SAFE_PLATFORMS
if not _is_pii_safe:
try:
@@ -535,29 +438,20 @@ def build_session_context_prompt(
if context.source.platform == Platform.LOCAL:
lines.append(f"**Source:** {platform_name} (the machine running this agent)")
else:
- # Build a description that respects PII redaction
src = context.source
if redact_pii:
- # Build a safe description without raw IDs
- _uname = src.user_name or (
- _hash_sender_id(src.user_id) if src.user_id else "user"
+ # Safe description without raw IDs (note: no thread suffix).
+ desc = SessionSource._describe(
+ src.chat_type,
+ src.user_name or (_hash_sender_id(src.user_id) if src.user_id else "user"),
+ src.chat_name or _hash_chat_id(src.chat_id),
)
- _cname = src.chat_name or _hash_chat_id(src.chat_id)
- if src.chat_type == "dm":
- desc = f"DM with {_uname}"
- elif src.chat_type == "group":
- desc = f"group: {_cname}"
- elif src.chat_type == "channel":
- desc = f"channel: {_cname}"
- else:
- desc = _cname
else:
desc = src.description
lines.append(
f"**Source:** {platform_name} ({_format_untrusted_prompt_value(desc)})"
)
- # Channel topic (if available - provides context about the channel's purpose)
if context.source.chat_topic:
lines.append(
f"**Channel Topic:** {_format_untrusted_prompt_value(context.source.chat_topic)}"
@@ -579,13 +473,9 @@ def build_session_context_prompt(
"about other Matrix rooms or projects unless the user explicitly says so."
)
- # User identity.
- # In shared multi-user sessions (shared threads OR shared non-thread groups
- # when group_sessions_per_user=False), multiple users contribute to the same
- # conversation. Don't pin a single user name in the system prompt — it
- # changes per-turn and would bust the prompt cache. Instead, note that
- # this is a multi-user session; individual sender names are prefixed on
- # each user message by the gateway.
+ # Shared multi-user sessions: never pin one user name in the system
+ # prompt (changes per turn -> busts the prompt cache); sender names are
+ # prefixed on each user message instead.
if context.shared_multi_user_session:
session_label = "Multi-user thread" if context.source.thread_id else "Multi-user session"
lines.append(
@@ -604,11 +494,8 @@ def build_session_context_prompt(
# Platform-specific behavioral notes
if context.source.platform == Platform.SLACK:
- # Inject the Slack capability note only when the agent actually has
- # Slack tools loaded this session — native `slack` toolset opt-in,
- # or a connected MCP server that has registered Slack tools.
- # Otherwise keep the stale-API disclaimer honest so we never
- # promise tools the agent lacks. Mirrors the Discord pattern below.
+ # Capability note only when Slack tools are actually loaded; otherwise
+ # keep the disclaimer honest so we never promise tools the agent lacks.
if _slack_tools_loaded():
lines.append("")
lines.append(
@@ -637,11 +524,6 @@ def build_session_context_prompt(
"conversation history."
)
elif context.source.platform == Platform.DISCORD:
- # Inject the Discord IDs block only when the agent actually has
- # Discord tools loaded this session — i.e. the user opted into
- # `discord` / `discord_admin` via `hermes tools` AND the bot
- # token is configured. Otherwise keep the stale-API disclaimer
- # honest so we never promise tools the agent lacks.
if _discord_tools_loaded():
src = context.source
id_lines = ["", "**Discord IDs (for the `discord` / `discord_admin` tools):**"]
@@ -653,13 +535,9 @@ def build_session_context_prompt(
else:
id_lines.append(f" - Channel: `{src.chat_id}`")
if src.message_id:
- # The triggering message id is volatile (changes every turn).
- # Keep it OUT of this cached system-prompt block — including it
- # here changes build_session_context_prompt() output per turn,
- # which busts the gateway agent-cache signature and forces an
- # AIAgent rebuild on every Discord message. The actual id is
- # injected per-turn into the user message instead (see the
- # "Triggering message id" note in run.py).
+ # The volatile per-turn message id must stay OUT of this cached
+ # block (it would bust the agent-cache signature every message);
+ # run.py injects it into the user message instead.
id_lines.append(
" - Triggering message: provided per-turn in the incoming "
"user message (use it as `message_id` for reply/react/pin)"
@@ -674,11 +552,8 @@ def build_session_context_prompt(
"Do not promise to perform these actions. If the user asks, explain "
"that you can only read messages sent directly to you and respond."
)
- # Static (never per-turn): live voice-channel state used to be
- # appended here and changed bytes every turn the bot sat in a voice
- # channel, busting the prompt cache. It now arrives on the current
- # user message as a `[Voice channel now: ...]` note, injected only
- # when it actually changed.
+ # Static: live voice-channel state arrives on the user message (it
+ # changed bytes every turn here and busted the prompt cache).
lines.append("")
lines.append(
"Voice-channel state, when relevant, appears in the current "
@@ -706,7 +581,6 @@ def build_session_context_prompt(
"are responding in."
)
- # Connected platforms
platforms_list = ["local (files on this machine)"]
for p in context.connected_platforms:
if p != Platform.LOCAL:
@@ -714,7 +588,6 @@ def build_session_context_prompt(
lines.append(f"**Connected Platforms:** {', '.join(platforms_list)}")
- # Home channels
if context.home_channels:
lines.append("")
lines.append("**Home Channels (default destinations):**")
@@ -724,13 +597,11 @@ def build_session_context_prompt(
safe_id = _format_untrusted_prompt_value(hc_id)
lines.append(f" - {platform.value}: {safe_name} (ID: {safe_id})")
- # Delivery options for scheduled tasks
lines.append("")
lines.append("**Delivery options for scheduled tasks:**")
from hermes_constants import display_hermes_home
- # Origin delivery
if context.source.platform == Platform.LOCAL:
lines.append("- `\"origin\"` → Local output (saved to files)")
else:
@@ -740,38 +611,28 @@ def build_session_context_prompt(
_origin_label = _format_untrusted_prompt_value(_origin_label)
lines.append(f"- `\"origin\"` → Back to this chat ({_origin_label})")
- # Local always available
lines.append(
f"- `\"local\"` → Save to local files only ({display_hermes_home()}/cron/output/)"
)
- # Platform home channels
for platform, home in context.home_channels.items():
home_name = _format_untrusted_prompt_value(home.name)
lines.append(f"- `\"{platform.value}\"` → Home channel ({home_name})")
- # Note about explicit targeting
lines.append("")
lines.append("*For explicit targeting, use `\"platform:chat_id\"` format if the user provides a specific chat ID.*")
return "\n".join(lines)
-# Keys of a /model session override that are safe to persist to disk.
-# ``api_key`` (and anything else, e.g. ``api_mode`` which is re-derived from
-# provider resolution) is intentionally excluded: credentials must NEVER be
-# written to sessions.json. On rehydration after a gateway restart the
-# runner re-resolves credentials via the normal runtime provider resolution.
+# /model override keys safe to persist. ``api_key``/``api_mode`` are excluded:
+# credentials must NEVER reach sessions.json; the runner re-resolves them.
PERSISTABLE_MODEL_OVERRIDE_KEYS = ("model", "provider", "base_url")
def sanitize_model_override(override: Optional[Dict[str, Any]]) -> Optional[Dict[str, str]]:
- """Return a copy of *override* containing only persistable, non-secret keys.
-
- Returns ``None`` when the input is empty/not a dict or no persistable
- values remain, so callers can store the result directly on
- ``SessionEntry.model_override``.
- """
+ """Copy of *override* with only persistable, non-secret keys; ``None`` when
+ nothing persistable remains (storable directly on ``model_override``)."""
if not isinstance(override, dict):
return None
cleaned = {
@@ -784,11 +645,7 @@ def sanitize_model_override(override: Optional[Dict[str, Any]]) -> Optional[Dict
@dataclass
class SessionEntry:
- """
- Entry in the session store.
-
- Maps a session key to its current session ID and metadata.
- """
+ """Routing-index entry: maps a session key to its current session ID and metadata."""
session_key: str
session_id: str
created_at: datetime
@@ -802,9 +659,8 @@ class SessionEntry:
platform: Optional[Platform] = None
chat_type: str = "dm"
- # Lightweight persisted key/value state scoped to this session entry
- # (e.g. Slack thread-context watermarks). Survives gateway restarts via
- # the routing index; must stay small and JSON-serializable.
+ # Small, JSON-serializable per-entry state (e.g. Slack thread watermarks);
+ # persisted in the routing index.
metadata: Dict[str, Any] = field(default_factory=dict)
# Token tracking
@@ -825,61 +681,49 @@ class SessionEntry:
auto_reset_reason: Optional[str] = None # "idle" or "daily"
reset_had_activity: bool = False # whether the expired session had any messages
- # When this session was created by an auto-reset, the session_id of the
- # session it replaced. Used to give Slack/Discord channels/threads a
- # lightweight continuity hint (see build_channel_continuity_note) so the
- # agent recalls the prior same-channel session via session_search instead
- # of binding the request to an unrelated recent session.
+ # session_id replaced by an auto-reset; feeds build_channel_continuity_note.
prev_session_id: Optional[str] = None
- # Set by reset_session() when the user explicitly sends /new or /reset.
- # Consumed once by _handle_message_with_agent to trigger topic/channel
- # skill re-injection on the first message of the new session. We can't
- # reuse was_auto_reset for this because that flag fires the "session
- # expired due to inactivity" user-facing notice and a misleading
- # context-note prepend — both wrong for an explicit manual reset.
- # See issue #6508.
+ # Set by reset_session() on explicit /new or /reset; consumed once to
+ # re-inject topic/channel skills. Distinct from was_auto_reset, which
+ # fires the "expired due to inactivity" notice (wrong for a manual reset).
is_fresh_reset: bool = False
-
- # Set by the background expiry watcher after it finalizes an expired
- # session (invoking on_session_finalize hooks and evicting the cached
- # agent). Persisted to sessions.json so the flag survives gateway
- # restarts — prevents redundant finalization runs.
+
+ # Set by the expiry watcher after finalizing an expired session; persisted
+ # so restarts don't re-run finalization.
expiry_finalized: bool = False
- # When True the next call to get_or_create_session() will auto-reset
- # this session (create a new session_id) so the user starts fresh.
- # Set by /stop to break stuck-resume loops (#7536).
+ # Next get_or_create_session() auto-resets (new session_id). Set by /stop
+ # to break stuck-resume loops.
suspended: bool = False
- # When True the session was interrupted by a gateway restart/shutdown
- # drain timeout, but recovery is still expected. Unlike ``suspended``,
- # ``resume_pending`` preserves the existing session_id on next access —
- # the user stays on the same transcript and the agent auto-continues
- # from where it left off. Cleared after the next successful turn.
- # Escalation to ``suspended`` is handled by the existing
- # ``.restart_failure_counts`` stuck-loop counter (#7536), not by a
- # parallel counter on this entry.
+ # Interrupted by a restart/drain timeout but recovery expected. Unlike
+ # ``suspended``, the session_id is preserved so the agent auto-continues
+ # the same transcript. Cleared after the next successful turn; escalation
+ # to ``suspended`` is the runner's ``.restart_failure_counts`` job.
resume_pending: bool = False
resume_reason: Optional[str] = None # e.g. "restart_timeout"
last_resume_marked_at: Optional[datetime] = None
- # Durable ownership marker for the agent turn currently executing on this
- # routing entry. A normal unwind clears it with compare-and-swap semantics;
- # SIGKILL/OOM leaves it behind so the next unclean startup can recover the
- # exact interrupted session instead of guessing from ``updated_at``.
+ # Durable marker of the executing agent turn; CAS-cleared on normal
+ # unwind, left behind by SIGKILL/OOM so unclean startup recovers the exact
+ # interrupted session instead of guessing from ``updated_at``.
active_turn_token: Optional[str] = None
active_turn_started_at: Optional[datetime] = None
# Session-scoped /model override (model/provider/base_url ONLY — never
- # credentials). ``_session_model_overrides`` in the gateway runner is
- # in-memory, so before this field a gateway restart silently reverted
- # every session to the global default model. api_key/api_mode are
- # re-resolved through the normal runtime provider resolution when the
- # override is rehydrated after a restart and are never written to disk
- # (see sanitize_model_override / SessionStore.set_model_override).
+ # credentials; see sanitize_model_override). Persisted so a restart does
+ # not revert sessions to the global default model.
model_override: Optional[Dict[str, str]] = None
+ # Fields (de)serialized verbatim, in wire order; ``from_dict`` reads them
+ # with ``data.get(name, <dataclass default>)``.
+ _PLAIN_FIELDS = (
+ "input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens",
+ "total_tokens", "last_prompt_tokens", "estimated_cost_usd", "cost_status",
+ "expiry_finalized", "suspended", "resume_pending", "resume_reason",
+ )
+
def to_dict(self) -> Dict[str, Any]:
result = {
"session_key": self.session_key,
@@ -890,38 +734,17 @@ class SessionEntry:
"platform": self.platform.value if self.platform else None,
"chat_type": self.chat_type,
"metadata": self.metadata,
- "input_tokens": self.input_tokens,
- "output_tokens": self.output_tokens,
- "cache_read_tokens": self.cache_read_tokens,
- "cache_write_tokens": self.cache_write_tokens,
- "total_tokens": self.total_tokens,
- "last_prompt_tokens": self.last_prompt_tokens,
- "estimated_cost_usd": self.estimated_cost_usd,
- "cost_status": self.cost_status,
- "expiry_finalized": self.expiry_finalized,
- "suspended": self.suspended,
- "resume_pending": self.resume_pending,
- "resume_reason": self.resume_reason,
- "last_resume_marked_at": (
- self.last_resume_marked_at.isoformat()
- if self.last_resume_marked_at
- else None
- ),
- "active_turn_token": self.active_turn_token,
- "active_turn_started_at": (
- self.active_turn_started_at.isoformat()
- if self.active_turn_started_at
- else None
- ),
- "is_fresh_reset": self.is_fresh_reset,
- "was_auto_reset": self.was_auto_reset,
- "auto_reset_reason": self.auto_reset_reason,
- "reset_had_activity": self.reset_had_activity,
- "prev_session_id": self.prev_session_id,
}
+ for name in self._PLAIN_FIELDS:
+ result[name] = getattr(self, name)
+ result["last_resume_marked_at"] = _iso(self.last_resume_marked_at)
+ result["active_turn_token"] = self.active_turn_token
+ result["active_turn_started_at"] = _iso(self.active_turn_started_at)
+ for name in ("is_fresh_reset", "was_auto_reset", "auto_reset_reason",
+ "reset_had_activity", "prev_session_id"):
+ result[name] = getattr(self, name)
if self.model_override:
- # Defence-in-depth: strip credentials even if a caller stored an
- # unsanitized dict directly on the entry.
+ # Defence-in-depth against an unsanitized dict stored directly.
result["model_override"] = sanitize_model_override(self.model_override)
if self.origin:
result["origin"] = self.origin.to_dict()
@@ -940,24 +763,11 @@ class SessionEntry:
except ValueError as e:
logger.debug("Unknown platform value %r: %s", data["platform"], e)
- last_resume_marked_at = None
- _lrma = data.get("last_resume_marked_at")
- if _lrma:
- try:
- last_resume_marked_at = datetime.fromisoformat(_lrma)
- except (TypeError, ValueError):
- last_resume_marked_at = None
-
- active_turn_started_at = None
- _atsa = data.get("active_turn_started_at")
- if _atsa:
- try:
- active_turn_started_at = datetime.fromisoformat(_atsa)
- except (TypeError, ValueError):
- active_turn_started_at = None
+ last_resume_marked_at = _parse_iso(data.get("last_resume_marked_at"))
+ active_turn_started_at = _parse_iso(data.get("active_turn_started_at"))
active_turn_token = data.get("active_turn_token")
if not isinstance(active_turn_token, str) or not active_turn_token:
- # The token/timestamp pair is written atomically. A partial or
+ # The token/timestamp pair is written atomically; a partial or
# malformed pair is not trustworthy enough to auto-resume.
active_turn_token = None
active_turn_started_at = None
@@ -965,13 +775,8 @@ class SessionEntry:
session_key = data["session_key"]
session_id = data["session_id"]
- # Validate path-sensitive fields to prevent directory traversal (CWE-22).
- # ``session_id`` is the value used as a filename
- # (``sessions_dir / f"{session_id}.json"``), so it must pass the strict
- # guard. ``session_key`` is a *logical* routing key that never touches
- # the filesystem — interior ``/`` is legitimate (Google Chat resource
- # names are ``spaces/<id>`` and ``spaces/<id>/threads/<id>``), so it
- # only needs the relaxed guard against genuine traversal vectors.
+ # CWE-22: session_id becomes a filename (strict guard); session_key is
+ # a logical routing key where interior ``/`` is legitimate (relaxed).
if _is_path_unsafe(session_id):
raise ValueError(
"Invalid session_id: potential directory traversal detected"
@@ -981,6 +786,9 @@ class SessionEntry:
"Invalid session_key: potential directory traversal detected"
)
+ defaults = {f.name: f.default for f in fields(cls)}
+ plain = {name: data.get(name, defaults[name]) for name in cls._PLAIN_FIELDS}
+ plain["expiry_finalized"] = data.get("expiry_finalized", data.get("memory_flushed", False))
return cls(
session_key=session_key,
session_id=session_id,
@@ -991,18 +799,7 @@ class SessionEntry:
platform=platform,
chat_type=data.get("chat_type", "dm"),
metadata=dict(data.get("metadata") or {}),
- input_tokens=data.get("input_tokens", 0),
- output_tokens=data.get("output_tokens", 0),
- cache_read_tokens=data.get("cache_read_tokens", 0),
- cache_write_tokens=data.get("cache_write_tokens", 0),
- total_tokens=data.get("total_tokens", 0),
- last_prompt_tokens=data.get("last_prompt_tokens", 0),
- estimated_cost_usd=data.get("estimated_cost_usd", 0.0),
- cost_status=data.get("cost_status", "unknown"),
- expiry_finalized=data.get("expiry_finalized", data.get("memory_flushed", False)),
- suspended=data.get("suspended", False),
- resume_pending=data.get("resume_pending", False),
- resume_reason=data.get("resume_reason"),
+ **plain,
last_resume_marked_at=last_resume_marked_at,
active_turn_token=active_turn_token,
active_turn_started_at=active_turn_started_at,
@@ -1019,22 +816,13 @@ def build_channel_continuity_note(
entry: "SessionEntry",
source: SessionSource,
) -> Optional[str]:
- """Build a lightweight session-continuity hint for Slack/Discord channels.
-
- Slack and Discord channels/threads are long-lived: when the daily/idle
- reset policy starts a fresh session, the agent loses the thread's prior
- context and can mistakenly bind a new request to an unrelated recent
- session. This deterministic one-line hint points the agent at the
- specific prior session in *this* channel/thread so it recalls that
- context via ``session_search`` before acting.
-
- Returns ``None`` (and the caller adds nothing) unless **all** hold:
- - the source platform is Slack or Discord,
- - this session was created by an auto-reset that had real activity,
- - the previous session_id was recorded on the entry.
-
- No LLM calls, no extra API/DB lookups — the previous session id is
- already known from :meth:`SessionStore.get_or_create_session`.
+ """One-line continuity hint for long-lived Slack/Discord channels/threads.
+
+ After an auto-reset the agent could bind a new request to an unrelated
+ recent session; this points it at the prior session in *this* channel so
+ it recalls context via ``session_search``. Returns ``None`` unless the
+ platform is Slack/Discord, the auto-reset had real activity, and the
+ previous session_id is recorded.
"""
if source.platform not in (Platform.SLACK, Platform.DISCORD):
return None
@@ -1061,14 +849,8 @@ def is_shared_multi_user_session(
group_sessions_per_user: bool = True,
thread_sessions_per_user: bool = False,
) -> bool:
- """Return True when a non-DM session is shared across participants.
-
- Mirrors the isolation rules in :func:`build_session_key`:
- - DMs are never shared.
- - Threads are shared unless ``thread_sessions_per_user`` is True.
- - Non-thread group/channel sessions are shared unless
- ``group_sessions_per_user`` is True (default: True = isolated).
- """
+ """True when a non-DM session is shared across participants (mirrors the
+ isolation rules in :func:`build_session_key`)."""
if source.chat_type == "dm":
return False
if source.thread_id:
@@ -1077,19 +859,11 @@ def is_shared_multi_user_session(
def _session_key_namespace(profile: Optional[str]) -> str:
- """Return the ``agent:<ns>`` namespace prefix for a session key.
-
- The historical key format is ``agent:main:<platform>:<chat_type>:...`` where
- ``main`` is a static namespace literal (NOT a branch name — branching keys
- off ``session_id``, not this slot). Multi-profile multiplexing reuses this
- slot to carry the profile:
-
- - default profile (or ``None``/``""``/``"default"``) → ``agent:main`` —
- BYTE-IDENTICAL to every key ever generated, so existing sessions and all
- positional parsers (``parts[2]`` == platform, etc.) are unaffected.
- - named profile ``coder`` → ``agent:coder`` — keeps the same positional
- layout, just a different namespace, so two profiles serving the same
- platform/chat never collide.
+ """``agent:<ns>`` prefix for a session key.
+
+ Default/None profile → ``agent:main`` (BYTE-IDENTICAL to every historical
+ key, so positional parsers are unaffected); named profile → ``agent:<name>``
+ so two profiles serving the same chat never collide.
"""
if not profile or profile == "default":
return "agent:main"
@@ -1102,37 +876,14 @@ def build_session_key(
thread_sessions_per_user: bool = False,
profile: Optional[str] = None,
) -> str:
- """Build a deterministic session key from a message source.
-
- This is the single source of truth for session key construction.
-
- ``profile`` selects the key namespace (see :func:`_session_key_namespace`).
- It defaults to ``None`` ⇒ the legacy ``agent:main`` namespace, so callers
- that don't multiplex produce byte-identical keys to before. Only the
- multiplexing gateway passes a non-default profile.
-
- DM rules:
- - Slack ``scope_id`` identifies the workspace before chat/user ids. Other
- platforms retain their existing key format; in particular, Discord
- guild scope is intentionally not added here as a compatibility change.
- - DMs include chat_id when present, so each private conversation is isolated.
- - thread_id further differentiates threaded DMs within the same DM chat.
- - Without chat_id, thread_id is used as a best-effort fallback.
- - Without thread_id or chat_id, DMs share a single session.
-
- Group/channel rules:
- - Slack ``scope_id`` identifies the workspace before chat/thread ids.
- - chat_id identifies the parent group/channel.
- - user_id/user_id_alt isolates participants within that parent chat when available when
- ``group_sessions_per_user`` is enabled.
- - thread_id differentiates threads within that parent chat. When
- ``thread_sessions_per_user`` is False (default), threads are *shared* across all
- participants — user_id is NOT appended, so every user in the thread
- shares a single session. This is the expected UX for threaded
- conversations (Telegram forum topics, Discord threads, Slack threads).
- - Without participant identifiers, or when isolation is disabled, messages fall back to one
- shared session per chat.
- - Without identifiers, messages fall back to one session per platform/chat_type.
+ """Build a deterministic session key from a message source (single source of truth).
+
+ Layout: ``<ns>:<platform>:<chat_type>[:<slack scope_id>][:<chat_id>][:<thread_id>][:<user>]``.
+ Slack ``scope_id`` precedes chat ids (Discord guild scope is deliberately
+ NOT added, for key compatibility). DMs are isolated per chat_id, falling
+ back to the sender id, then to one session per platform. Groups add the
+ participant id only when ``group_sessions_per_user`` and not in a thread
+ (threads are shared unless ``thread_sessions_per_user``).
"""
ns = _session_key_namespace(profile)
platform = source.platform.value
@@ -1151,49 +902,29 @@ def build_session_key(
dm_parts.append(slack_scope_id)
if dm_chat_id:
dm_parts.append(dm_chat_id)
- if source.thread_id:
- dm_parts.append(source.thread_id)
- return ":".join(str(part) for part in dm_parts)
- # No chat_id — fall back to the sender's own identifier before the
- # bare per-platform sink. Without this, every DM from every user that
- # arrives without a chat_id (non-standard adapters / synthetic sources)
- # collapses into one shared "<ns>:<platform>:dm" session, and a
- # single cached agent ends up serving multiple people's conversations —
- # cross-user history bleed. participant_id keeps DMs isolated per user.
- dm_participant_id = source.user_id_alt or source.user_id
- if dm_participant_id and source.platform == Platform.WHATSAPP:
- dm_participant_id = (
- canonical_whatsapp_identifier(str(dm_participant_id))
- or dm_participant_id
- )
- if dm_participant_id:
- dm_parts.append(str(dm_participant_id))
- if source.thread_id:
- dm_parts.append(source.thread_id)
- return ":".join(str(part) for part in dm_parts)
+ else:
+ # No chat_id: fall back to the sender id before the bare
+ # per-platform sink, or every chat_id-less DM shares one agent.
+ dm_participant_id = source.user_id_alt or source.user_id
+ if dm_participant_id and source.platform == Platform.WHATSAPP:
+ dm_participant_id = (
+ canonical_whatsapp_identifier(str(dm_participant_id))
+ or dm_participant_id
+ )
+ if dm_participant_id:
+ dm_parts.append(str(dm_participant_id))
if source.thread_id:
dm_parts.append(source.thread_id)
return ":".join(str(part) for part in dm_parts)
participant_id = source.user_id_alt or source.user_id
if participant_id and source.platform == Platform.WHATSAPP:
- # Same JID/LID-flip bug as the DM case: without canonicalisation, a
- # single group member gets two isolated per-user sessions when the
- # bridge reshuffles alias forms.
+ # JID/LID alias flips would otherwise split one member into two sessions.
participant_id = canonical_whatsapp_identifier(str(participant_id)) or participant_id
- # Discord auto-thread continuity: a channel-initiating message carries no
- # thread_id yet, but the connector tells us the thread its reply WILL be
- # auto-threaded into (prospective_thread_id == the message id, which becomes
- # the thread id). Key the session on that so the initiating channel message
- # and every follow-up that later arrives IN that thread (real thread_id ==
- # prospective_thread_id) resolve to the SAME session — "initiate in channel,
- # continue in thread". A real thread_id always wins when present.
- #
- # The follow-up arrives with chat_type="thread" while the initiating message
- # has chat_type="group"/"channel"; normalize the chat_type slot to "thread"
- # when keying on a prospective id so the two byte-match. (Real-thread events
- # already carry chat_type="thread", so this only rewrites the initiating
- # channel message's slot.)
+ # Discord auto-thread continuity: key a channel-initiating message on the
+ # thread it WILL be delivered into (prospective_thread_id), and normalize
+ # the chat_type slot to "thread" so in-thread follow-ups byte-match. A
+ # real thread_id always wins.
effective_thread_id = source.thread_id or source.prospective_thread_id
chat_type_slot = source.chat_type
if source.prospective_thread_id and not source.thread_id:
@@ -1207,9 +938,8 @@ def build_session_key(
if effective_thread_id:
key_parts.append(effective_thread_id)
- # In threads, default to shared sessions (all participants see the same
- # conversation). Per-user isolation only applies when explicitly enabled
- # via thread_sessions_per_user, or when there is no thread (regular group).
+ # Threads are shared by default; per-user isolation only via
+ # thread_sessions_per_user or outside a thread.
isolate_user = group_sessions_per_user
if effective_thread_id and not thread_sessions_per_user:
isolate_user = False
@@ -1244,21 +974,15 @@ class AsyncSessionStore:
return _offloaded
-# Sentinel for "no explicit SessionDB has been pinned on this store", so the
-# ``_db`` property can distinguish "resolve from the active profile scope"
-# from a deliberate ``store._db = None`` (which disables the DB and selects
-# the JSONL fallback). A plain ``None`` cannot express both.
+# "No SessionDB pinned" sentinel: lets ``_db`` distinguish "resolve from the
+# active scope" from a deliberate ``store._db = None`` (JSONL fallback).
_DB_UNPINNED = object()
class SessionStore:
- """
- Manages session storage and retrieval.
-
- Uses SQLite (via SessionDB) for session metadata and message transcripts.
- Falls back to legacy JSONL files if SQLite is unavailable.
- """
-
+ """Session storage/retrieval: SQLite (SessionDB) for metadata and
+ transcripts, legacy JSONL fallback when SQLite is unavailable."""
+
def __init__(self, sessions_dir: Path, config: GatewayConfig,
has_active_processes_fn=None):
self.sessions_dir = sessions_dir
@@ -1270,74 +994,51 @@ class SessionStore:
self._routing_db_loaded = False
self._routing_fallback_baseline: Optional[Dict[str, Any]] = None
self._lock = threading.Lock()
- # Serialize whole-index persistence without holding ``_lock`` across
- # SQLite / fsync. Each writer snapshots the latest state only after
- # acquiring this lock, preventing stale delayed writes.
+ # Serializes whole-index persistence without holding ``_lock`` across
+ # SQLite/fsync; writers snapshot only after acquiring it.
self._save_lock = threading.Lock()
self._routing_generation = 0
self._persisted_routing_generation = 0
- # Single-entry upserts persisted since the last full rewrite:
- # session_key -> (revision, entry_json). Revisions are allocated
- # from _routing_generation, so fast and full snapshots are totally
- # ordered; guarded by _save_lock (see _save_entry).
+ # Single-entry upserts since the last full rewrite: key -> (revision,
+ # entry_json). Revisions share _routing_generation so fast and full
+ # snapshots are totally ordered; guarded by _save_lock.
self._fast_persisted_entries: Dict[str, tuple[int, str]] = {}
self._inflight_lock = threading.Lock()
self._inflight_sessions: Dict[str, _SessionFlight] = {}
- # An unscoped pre-migration Slack key can represent at most one
- # workspace. Claim it once per process so simultaneous first messages
- # from two workspaces cannot both revive the same legacy session.
+ # An unscoped pre-migration Slack key is claimed once per process so
+ # two workspaces cannot both revive the same legacy session.
self._legacy_slack_claim_lock = threading.Lock()
self._claimed_legacy_slack_keys: set[str] = set()
self._transcript_retry_lock = threading.Lock()
- # Exactly one transcript drainer mutates routing/queues at a time. SQLite
- # serializes writes anyway; this outer lock also makes parent->child
- # queue migration and routing publication linearizable.
+ # One transcript drainer at a time: makes parent->child queue
+ # migration and routing publication linearizable.
self._transcript_drain_lock = threading.RLock()
self._transcript_reroutes: Dict[str, str] = {}
self._dirty_transcripts: Dict[str, List[Dict[str, Any]]] = {}
self._transcript_append_failures: Dict[str, int] = {}
self._fts_rebuild_attempted = False
self._has_active_processes_fn = has_active_processes_fn
- # Whether to keep writing the legacy sessions.json mirror alongside
- # the primary gateway_routing table in state.db. Default True for
- # backward compatibility; disable via gateway.write_sessions_json.
+ # Keep the legacy sessions.json mirror (disable via gateway.write_sessions_json).
self._write_sessions_json = bool(
getattr(config, "write_sessions_json", True)
)
-
- # Initialize SQLite session database.
- #
- # Handles are cached per resolved path and looked up through the
- # ``_db`` property instead of being bound to one handle here. A
- # multiplexed gateway serves every profile from a SINGLE process, so
- # a handle bound during __init__ is frozen to the process's own root
- # home; every profile's rows then land in the root state.db even
- # though ``_profile_runtime_scope`` has already redirected
- # ``get_hermes_home()`` for the turn (its docstring lists "sessions"
- # among what it scopes). The row still carries the right
- # ``profile_name``, so the damage is invisible in the data and shows
- # up only as the desktop listing a profile's session under the
- # default bot -- ``_open_session_db_for_profile`` reads
- # ``profiles/<name>/state.db``, which never received the write.
- # See #88532.
- #
- # Priming the handle for the current scope here keeps the startup
- # diagnostics exactly where they were: the live-DB isolation guard
- # still raises during construction, and the JSONL-fallback warning
- # is still printed once at startup rather than on first use.
+
+ # SQLite handles are cached per resolved path and looked up through
+ # the ``_db`` property rather than bound once here: a multiplexed
+ # gateway serves every profile from ONE process, and a handle bound in
+ # __init__ would be frozen to the root home so every profile's rows
+ # land in the root state.db. Priming the current scope's handle below
+ # keeps startup diagnostics (live-DB guard, JSONL warning) at
+ # construction time.
self._db_pinned = _DB_UNPINNED
self._db_handles: Dict[Path, Any] = {}
self._db_handles_lock = threading.Lock()
- # profile name -> its HERMES_HOME (or None to use the ambient scope).
- # Memoized so the per-key store lookup stays a dict hit instead of a
- # profile-directory stat on every transcript append.
+ # profile name -> its HERMES_HOME; memoized so the per-key store
+ # lookup is a dict hit, not a profile-directory stat per append.
self._profile_home_cache: Dict[str, Optional[Path]] = {}
- # session_id -> owning routing key, for ids whose ownership is already
- # proven but not yet published in ``_entries``. The compression
- # continuation is the case that needs it: the child row is written
- # before its reroute is published, so an index lookup would miss and
- # fall back to the ambient store. Entries are dropped as soon as
- # routing publishes.
+ # session_id -> owning routing key, for ids whose ownership is proven
+ # but not yet published in ``_entries`` (compression continuation:
+ # the child row is written before its reroute is published).
self._session_owner_hints: Dict[str, str] = {}
from gateway.session_db_recovery import RecoverableHandleCache
@@ -1346,10 +1047,9 @@ class SessionStore:
lock=self._db_handles_lock,
)
# The routing index is one process-wide structure keyed by
- # ``agent:<profile>:…``, not a per-profile one, so it needs exactly one
- # home for its lifetime. The store is constructed at startup under the
- # gateway's own home, before any profile scope exists, so capturing it
- # here is what makes the index deterministic — see ``_routing_db``.
+ # ``agent:<profile>:…``, so it needs exactly one home for its lifetime;
+ # capture the gateway's own home at startup (before any profile scope
+ # exists) — see ``_routing_db``.
try:
from hermes_constants import get_hermes_home
@@ -1358,48 +1058,41 @@ class SessionStore:
self._routing_home = None
self._open_session_db_for_active_scope()
+ def _lazy(self, name: str, factory):
+ """Return ``self.<name>``, creating it via *factory* when missing/None.
+
+ Suites build bare stores via ``object.__new__`` without running
+ ``__init__``; every optional lock/map is read through this so those
+ instances still work.
+ """
+ value = getattr(self, name, None)
+ if value is None:
+ value = factory()
+ setattr(self, name, value)
+ return value
+
def _open_session_db_for_active_scope(self, db_path: Optional[Path] = None):
"""Return the SessionDB for the profile scope active on this task.
- ``db_path`` pins the store explicitly instead of consulting the
- ambient scope. ``_db_for_key`` uses it so work running outside
- ``_profile_runtime_scope`` still reaches the profile that owns the
- row it is about to touch.
-
- ``SessionDB(db_path=None)`` resolves ``_default_db_path()`` at call
- time, and that helper follows the context-local HERMES_HOME override
- installed by ``_profile_runtime_scope``. Resolving here rather than
- once in ``__init__`` is the whole fix for #88532: it lets the
- scoping that the multiplexed inbound path already performs actually
- reach session storage.
-
- Handles are cached per resolved path, so a hot inbound path opens
- SQLite once per profile rather than once per message, and two
- profiles never share a handle. Failed opens enter a bounded backoff;
- once it expires, one caller reopens while concurrent callers keep
- using the JSONL fallback.
+ ``db_path`` pins the store explicitly; otherwise ``_default_db_path()``
+ follows the context-local HERMES_HOME installed by
+ ``_profile_runtime_scope`` (resolving per call, not once in
+ ``__init__``, is what lets multiplexed profiles reach their own store).
+ Handles are cached per resolved path; failed opens enter a bounded
+ backoff during which callers keep using the JSONL fallback.
"""
from hermes_state import _default_db_path, get_shared_session_db
path = Path(db_path) if db_path is not None else Path(_default_db_path())
def _open():
try:
- # Route through the process-wide shared registry (#90837):
- # every long-lived in-process caller (store, runner, cron,
- # mirror, slash commands, tools) shares ONE writer
- # connection per path instead of each minting its own.
+ # Process-wide shared registry: one writer connection per path.
return get_shared_session_db(path)
- except RuntimeError as e:
- if "live-system guard" in str(e):
- # Test-isolation guard fired: a pytest-context process
- # resolved the developer's production state.db. Never
- # swallow this into the JSONL fallback — the whole point
- # is a loud, hard failure. Deliberately not cached: the
- # guard must fire again on the next attempt.
- raise
- print(f"[gateway] Warning: SQLite session store unavailable, falling back to JSONL: {e}")
- raise
except Exception as e:
+ if isinstance(e, RuntimeError) and "live-system guard" in str(e):
+ # Test-isolation guard: must stay a loud failure and is
+ # deliberately not cached so it fires again next attempt.
+ raise
print(f"[gateway] Warning: SQLite session store unavailable, falling back to JSONL: {e}")
raise
@@ -1411,17 +1104,20 @@ class SessionStore:
),
)
+ def _pinned_db(self):
+ """Return the explicitly pinned DB (``store._db = x``), else ``_DB_UNPINNED``."""
+ return getattr(self, "_db_pinned", _DB_UNPINNED)
+
@property
def _db(self):
"""The SessionDB for the active profile scope, or a pinned override.
- Assigning ``store._db`` pins that value for every subsequent read,
- which is what tests rely on to install a fake or to disable the DB
- with ``store._db = None``. Unpinned (the production path), each read
- resolves the scope so a multiplexed profile's writes reach its own
- store.
+ Assigning ``store._db`` pins that value for every subsequent read
+ (tests install a fake or disable the DB with ``store._db = None``).
+ Unpinned, each read resolves the scope so a multiplexed profile's
+ writes reach its own store.
"""
- pinned = getattr(self, "_db_pinned", _DB_UNPINNED)
+ pinned = self._pinned_db()
if pinned is not _DB_UNPINNED:
return pinned
return self._open_session_db_for_active_scope()
@@ -1434,20 +1130,15 @@ class SessionStore:
def _routing_db(self):
"""The one store that owns the routing index, whatever scope is active.
- ``_entries`` is a single flat dict holding every profile's keys, so the
- index it persists to has to be a single file too. Reading it through
- ``_db`` made that file whichever profile happened to be scoped at the
- time: a whole-index rewrite during one profile's turn copied every
- other profile's routing rows into that profile's store, and startup —
- which runs unscoped — then loaded a different copy than the one the
- last writer produced. That is why a crash marker written while a
- secondary profile was active is invisible to the startup recovery pass
- (#66887).
-
- A pinned handle still wins, so the suites that install a fake or
- disable the DB keep working unchanged.
+ ``_entries`` is a single flat dict holding every profile's keys, so it
+ must persist to a single file (``_routing_home``), not whichever
+ profile happens to be scoped — otherwise a rewrite during one
+ profile's turn and the unscoped startup load see different copies,
+ and crash markers written under a secondary profile go unrecovered.
+ A pinned handle still wins. Bare test instances lacking the handle
+ cache report no DB.
"""
- pinned = getattr(self, "_db_pinned", _DB_UNPINNED)
+ pinned = self._pinned_db()
if pinned is not _DB_UNPINNED:
return pinned
home = getattr(self, "_routing_home", None)
@@ -1455,22 +1146,16 @@ class SessionStore:
if home is None:
return self._db
return self._open_session_db_for_active_scope(db_path=home / "state.db")
- except AttributeError:
- # Bare test instances (object.__new__) lack _routing_home AND the
- # handle cache behind the _db property; behave like main's old
- # getattr(self, "_db", None) contract and report no DB.
- return getattr(self, "_db_pinned", None) if getattr(self, "_db_pinned", _DB_UNPINNED) is not _DB_UNPINNED else None
except Exception:
return None
def _named_profile_for_key(self, session_key: Optional[str]) -> Optional[str]:
"""The non-default profile that owns *session_key*, or None.
- None means the ambient store is authoritative for this key —
- multiplexing is off, or the key carries the legacy ``agent:main``
- namespace. It deliberately does NOT cover "that profile has no
- directory": ownership and resolvability are different questions, and
- ``_db_for_key`` has to answer them separately.
+ None means the ambient store is authoritative (multiplexing off, or
+ legacy ``agent:main`` namespace). It deliberately does NOT cover "that
+ profile has no directory" — ownership and resolvability are separate
+ questions that ``_db_for_key`` answers separately.
"""
if not getattr(self.config, "multiplex_profiles", False):
return None
@@ -1482,10 +1167,8 @@ class SessionStore:
def _profile_home_for_key(self, session_key: Optional[str]) -> Optional[Path]:
"""HERMES_HOME of the profile that owns *session_key*, or None.
- None here means only "no live home to point at" — either the key has
- no named owner, or that owner's directory could not be resolved.
- Callers that mutate state must tell those two apart through
- ``_named_profile_for_key``.
+ None means only "no live home to point at" — no named owner, or the
+ owner's directory could not be resolved.
"""
profile = self._named_profile_for_key(session_key)
if profile is None:
@@ -1500,16 +1183,11 @@ class SessionStore:
if profile_exists(profile):
home = Path(get_profile_dir(profile))
except Exception as exc:
- logger.debug(
- "Could not resolve profile home for %r: %s", session_key, exc
- )
+ logger.debug("Could not resolve profile home for %r: %s", session_key, exc)
home = None
- # Only a hit is memoized. A profile directory can appear *after* the
- # gateway started — the enrollment bridge provisions profiles/<name>/
- # at runtime — and caching the miss would pin that profile's rows to
- # the ambient store for the life of the process, which is the bug
- # this helper exists to prevent. A miss costs one profile_exists()
- # stat and only recurs for profiles that genuinely do not exist.
+ # Only hits are memoized: a profile directory can be provisioned
+ # *after* startup (enrollment bridge), and a cached miss would pin
+ # that profile's rows to the ambient store for the process lifetime.
if home is not None:
cache[profile] = home
return home
@@ -1517,38 +1195,25 @@ class SessionStore:
def _db_for_key(self, session_key: Optional[str]):
"""The SessionDB holding *session_key*'s rows, whatever scope is active.
- ``_db`` follows the ambient HERMES_HOME, and only the inbound message
- path installs one (``_profile_runtime_scope``). Background work runs
- unscoped while operating on every profile's keys out of the single
- process-wide ``_entries`` dict — ``_session_expiry_watcher`` is the
- clearest case — so it reads and writes the ROOT store for rows that
- actually live under ``profiles/<name>/state.db``. The two writers
- then drift apart on the same logical session until the routing index
- disagrees with the row and the #54878 self-heal drops a live
- conversation (#66887).
-
- The owning profile is already encoded in the key, so deriving the
- store from it makes every caller agree on one file per session
- without threading scope through each call site.
+ ``_db`` follows the ambient HERMES_HOME, which only the inbound
+ message path installs; background work (e.g. the expiry watcher)
+ runs unscoped over every profile's keys and would otherwise write
+ profile rows into the ROOT store, drifting from the real row until
+ the stale-route self-heal drops a live conversation. The owning
+ profile is encoded in the key, so derive the store from it.
"""
- pinned = getattr(self, "_db_pinned", _DB_UNPINNED)
+ pinned = self._pinned_db()
if pinned is not _DB_UNPINNED:
return pinned
profile = self._named_profile_for_key(session_key)
if profile is None:
- # No named owner — the ambient store is authoritative, exactly as
- # it was before this helper existed.
return self._db
home = self._profile_home_for_key(session_key)
if home is None:
- # A named owner we cannot resolve: the profile is not provisioned
- # yet (the enrollment bridge creates profiles/<name>/ at runtime,
- # so a key legitimately arrives first), or the lookup failed.
- # Falling back to the ambient store would put ONE qualified
- # session identity in two physical stores — the split this helper
- # exists to remove — because the first lookup would land in root
- # and the next one, after provisioning, in the profile. Fail
- # closed instead; callers already handle a missing DB.
+ # Named owner we cannot resolve (not provisioned yet, or lookup
+ # failed). Falling back to the ambient store would split ONE
+ # session identity across two physical stores — fail closed;
+ # callers already handle a missing DB.
logger.warning(
"gateway.session: profile %r has no resolvable home (key %r); "
"refusing to fall back to the ambient store",
@@ -1558,17 +1223,15 @@ class SessionStore:
try:
return self._open_session_db_for_active_scope(db_path=home / "state.db")
except Exception:
- # Same contract as ``_db``: a failed open degrades to the JSONL
- # fallback rather than taking routing down.
+ # Same contract as ``_db``: a failed open degrades to JSONL fallback.
return None
def _owner_key_for_session_id(self, session_id: Optional[str]) -> Optional[str]:
"""The routing key that owns *session_id*, or None.
The published index is authoritative; ``_session_owner_hints`` covers
- the window where ownership is already proven but routing has not been
- published yet. Deliberately lock-free: several callers already hold
- ``_lock``.
+ the window where ownership is proven but routing not yet published.
+ Deliberately lock-free: several callers already hold ``_lock``.
"""
if not session_id:
return None
@@ -1578,20 +1241,11 @@ class SessionStore:
return entry.session_key
except Exception:
pass
- # getattr: suites build bare stores via ``object.__new__`` and never
- # run __init__, the same reason the other optional maps are read
- # defensively here.
return (getattr(self, "_session_owner_hints", None) or {}).get(session_id)
def _db_for_session_id(self, session_id: Optional[str]):
- """The SessionDB holding *session_id*'s row.
-
- Transcript, compression and rewind entry points are addressed by
- session id rather than routing key, so the owning profile is
- recovered from the index (or from a pre-published ownership hint).
- An id nothing knows about still falls back to the ambient store —
- the behavior that predates ``_db_for_key``.
- """
+ """The SessionDB holding *session_id*'s row (owner recovered from the
+ index or a pre-published hint; unknown ids fall back to the ambient store)."""
if not session_id:
return self._db
return self._db_for_key(self._owner_key_for_session_id(session_id))
@@ -1599,27 +1253,14 @@ class SessionStore:
def close_all_db_handles(self) -> None:
"""Close every SessionDB handle this store opened, one per resolved path.
- A multiplexed gateway accumulates one cached handle per profile it
- served (see ``_open_session_db_for_active_scope``). Reading ``_db``
- at shutdown resolves only the handle for the scope active *then* —
- the root home — so a shutdown that closes just ``store._db`` would
- strand every secondary profile's handle with its WAL write lock held
- until the interpreter exits, recreating the abandoned-handle leak
- that ``SessionDB.close()`` exists to prevent. Restart flows
- (``--replace``) would then hit 'database is locked' opening those
- profiles' stores.
-
- Handles are drained under the lock but closed outside it, so a
- concurrent resolver blocked in ``_open_session_db_for_active_scope``
- is never made to wait on N ``close()`` calls; it simply opens a
- fresh handle afterwards. ``close()`` failures are swallowed the
- same way the shutdown path treats the primary handle. A pinned
- handle (``store._db = fake``) is deliberately not closed here — the
- pinner owns its lifecycle.
+ Closing just ``store._db`` at shutdown would strand every secondary
+ profile's handle with its WAL lock held (restart flows then hit
+ 'database is locked'). Handles are drained under the lock but closed
+ outside it so concurrent resolvers never wait on N ``close()`` calls.
+ A pinned handle is deliberately not closed — the pinner owns it.
"""
def _close(db) -> None:
- # Shared instances no-op on close() (the registry owns the
- # lifecycle). Release the refcount instead (#90837).
+ # Shared instances no-op on close(); release the refcount instead.
from hermes_state import release_or_close
try:
release_or_close(db)
@@ -1648,26 +1289,41 @@ class SessionStore:
with self._lock:
self._ensure_loaded_locked()
- def _routing_scope(self) -> str:
- """Namespace for this store's rows in the gateway_routing table.
+ def _entry_locked(self, session_key: str) -> Optional[SessionEntry]:
+ """Load the index and return the entry for *session_key*. Lock held."""
+ self._ensure_loaded_locked()
+ return self._entries.get(session_key)
- The resolved sessions_dir path — the same identity that used to
- distinguish separate sessions.json files, so two stores with
- different directories (tests, multi-profile setups sharing one
- state.db) never see each other's routing entries.
- """
+ def _routing_scope(self) -> str:
+ """Namespace for this store's gateway_routing rows: the resolved
+ sessions_dir, so stores with different dirs never share entries."""
try:
return str(Path(self.sessions_dir).resolve())
except Exception:
return str(self.sessions_dir)
+ def _routing_db_method(self, name: str):
+ """Bound ``_routing_db.<name>`` if the handle exists and has it, else None."""
+ db = self._routing_db
+ method = getattr(db, name, None) if db else None
+ return method if callable(method) else None
+
+ @staticmethod
+ def _routing_entry_from_json(key: str, entry_json: str) -> Optional[SessionEntry]:
+ """Parse one gateway_routing row; None (with a warning) when invalid."""
+ try:
+ entry_data = json.loads(entry_json)
+ if isinstance(entry_data, dict):
+ return SessionEntry.from_dict(entry_data)
+ except (ValueError, KeyError, TypeError) as e:
+ logger.warning("Skipping invalid routing entry %r: %s", key, e)
+ return None
+
def _ensure_loaded_locked(self) -> None:
"""Load the routing index. Must be called with self._lock held.
- Read order (#9006 follow-up): the ``gateway_routing`` table in
- state.db is the primary source; sessions.json is the legacy import
- path for pre-migration installs (its entries are folded in for keys
- the DB doesn't have, then persisted to the DB on the next _save).
+ state.db ``gateway_routing`` is primary; sessions.json is the legacy
+ import for keys the DB lacks (persisted to the DB on the next _save).
"""
if self._loaded:
self._reconcile_recovered_routing_locked()
@@ -1675,35 +1331,21 @@ class SessionStore:
self.sessions_dir.mkdir(parents=True, exist_ok=True)
- # Primary: state.db gateway_routing table. getattr: some tests build
- # partially-initialized stores without __init__ (same pattern as
- # _prune_stale_sessions_locked).
db_had_entries = False
db_load_succeeded = False
- _db = self._routing_db
- if _db:
- loader = getattr(_db, "load_gateway_routing_entries", None)
- if callable(loader):
- try:
- for key, entry_json in loader(scope=self._routing_scope()).items():
- try:
- entry_data = json.loads(entry_json)
- if isinstance(entry_data, dict):
- self._entries[key] = SessionEntry.from_dict(entry_data)
- except (ValueError, KeyError, TypeError) as e:
- logger.warning(
- "Skipping invalid routing entry %r: %s", key, e
- )
- db_had_entries = bool(self._entries)
- db_load_succeeded = True
- except Exception as e:
- logger.warning(
- "gateway.session: state.db routing load failed: %s", e
- )
+ loader = self._routing_db_method("load_gateway_routing_entries")
+ if loader is not None:
+ try:
+ for key, entry_json in loader(scope=self._routing_scope()).items():
+ entry = self._routing_entry_from_json(key, entry_json)
+ if entry is not None:
+ self._entries[key] = entry
+ db_had_entries = bool(self._entries)
+ db_load_succeeded = True
+ except Exception as e:
+ logger.warning("gateway.session: state.db routing load failed: %s", e)
- # Legacy import: sessions.json (pre-migration installs, or entries
- # written by an older gateway after a downgrade). Only fills keys the
- # DB didn't provide — DB entries win.
+ # Legacy import: sessions.json only fills keys the DB lacks.
sessions_file = self.sessions_dir / "sessions.json"
if sessions_file.exists():
try:
@@ -1711,18 +1353,13 @@ class SessionStore:
data = json.load(f)
imported = 0
for key, entry_data in data.items():
- # Keys starting with "_" are documentation/metadata sentinels
- # (e.g. the "_README" note written by _save), not session
- # entries. Skip them so they never reach SessionEntry.from_dict.
+ # "_"-prefixed keys are sentinels (e.g. "_README"), not entries.
if key.startswith("_"):
continue
if key in self._entries:
continue
- # Skip non-dict entries (corrupted sessions.json, e.g. a
- # bare bool or string where a dict is expected). Without
- # this, from_dict raises TypeError on `"origin" in data`
- # which escapes the inner except (ValueError, KeyError) and
- # aborts loading ALL remaining sessions (#46994).
+ # A non-dict entry (corrupt file) must not abort the
+ # whole load.
if not isinstance(entry_data, dict):
logger.warning(
"Skipping invalid session entry %r: "
@@ -1752,25 +1389,15 @@ class SessionStore:
else {key: entry.to_dict() for key, entry in self._entries.items()}
)
- # Prune any sessions.json entries that point to sessions already ended
- # in state.db. A hard gateway crash (exit code 1) skips the graceful
- # shutdown path, so sessions.json is never cleared and is left pointing
- # at ended sessions. On the next startup those stale entries act as live
- # routing keys. get_or_create_session() only consulted end_reason at
- # startup (here) until #54878 added a routing-time guard for the
- # live-gateway case; this startup prune still self-heals crash-left
- # entries before the first message arrives. Pruning here (lock already
- # held) is cheap: one lookup per routing key, once at startup.
+ # A hard crash skips graceful shutdown and leaves sessions.json
+ # pointing at ended sessions; self-heal before the first message.
self._prune_stale_sessions_locked()
def _prune_stale_sessions_locked(self) -> None:
- """Remove sessions.json entries whose session has ended in state.db.
+ """Remove routing entries whose session has ended in state.db (startup, lock held).
- Called once during startup (from ``_ensure_loaded_locked``, lock held).
- A ``session_id`` is stale when state.db reports ``end_reason IS NOT
- NULL`` for it. Sessions absent from the DB (never persisted / pre-SQLite
- legacy) are left alone, and a ``None`` DB handle (SQLite unavailable) is
- a no-op. DB errors are non-fatal — startup must never fail here.
+ Stale == ``end_reason IS NOT NULL``. Rows absent from the DB are kept;
+ a ``None`` DB handle is a no-op; DB errors are non-fatal.
"""
if not self._entries:
return
@@ -1779,21 +1406,14 @@ class SessionStore:
recovered_keys = 0
try:
for key, entry in self._entries.items():
- # Whether a session ended is a per-session question, so ask the
- # store that owns the key. A single ambient handle answered it
- # for every profile at once, which is how a live secondary
- # profile session could be pruned on the strength of the root
- # store's copy of it.
+ # Ask the store that owns the key, not the ambient handle, or a
+ # live secondary-profile session gets pruned on the root copy.
db = self._db_for_key(key)
if db is None:
continue
row = db.get_session(entry.session_id)
- # row is None -> not in DB (legacy / pre-SQLite) — keep
- # end_reason is None -> session alive — keep
- # end_reason not None -> session ended — prune
if row is not None and row.get("end_reason") is not None:
recovered_entry = None
- recovery_lookup_failed = False
if entry.origin is not None:
try:
recovered_entry = self._recover_session_from_db(
@@ -1803,6 +1423,7 @@ class SessionStore:
raise_on_lookup_error=True,
)
except Exception as exc:
+ # Indeterminate: keep the only routing handle.
logger.debug(
"gateway.session: recovery lookup failed for stale "
"sessions.json entry %r -> %s: %s",
@@ -1810,18 +1431,11 @@ class SessionStore:
entry.session_id,
exc,
)
- recovery_lookup_failed = True
-
- if recovery_lookup_failed:
- continue
+ continue
- # If the stale entry points at a compression-ended parent but
- # a newer live child session exists for the exact same gateway
- # peer, repoint the routing index instead of dropping it. A
- # hard restart between compression rotation and the next clean
- # save otherwise leaves Telegram with no resumable mapping, so
- # queued/resume-pending work disappears until the user sends a
- # fresh message.
+ # Compression-ended parent with a newer live child for the
+ # same peer: repoint instead of dropping, or queued/
+ # resume-pending work vanishes until the next message.
if recovered_entry is not None and recovered_entry.session_id != entry.session_id:
logger.warning(
"gateway.session: repointing stale sessions.json entry "
@@ -1835,16 +1449,10 @@ class SessionStore:
recovered_keys += 1
continue
- # A non-None recovery with the SAME session id is a
- # successful resume (all recovery gates passed, row
- # reopened): keep the routing entry — it is proven valid,
- # not a dead route (#95957). Keep the ORIGINAL entry
- # object, not the recovered one: the recovered entry is
- # rebuilt minimal from the DB row and would silently drop
- # live state the existing entry carries (token/cost
- # counters, model_override, resume_pending/queued-work
- # markers, metadata). Nothing in sessions.json changes,
- # so no save is needed for this branch.
+ # Same-id recovery == successful resume: keep the ORIGINAL
+ # entry object (the recovered one is rebuilt minimal and
+ # would drop counters, model_override, resume markers,
+ # metadata). Nothing changes, so no save.
if recovered_entry is not None:
logger.info(
"gateway.session: reopened ended session %s for "
@@ -1880,11 +1488,9 @@ class SessionStore:
def _next_routing_generation_locked(self) -> int:
"""Bump and return the shared routing counter. Caller holds ``_lock``.
- BOTH full snapshots (_snapshot_routing_locked) and single-entry fast
- saves (_save_entry) MUST allocate from this one counter — the stale-
- write protection in _persist_routing_data/_save_entry is a total order
- over serialization times and silently breaks if the two paths ever
- number themselves independently.
+ Full snapshots AND single-entry fast saves MUST allocate from this one
+ counter: the stale-write protection is a total order over
+ serialization times and silently breaks otherwise.
"""
self._routing_generation = getattr(self, "_routing_generation", 0) + 1
return self._routing_generation
@@ -1895,27 +1501,19 @@ class SessionStore:
if getattr(self, "_routing_db_loaded", False) or baseline is None:
return
- db = self._routing_db
- loader = getattr(db, "load_gateway_routing_entries", None) if db else None
- if not callable(loader):
+ loader = self._routing_db_method("load_gateway_routing_entries")
+ if loader is None:
return
try:
durable = loader(scope=self._routing_scope())
except Exception as exc:
- logger.warning(
- "gateway.session: recovered state.db routing load failed: %s", exc
- )
+ logger.warning("gateway.session: recovered state.db routing load failed: %s", exc)
return
current = {key: entry.to_dict() for key, entry in self._entries.items()}
for key, entry_json in durable.items():
- try:
- entry_data = json.loads(entry_json)
- if not isinstance(entry_data, dict):
- continue
- durable_entry = SessionEntry.from_dict(entry_data)
- except (ValueError, KeyError, TypeError) as exc:
- logger.warning("Skipping invalid routing entry %r: %s", key, exc)
+ durable_entry = self._routing_entry_from_json(key, entry_json)
+ if durable_entry is None:
continue
if key not in baseline:
@@ -1942,38 +1540,27 @@ class SessionStore:
def _persist_routing_data(self, data: Dict[str, Any], generation: int) -> None:
"""Serialize all whole-index writers through one durable write lock."""
- save_lock = getattr(self, "_save_lock", None)
- if save_lock is None:
- save_lock = threading.Lock()
- self._save_lock = save_lock
- with save_lock:
+ with self._lazy("_save_lock", threading.Lock):
if generation <= getattr(self, "_persisted_routing_generation", 0):
return
- # Fold in single-entry upserts with a newer revision than this
- # snapshot (see _save_entry): revisions share the routing
- # generation counter, so a fast record numbered above us was
- # serialized after us and a delayed full rewrite must not
- # regress it.
+ # Fold in fast upserts numbered above this snapshot: they were
+ # serialized after us and a delayed full rewrite must not regress them.
fast_persisted = getattr(self, "_fast_persisted_entries", None)
if fast_persisted:
for key, (revision, entry_json) in fast_persisted.items():
if revision > generation:
data[key] = json.loads(entry_json)
db_saved = False
- _db = self._routing_db
- if _db:
- replacer = getattr(_db, "replace_gateway_routing_entries", None)
- if callable(replacer):
- try:
- replacer(
- {k: json.dumps(v) for k, v in data.items()},
- scope=self._routing_scope(),
- )
- db_saved = True
- except Exception as exc:
- logger.warning(
- "gateway.session: state.db routing save failed: %s", exc
- )
+ replacer = self._routing_db_method("replace_gateway_routing_entries")
+ if replacer is not None:
+ try:
+ replacer(
+ {k: json.dumps(v) for k, v in data.items()},
+ scope=self._routing_scope(),
+ )
+ db_saved = True
+ except Exception as exc:
+ logger.warning("gateway.session: state.db routing save failed: %s", exc)
if getattr(self, "_write_sessions_json", True) or not db_saved:
try:
self._save_sessions_json(data)
@@ -2003,11 +1590,8 @@ class SessionStore:
self.sessions_dir.mkdir(parents=True, exist_ok=True)
sessions_file = self.sessions_dir / "sessions.json"
- # Self-documenting sentinel so anyone who inspects this file directly
- # understands what it is and where CLI/TUI sessions actually live. Keys
- # starting with "_" are skipped on load (see _ensure_loaded_locked), so
- # this never round-trips into a SessionEntry. Ordered first via a fresh
- # dict so it renders at the top of the pretty-printed JSON.
+ # Self-documenting sentinel; "_" keys are skipped on load. Ordered
+ # first so it renders at the top of the file.
data = {
"_README": (
"LEGACY MIRROR of the gateway routing index (the primary copy "
@@ -2052,49 +1636,26 @@ class SessionStore:
) -> None:
"""Persist ONE routing entry via UPSERT — the per-turn fast path.
- The steady-state turn only bumps ``updated_at`` /
- ``last_prompt_tokens`` on one entry; routing that through the
- full index rewrite re-serializes every entry, DELETE+INSERTs
- every gateway_routing row, and dumps+fsyncs a multi-MB
- sessions.json — ~50ms p50 at ~1100 routing keys, and it runs
- twice per turn. A single-row UPSERT keeps the durable state.db
- mapping current in well under a millisecond.
-
- Correctness constraints this path relies on:
-
- - The key -> session_id mapping never changes here. Structural
- transitions (create/recover/reset/switch/prune, and
- compression-tip heals — see get_or_create_session) still use
- the full-rewrite path, which also refreshes the legacy
- sessions.json mirror. Between structural saves the mirror may
- lag in metadata only; every remaining sessions.json reader is
- a legacy fallback and state.db stays primary, so restart
- rebinding is unaffected.
-
- - Ordering vs concurrent writers: the entry is serialized under
- ``_lock`` together with a revision allocated from the routing
- generation counter, so every snapshot — fast or full — carries
- a unique, monotonically increasing number, and a higher number
- always means same-or-newer data for this key. Under
- ``_save_lock`` the upsert is skipped when a snapshot numbered
- above ours already persisted this key: a FULL snapshot
- (``_persisted_routing_generation``) or another fast save of
- the same key (``_fast_persisted_entries``). Either contains a
- same-or-newer copy, so writing ours would regress it. The
- reverse interaction — a delayed full rewrite landing after a
- later-serialized fast save — is handled in
- ``_persist_routing_data``, which folds fast records numbered
- above its snapshot into the rewrite. An older snapshot can
- therefore never overwrite a newer one, in either direction.
-
+ A full index rewrite re-serializes every entry and fsyncs a multi-MB
+ sessions.json (~50ms at ~1100 keys, twice per turn); a single-row
+ UPSERT takes well under a millisecond. Invariants:
+
+ - The key -> session_id mapping never changes here; structural
+ transitions (create/recover/reset/switch/prune/heal) use the full
+ rewrite, which also refreshes the legacy sessions.json mirror. The
+ mirror may lag in metadata only; state.db stays primary.
+ - Ordering: the entry is serialized under ``_lock`` with a revision
+ from the shared routing generation counter, so a higher number
+ always means same-or-newer data. Under ``_save_lock`` the upsert is
+ skipped if a full snapshot or a fast save of this key with a higher
+ number already persisted. The reverse (delayed full rewrite after a
+ later fast save) is handled in ``_persist_routing_data``.
- No DB, or a failed upsert, falls back to the full rewrite so
- DB-less installs keep sessions.json — their primary store —
- durable every turn.
+ DB-less installs keep sessions.json durable every turn.
- ``entry_data`` lets a failure-atomic metadata transition persist a
- candidate before publishing it to the live entry. Its full-save
- fallback carries the same candidate instead of re-snapshotting the
- unchanged live value.
+ ``entry_data`` persists a candidate before it is published to the live
+ entry (failure-atomic metadata transitions); the full-save fallback
+ carries the same candidate.
"""
def _capture() -> Optional[tuple[str, int, Optional[Dict[str, Any]]]]:
entry = self._entries.get(session_key)
@@ -2105,9 +1666,7 @@ class SessionStore:
)
entry_json = json.dumps(serialized_entry)
revision = self._next_routing_generation_locked()
- # Don't eagerly build the O(n) full snapshot — only the candidate
- # is needed for the DB upsert. The fallback is deferred to the
- # except branch below where it's actually used.
+ # The O(n) full snapshot is deferred to the fallback branch.
return entry_json, revision, serialized_entry if entry_data is not None else None
if lock_held:
@@ -2118,21 +1677,13 @@ class SessionStore:
if captured is None:
return
entry_json, revision, candidate_entry = captured
- _db = self._routing_db
- saver = getattr(_db, "save_gateway_routing_entry", None) if _db else None
- if callable(saver):
- save_lock = getattr(self, "_save_lock", None)
- if save_lock is None:
- save_lock = threading.Lock()
- self._save_lock = save_lock
+ saver = self._routing_db_method("save_gateway_routing_entry")
+ if saver is not None:
try:
- with save_lock:
+ with self._lazy("_save_lock", threading.Lock):
if getattr(self, "_persisted_routing_generation", 0) >= revision:
return
- fast_persisted = getattr(self, "_fast_persisted_entries", None)
- if fast_persisted is None:
- fast_persisted = {}
- self._fast_persisted_entries = fast_persisted
+ fast_persisted = self._lazy("_fast_persisted_entries", dict)
persisted = fast_persisted.get(session_key)
if persisted is not None and persisted[0] >= revision:
return
@@ -2146,35 +1697,22 @@ class SessionStore:
session_key, exc,
)
if candidate_entry is not None:
- # DB upsert failed (or no DB): build the full snapshot now, carrying
- # the candidate entry so the fallback persists the intended
- # transition rather than re-snapshotting the unchanged live value.
+ # Full-snapshot fallback carrying the candidate transition.
+ def _snapshot() -> Dict[str, Any]:
+ return {key: current.to_dict() for key, current in self._entries.items()}
if lock_held:
- # Caller already holds _lock — build snapshot in-place.
- fallback_data: Dict[str, Any] = {
- key: current.to_dict()
- for key, current in self._entries.items()
- }
+ fallback_data = _snapshot()
else:
with self._lock:
- fallback_data = {
- key: current.to_dict()
- for key, current in self._entries.items()
- }
+ fallback_data = _snapshot()
fallback_data[session_key] = candidate_entry
self._persist_routing_data(fallback_data, revision)
else:
self._save_entries()
def _resolve_profile_for_key(self, source: Optional[SessionSource] = None) -> Optional[str]:
- """Return the profile namespace for session keys, or None when off.
-
- When ``multiplex_profiles`` is disabled (default), returns ``None`` so
- keys stay in the legacy ``agent:main`` namespace — byte-identical to
- before. When enabled, prefers the profile the inbound source was routed
- to (``source.profile`` — set by the /p/<profile>/ URL prefix or
- per-credential adapter), falling back to the active profile name.
- """
+ """Profile namespace for session keys: None when multiplexing is off
+ (legacy ``agent:main``), else ``source.profile`` or the active profile."""
if not getattr(self.config, "multiplex_profiles", False):
return None
if source is not None and source.profile:
@@ -2212,12 +1750,9 @@ class SessionStore:
) -> bool:
"""Prevent a gateway from reviving another profile's row.
- Single-profile: the recovered row's namespace must match the ACTIVE
- profile. Multiplexed: several profiles serve traffic at once, so the
- active profile is meaningless — the requested key carries the profile
- the turn was routed to, and the recovered row must sit in the same
- ``agent:<ns>:`` namespace (#74285). Rows with no key namespace stay
- adoptable in both modes (legacy/keyless data owned by this store).
+ Single-profile: the row's namespace must match the ACTIVE profile.
+ Multiplexed: it must match the namespace of the requested key (the
+ active profile is meaningless there). Keyless rows stay adoptable.
"""
recovered_key = str(recovered.get("session_key") or "")
if not recovered_key or recovered_key == requested_session_key:
@@ -2233,50 +1768,34 @@ class SessionStore:
return recovered_profile == self._active_profile_name()
- def _generate_session_key(self, source: SessionSource) -> str:
- """Generate a session key from a source."""
+ def _generate_session_key(self, source: SessionSource, key_source: Optional[SessionSource] = None) -> str:
+ """Session key for *source* (profile resolved from *source*, key built
+ from *key_source* when given)."""
return build_session_key(
- source,
+ key_source if key_source is not None else source,
group_sessions_per_user=getattr(self.config, "group_sessions_per_user", True),
thread_sessions_per_user=getattr(self.config, "thread_sessions_per_user", False),
profile=self._resolve_profile_for_key(source),
)
def _legacy_slack_session_key(self, source: SessionSource) -> Optional[str]:
- """Return the pre-workspace Slack key for an explicitly scoped source.
+ """Pre-workspace Slack key for an explicitly scoped source.
- The compatibility path is deliberately Slack-only. Discord and every
- other platform keep byte-identical keys, and an unscoped Slack session
- may be claimed by only one workspace because its old key contains no
- information that could safely distinguish multiple teams.
+ Deliberately Slack-only; an unscoped Slack session may be claimed by
+ only one workspace because its old key cannot distinguish teams.
"""
if source.platform != Platform.SLACK or not source.scope_id:
return None
- legacy_source = replace(source, scope_id=None, guild_id=None)
- return build_session_key(
- legacy_source,
- group_sessions_per_user=getattr(
- self.config, "group_sessions_per_user", True
- ),
- thread_sessions_per_user=getattr(
- self.config, "thread_sessions_per_user", False
- ),
- profile=self._resolve_profile_for_key(source),
+ return self._generate_session_key(
+ source, replace(source, scope_id=None, guild_id=None)
)
def _claim_legacy_slack_key(self, legacy_key: Optional[str]) -> bool:
"""Atomically reserve one ambiguous legacy Slack key for migration."""
if not legacy_key:
return False
- claim_lock = getattr(self, "_legacy_slack_claim_lock", None)
- if claim_lock is None:
- claim_lock = threading.Lock()
- self._legacy_slack_claim_lock = claim_lock
- with claim_lock:
- claimed = getattr(self, "_claimed_legacy_slack_keys", None)
- if claimed is None:
- claimed = set()
- self._claimed_legacy_slack_keys = claimed
+ with self._lazy("_legacy_slack_claim_lock", threading.Lock):
+ claimed = self._lazy("_claimed_legacy_slack_keys", set)
if legacy_key in claimed:
return False
claimed.add(legacy_key)
@@ -2288,13 +1807,9 @@ class SessionStore:
) -> bool:
"""Reject recovered rows whose recorded origin belongs to another workspace.
- Slack group/channel rows recorded with an origin_json carry the
- workspace (scope_id) they were created under. A workspace-scoped
- lookup must not adopt a row another team recorded — even via the
- legacy-key fallback — unless the recorded origin names the same
- workspace. Rows without a parseable origin are rejected for scoped
- sources: an unattributable transcript is precisely the ambiguity
- this guard exists to avoid.
+ A workspace-scoped Slack lookup adopts a row only if its origin_json
+ names the same scope_id; rows without a parseable origin are rejected
+ (an unattributable transcript is exactly the ambiguity to avoid).
"""
if (
source.platform != Platform.SLACK
@@ -2318,24 +1833,17 @@ class SessionStore:
source: SessionSource,
now: datetime,
) -> SessionEntry:
- started_at = row.get("started_at")
- try:
- created_at = datetime.fromtimestamp(float(started_at))
- except (TypeError, ValueError, OSError):
- # An invalid durable timestamp must look old, never freshly active.
- created_at = datetime.fromtimestamp(0)
- # The finder already returns the row's durable recency
- # (last_activity_at is what it ranks candidates by), so no extra DB
- # round-trip is needed: derive updated_at straight from the row.
+ def _ts(value, default: datetime) -> datetime:
+ try:
+ return datetime.fromtimestamp(float(value))
+ except (TypeError, ValueError, OSError):
+ return default
+
+ # An invalid durable timestamp must look old, never freshly active.
+ created_at = _ts(row.get("started_at"), datetime.fromtimestamp(0))
+ # The finder already returns durable recency; no extra round-trip.
last_activity = row.get("last_activity_at")
- try:
- updated_at = (
- datetime.fromtimestamp(float(last_activity))
- if last_activity is not None
- else created_at
- )
- except (TypeError, ValueError, OSError):
- updated_at = created_at
+ updated_at = _ts(last_activity, created_at) if last_activity is not None else created_at
had_activity = row.get("_has_messages")
if had_activity is None:
had_activity = bool(row.get("message_count") or 0) or (
@@ -2368,9 +1876,8 @@ class SessionStore:
another team's session. The caller performs one explicit exact lookup
of the old unscoped key instead.
"""
- if not self._db_for_key(session_key):
- return None
- finder = getattr(self._db_for_key(session_key), "find_latest_gateway_session_for_peer", None)
+ db = self._db_for_key(session_key)
+ finder = getattr(db, "find_latest_gateway_session_for_peer", None) if db else None
if not callable(finder):
return None
try:
@@ -2383,11 +1890,7 @@ class SessionStore:
thread_id=source.thread_id,
)
except Exception as exc:
- logger.debug(
- "Gateway session DB recovery failed for %s: %s",
- session_key,
- exc,
- )
+ logger.debug("Gateway session DB recovery failed for %s: %s", session_key, exc)
if raise_on_lookup_error:
raise
return None
@@ -2403,93 +1906,66 @@ class SessionStore:
"""Rebuild a missing session-key mapping from durable state.db data.
Returns ``None`` when no row is recoverable, or when the recovered
- session is already overdue under the configured reset policy — the
- row is then durably promoted to a reset boundary instead of being
- resurrected as freshly active.
+ session is already overdue under the reset policy — the row is then
+ durably promoted to a reset boundary instead of resurrected.
"""
- legacy_key = self._legacy_slack_session_key(source)
- recovered = self._find_gateway_session_row(
+ entry, migrated_legacy = self._query_recoverable_row(
session_key=session_key,
source=source,
- allow_peer_fallback=legacy_key is None,
+ now=now,
raise_on_lookup_error=raise_on_lookup_error,
)
- migrated_legacy = False
- if (
- not recovered
- and legacy_key
- and self._claim_legacy_slack_key(legacy_key)
- ):
- recovered = self._find_gateway_session_row(
- session_key=legacy_key,
- source=source,
- allow_peer_fallback=False,
- raise_on_lookup_error=raise_on_lookup_error,
- )
- migrated_legacy = bool(recovered)
- if not recovered:
- return None
- if not self._recovered_row_matches_source_scope(recovered, source):
- return None
- if not self._recovered_row_allowed_for_active_profile(
- requested_session_key=session_key,
- recovered=recovered,
- ):
- logger.warning(
- "Gateway session DB recovery ignored %s for %s because "
- "the row belongs to a different profile",
- recovered.get("session_key"),
- session_key,
- )
+ if entry is None:
return None
- entry = self._create_entry_from_recovered_row(
- row=recovered,
- session_key=session_key,
- source=source,
- now=now,
- )
reset_reason = self._should_reset(entry, source)
if reset_reason:
- try:
- promote = getattr(self._db_for_key(session_key), "promote_to_session_reset", None)
- if callable(promote):
- promote(entry.session_id, reset_reason)
- else:
- self._db_for_key(session_key).end_session(entry.session_id, reset_reason)
- except Exception as exc:
- logger.debug(
+ self._promote_session_reset(
+ session_key, entry.session_id, reset_reason,
+ log=lambda exc: logger.debug(
"Gateway recovered-session reset promotion failed for %s: %s",
- session_key,
- exc,
- )
+ session_key, exc,
+ ),
+ )
return None
- try:
- self._db_for_key(session_key).reopen_session(entry.session_id)
- except Exception as exc:
- logger.debug("Gateway session DB reopen failed for %s: %s", session_key, exc)
+ self._reopen_session_row(session_key, entry.session_id)
if migrated_legacy:
self._record_gateway_session_peer(
- entry.session_id,
- session_key,
- source,
- display_name=entry.display_name,
+ entry.session_id, session_key, source, display_name=entry.display_name,
)
return entry
- def _query_recoverable_session(
- self, *, session_key, source, now, lookup_session_key=None
- ):
+ def _query_recoverable_session(self, *, session_key, source, now):
"""DB-only half of _recover_session_from_db (no lock needed).
- Returns a SessionEntry or None. Caller assigns _entries[key] under lock.
- The returned entry's session row is NOT reopened here: the caller
- evaluates the reset policy first and decides reset vs resume.
+ Returns a SessionEntry or None. Caller assigns _entries[key] under
+ lock. The row is NOT reopened here: the caller evaluates reset policy
+ first (an agent_close/ws_orphan row may need promotion to a real reset
+ boundary instead).
+ """
+ entry, migrated_legacy = self._query_recoverable_row(
+ session_key=session_key, source=source, now=now,
+ )
+ if entry is not None and migrated_legacy:
+ self._record_gateway_session_peer(
+ entry.session_id, session_key, source, display_name=entry.display_name,
+ )
+ return entry
+
+ def _query_recoverable_row(
+ self, *, session_key, source, now, raise_on_lookup_error=False,
+ ) -> tuple[Optional[SessionEntry], bool]:
+ """Find and gate a recoverable row -> (entry or None, migrated_legacy).
+
+ The legacy (pre-workspace) Slack key fallback lives here: exact-key
+ lookup, claimed once per process; ``migrated_legacy`` tells the caller
+ to rewrite the peer row to the scoped key.
"""
legacy_key = self._legacy_slack_session_key(source)
recovered = self._find_gateway_session_row(
session_key=session_key,
source=source,
allow_peer_fallback=legacy_key is None,
+ raise_on_lookup_error=raise_on_lookup_error,
)
migrated_legacy = False
if (
@@ -2501,12 +1977,13 @@ class SessionStore:
session_key=legacy_key,
source=source,
allow_peer_fallback=False,
+ raise_on_lookup_error=raise_on_lookup_error,
)
migrated_legacy = bool(recovered)
if not isinstance(recovered, dict):
- return None
+ return None, False
if not self._recovered_row_matches_source_scope(recovered, source):
- return None
+ return None, False
if not self._recovered_row_allowed_for_active_profile(
requested_session_key=session_key,
recovered=recovered,
@@ -2517,21 +1994,37 @@ class SessionStore:
recovered.get("session_key"),
session_key,
)
- return None
- # Reopen only after the caller evaluates reset policy against durable
- # last activity. An agent_close/ws_orphan row may need promotion to a
- # real reset boundary instead.
+ return None, False
entry = self._create_entry_from_recovered_row(
row=recovered, session_key=session_key, source=source, now=now,
)
- if migrated_legacy:
- self._record_gateway_session_peer(
- entry.session_id,
- session_key,
- source,
- display_name=entry.display_name,
- )
- return entry
+ return entry, migrated_legacy
+
+ def _promote_session_reset(self, session_key: str, session_id: str, reason: str, *, log) -> None:
+ """End *session_id* with *reason* via ``promote_to_session_reset``.
+
+ Promote (not plain ``end_session``): a row already ended with a
+ recoverable accidental reason (agent_close / ws_orphan_reap) must be
+ upgraded to the explicit boundary, or stale-route recovery resurrects
+ it over the reset. Falls back to ``end_session`` on old SessionDBs.
+ ``log(exc)`` reports failures (each caller has its own message).
+ """
+ try:
+ db = self._db_for_key(session_key)
+ promote = getattr(db, "promote_to_session_reset", None)
+ if callable(promote):
+ promote(session_id, reason)
+ else:
+ db.end_session(session_id, reason)
+ except Exception as exc:
+ log(exc)
+
+ def _reopen_session_row(self, session_key: str, session_id: str) -> None:
+ try:
+ self._db_for_key(session_key).reopen_session(session_id)
+ except Exception as exc:
+ logger.debug("Gateway session DB reopen failed for %s: %s", session_key, exc)
+
def _record_gateway_session_peer(
self,
session_id: str,
@@ -2541,23 +2034,27 @@ class SessionStore:
include_compression_ancestors: bool = False,
) -> None:
"""Persist the routing peer for an existing gateway session row."""
- if not self._db_for_key(session_key) or not source:
+ db = self._db_for_key(session_key)
+ if not db or not source:
return
- recorder = getattr(self._db_for_key(session_key), "record_gateway_session_peer", None)
+ recorder = getattr(db, "record_gateway_session_peer", None)
if not callable(recorder):
return
+ peer = dict(
+ source=source.platform.value,
+ user_id=source.user_id,
+ session_key=session_key,
+ chat_id=source.chat_id,
+ chat_type=source.chat_type,
+ thread_id=source.thread_id,
+ )
try:
origin_json = None
with contextlib.suppress(Exception):
origin_json = json.dumps(source.to_dict())
recorder(
session_id,
- source=source.platform.value,
- user_id=source.user_id,
- session_key=session_key,
- chat_id=source.chat_id,
- chat_type=source.chat_type,
- thread_id=source.thread_id,
+ **peer,
display_name=display_name or source.chat_name,
origin_json=origin_json,
include_compression_ancestors=include_compression_ancestors,
@@ -2565,15 +2062,7 @@ class SessionStore:
except TypeError:
# Older SessionDB without display_name/origin_json kwargs.
try:
- recorder(
- session_id,
- source=source.platform.value,
- user_id=source.user_id,
- session_key=session_key,
- chat_id=source.chat_id,
- chat_type=source.chat_type,
- thread_id=source.thread_id,
- )
+ recorder(session_id, **peer)
except Exception as exc:
logger.debug("Gateway session peer record failed for %s: %s", session_key, exc)
except Exception as exc:
@@ -2584,24 +2073,18 @@ class SessionStore:
) -> None:
"""Mark a session entry expiry-finalized in memory, sessions.json, AND state.db.
- Single write-path for the expiry watcher (#9006): keeps the durable
- state.db flag in sync with the JSON routing index so the flag
- survives sessions.json pruning/loss.
-
- ``clear_model_override=False`` preserves the give-up path's original
- behavior (flag only, no override drop).
+ Single write-path for the expiry watcher so the durable flag survives
+ sessions.json loss. ``clear_model_override=False`` = flag only.
"""
with self._lock:
entry.expiry_finalized = True
if clear_model_override:
- # Session finalization is a conversation boundary — drop the
- # persisted /model override too so a later message doesn't
- # rehydrate it after the in-memory override was popped.
+ # Finalization is a conversation boundary: drop the persisted
+ # /model override so a later message cannot rehydrate it.
entry.model_override = None
self._save()
- # The expiry watcher calls this from a background task that never
- # entered ``_profile_runtime_scope``, so resolve the store from the
- # key rather than from the ambient scope (#66887).
+ # Background caller never entered ``_profile_runtime_scope``: resolve
+ # the store from the key, not the ambient scope.
_db = self._db_for_key(entry.session_key)
if _db:
setter = getattr(_db, "set_expiry_finalized", None)
@@ -2609,89 +2092,56 @@ class SessionStore:
try:
setter(entry.session_id, True)
except Exception as exc:
- logger.debug(
- "Session DB expiry_finalized write failed for %s: %s",
- entry.session_id, exc,
- )
+ logger.debug("Session DB expiry_finalized write failed for %s: %s", entry.session_id, exc)
try:
- # Expiry finalization is a real conversation boundary. Without
- # a durable ``session_reset`` end_reason, later agent cleanup can
- # close the row as ``agent_close``; stale-route recovery treats
- # that as resumable and resurrects the expired full history.
- #
- # promote_to_session_reset is conditional: it only promotes
- # live rows or rows ended with ``agent_close``. Explicit
- # boundaries (compression, session_reset, new_command, etc.)
- # are preserved — the first writer wins.
+ # Without a durable ``session_reset`` end_reason, later agent
+ # cleanup ends the row as ``agent_close``, which stale-route
+ # recovery treats as resumable. Promotion only upgrades live/
+ # agent_close rows; explicit boundaries are preserved.
_db.promote_to_session_reset(entry.session_id)
except Exception as exc:
- logger.debug(
- "Session DB promote_to_session_reset failed for %s: %s",
- entry.session_id, exc,
- )
+ logger.debug("Session DB promote_to_session_reset failed for %s: %s", entry.session_id, exc)
- def _is_session_expired(self, entry: SessionEntry) -> bool:
- """Check if a session has expired based on its reset policy.
-
- Works from the entry alone — no SessionSource needed.
- Used by the background expiry watcher to proactively flush memories.
- Sessions with active background processes are never considered expired.
- """
- if self._has_active_processes_safe(entry.session_key, context="expiry"):
- logger.debug(
- "Session %s not expired — active background processes",
- entry.session_key,
- )
- return False
-
- policy = self.config.get_reset_policy(
- platform=entry.platform,
- session_type=entry.chat_type,
- )
-
+ @staticmethod
+ def _policy_reset_reason(policy, updated_at: datetime) -> Optional[str]:
+ """Return "idle"/"daily" when *updated_at* is overdue under *policy*, else None."""
if policy.mode == "none":
- return False
-
+ return None
now = _now()
-
- if policy.mode in {"idle", "both"}:
- idle_deadline = entry.updated_at + timedelta(minutes=policy.idle_minutes)
- if now > idle_deadline:
- return True
-
+ if policy.mode in {"idle", "both"} and now > updated_at + timedelta(minutes=policy.idle_minutes):
+ return "idle"
if policy.mode in {"daily", "both"}:
today_reset = now.replace(
- hour=policy.at_hour,
- minute=0, second=0, microsecond=0,
+ hour=policy.at_hour, minute=0, second=0, microsecond=0,
)
if now.hour < policy.at_hour:
today_reset -= timedelta(days=1)
- if entry.updated_at < today_reset:
- return True
+ if updated_at < today_reset:
+ return "daily"
+ return None
- return False
+ def _is_session_expired(self, entry: SessionEntry) -> bool:
+ """Whether the entry's reset policy has expired it (entry alone, no source).
+
+ Used by the background expiry watcher. Sessions with active
+ background processes are never considered expired.
+ """
+ if self._has_active_processes_safe(entry.session_key, context="expiry"):
+ logger.debug("Session %s not expired — active background processes", entry.session_key)
+ return False
+ policy = self.config.get_reset_policy(
+ platform=entry.platform,
+ session_type=entry.chat_type,
+ )
+ return self._policy_reset_reason(policy, entry.updated_at) is not None
def is_session_finalizable(self, entry: SessionEntry) -> bool:
- """Return True if the expiry watcher will *ever* finalize this session.
-
- The expiry watcher (``GatewayRunner._session_expiry_watcher``) only
- tears an agent down — and only then fires ``on_session_end`` — for
- sessions whose reset policy eventually expires. A ``mode == "none"``
- session never expires (``_is_session_expired`` returns ``False``
- forever), so the watcher will never finalize it.
-
- This distinction matters for the agent-cache idle sweep: deferring
- idle eviction to "let the watcher finalize it later" is only correct
- when the watcher WILL run for this session. For a ``mode == "none"``
- session, deferring pins the cached agent in memory for the gateway's
- entire lifetime with no finalization ever coming — the exact leak the
- idle sweep exists to relieve. Callers use this predicate to decide
- whether the session store owns the eviction boundary (finalizable) or
- the idle sweep must still reap the agent itself (not finalizable).
-
- Public wrapper so callers don't reach into policy internals. Errors
- resolving the policy are treated as "not finalizable" (safe: the idle
- sweep falls back to reaping the agent rather than pinning it).
+ """True if the expiry watcher will *ever* finalize this session.
+
+ A ``mode == "none"`` session never expires, so the agent-cache idle
+ sweep must reap its agent itself instead of deferring to the watcher
+ (deferring would pin the agent for the gateway's lifetime). Policy
+ resolution errors count as "not finalizable" (sweep reaps — safe).
"""
try:
policy = self.config.get_reset_policy(
@@ -2703,26 +2153,13 @@ class SessionStore:
return False
def _is_session_ended_in_db(self, session_id: str) -> bool:
- """Return True iff state.db has this session with a non-null end_reason.
-
- Mirrors the staleness test in ``_prune_stale_sessions_locked``:
- - no DB handle / no session_id -> False (can't tell — keep)
- - row absent (legacy / not yet persisted) -> False (keep)
- - end_reason is None -> False (alive — keep)
- - end_reason not None -> True (ended — stale)
-
- Used by ``get_or_create_session`` to self-heal at routing time:
- ``_prune_stale_sessions_locked`` only runs at startup, so a session
- ended in the DB while the gateway stays alive (any path that finalizes
- the row without clearing sessions.json) would otherwise be reused as a
- live routing key and silently swallow every subsequent message until
- the next restart (#54878 — the live-gateway variant of #52804/FM9).
- DB errors are non-fatal — never block routing on a failed lookup.
-
- The store is resolved from the row's owning profile rather than the
- ambient scope: an unscoped background writer keeps its own copy of
- the same session, and comparing against that copy reports a live
- session as ended (#66887).
+ """True iff state.db has this session with a non-null end_reason.
+
+ Same staleness test as ``_prune_stale_sessions_locked`` (no DB, no
+ row, or DB error -> False, keep). Used by ``get_or_create_session``
+ to self-heal at routing time, since the startup prune cannot see a
+ session ended while the gateway stays alive. Store resolved from the
+ row's owning profile, not the ambient scope.
"""
db = self._db_for_session_id(session_id)
if not db or not session_id:
@@ -2734,70 +2171,32 @@ class SessionStore:
return bool(row is not None and row.get("end_reason") is not None)
def _should_reset(self, entry: SessionEntry, source: SessionSource) -> Optional[str]:
- """
- Check if a session should be reset based on policy.
-
- Returns the reset reason ("idle" or "daily") if a reset is needed,
- or None if the session is still valid.
-
+ """Return the reset reason ("idle"/"daily") if policy says reset, else None.
+
Sessions with active background processes are never reset.
"""
session_key = self._generate_session_key(source)
if self._has_active_processes_safe(session_key, context="reset"):
- logger.debug(
- "Session reset skipped for %s — active background processes",
- session_key,
- )
+ logger.debug("Session reset skipped for %s — active background processes", session_key)
return None
-
policy = self.config.get_reset_policy(
platform=source.platform,
session_type=source.chat_type
)
-
- if policy.mode == "none":
- return None
-
- now = _now()
-
- if policy.mode in {"idle", "both"}:
- idle_deadline = entry.updated_at + timedelta(minutes=policy.idle_minutes)
- if now > idle_deadline:
- return "idle"
-
- if policy.mode in {"daily", "both"}:
- today_reset = now.replace(
- hour=policy.at_hour,
- minute=0,
- second=0,
- microsecond=0
- )
- if now.hour < policy.at_hour:
- today_reset -= timedelta(days=1)
-
- if entry.updated_at < today_reset:
- return "daily"
-
- return None
+ return self._policy_reset_reason(policy, entry.updated_at)
def _compression_tip_for_session_id(self, session_id: Optional[str]) -> Optional[str]:
- """Return the latest compression continuation for *session_id*.
-
- When an agent compresses context mid-turn the transcript moves to a
- child session, but a restart or failed send can leave the SessionStore
- mapping pointing at the compressed parent. Heal that on read so the
- next inbound message resumes the child instead of reloading the parent.
- """
- if not session_id or self._db_for_session_id(session_id) is None:
+ """Latest compression continuation for *session_id* (heals a mapping
+ left pointing at a compressed parent by a restart or failed send)."""
+ if not session_id:
+ return session_id
+ db = self._db_for_session_id(session_id)
+ if db is None:
return session_id
try:
- return self._db_for_session_id(session_id).get_compression_tip(session_id) or session_id
+ return db.get_compression_tip(session_id) or session_id
except Exception:
- logger.debug(
- "Compression-tip lookup failed for session %s",
- session_id,
- exc_info=True,
- )
+ logger.debug("Compression-tip lookup failed for session %s", session_id, exc_info=True)
return session_id
def _heal_compression_tip_locked(
@@ -2823,23 +2222,17 @@ class SessionStore:
return True
def has_any_sessions(self) -> bool:
- """Check if any sessions have ever been created (across all platforms).
-
- Uses the SQLite database as the source of truth because it preserves
- historical session records (ended sessions still count). The in-memory
- ``_entries`` dict replaces entries on reset, so ``len(_entries)`` would
- stay at 1 for single-platform users — which is the bug this fixes.
+ """Whether any session has ever been created (across all platforms).
- The current session is already in the DB by the time this is called
- (get_or_create_session runs first), so we check ``> 1``.
+ SQLite is the source of truth (ended sessions count; ``_entries`` is
+ replaced on reset). The current session is already in the DB when
+ this runs, hence ``> 1``.
"""
if self._db:
try:
return self._db.session_count_ge(2)
except Exception:
pass # fall through to heuristic
- # Fallback: check if sessions.json was loaded with existing data.
- # This covers the rare case where the DB is unavailable.
with self._lock:
self._ensure_loaded_locked()
return len(self._entries) > 1
@@ -2859,11 +2252,8 @@ class SessionStore:
prior user-activity clock when an internal/system event reuses a session.
"""
session_key = self._generate_session_key(source)
- inflight_lock = getattr(self, "_inflight_lock", None)
- if inflight_lock is None:
- inflight_lock = threading.Lock()
- self._inflight_lock = inflight_lock
- self._inflight_sessions = {}
+ inflight_lock = self._lazy("_inflight_lock", threading.Lock)
+ self._lazy("_inflight_sessions", dict)
with inflight_lock:
slot = self._inflight_sessions.get(session_key)
@@ -2914,20 +2304,12 @@ class SessionStore:
session_key = self._generate_session_key(source)
now = _now()
- # One-time routing-index migration for Slack sessions created before
- # workspace scope was part of the key. Move (rather than copy) the
- # legacy entry so a second workspace with identical Slack ids cannot
- # attach to the same transcript.
- #
- # Adoption policy (composed from #20583/#66398 and #68925):
- # - The legacy entry's recorded origin names a workspace → migrate
- # only when it matches the incoming workspace (precise).
- # - Scope-less origin, DM → first workspace claims it once
- # (claim-once): a 1:1 DM has a single human peer, so continuity
- # across the key-format change outweighs the ambiguity risk.
- # - Scope-less origin, channel/group → refuse: channel ids collide
- # across workspaces and a shared transcript leaking to a second
- # tenant is exactly the bug this fix removes.
+ # One-time migration of pre-workspace-scope Slack keys: MOVE (not
+ # copy) the legacy entry so a second workspace with identical Slack
+ # ids cannot attach to the same transcript. Adopt when the legacy
+ # origin names the same workspace; a scope-less DM is claimed once by
+ # the first workspace; a scope-less channel/group is refused (channel
+ # ids collide across workspaces).
migrated_legacy_entry: Optional[SessionEntry] = None
legacy_key = self._legacy_slack_session_key(source)
if legacy_key and not force_new:
@@ -2935,11 +2317,7 @@ class SessionStore:
self._ensure_loaded_locked()
legacy_entry = self._entries.get(legacy_key)
if session_key not in self._entries and legacy_entry is not None:
- origin_scope = (
- getattr(legacy_entry.origin, "scope_id", None)
- if legacy_entry.origin is not None
- else None
- )
+ origin_scope = getattr(legacy_entry.origin, "scope_id", None)
if origin_scope is not None:
adopt = origin_scope == source.scope_id
else:
@@ -3001,12 +2379,10 @@ class SessionStore:
elif _entry_for_checks.resume_pending:
_reset_reason = self._should_reset(_entry_for_checks, source)
if not _reset_reason:
- # Freshness-gate stale resume_pending zombies (#46934) —
- # but honor an explicit ``session_reset.mode: none``: the
- # user opted out of ALL automatic resets, so an expired
- # resume marker must fall through to a normal resume of
- # the preserved transcript, never a silent fresh session
- # (#61052).
+ # Freshness-gate stale resume_pending zombies — but honor
+ # ``session_reset.mode: none`` (user opted out of ALL
+ # automatic resets): an expired marker then falls through
+ # to a normal resume, never a silent fresh session.
_policy = self.config.get_reset_policy(
platform=source.platform,
session_type=source.chat_type,
@@ -3024,10 +2400,8 @@ class SessionStore:
# ---- Phase 2: lock write -- apply decisions to _entries ----
_needs_save = False
- # Healthy-path saves only bump updated_at on one entry; they take
- # the single-row UPSERT fast path instead of the full index rewrite
- # (see _save_entry). Structural transitions (recover/create below)
- # keep the full rewrite.
+ # Healthy-path saves take the single-row UPSERT fast path; structural
+ # transitions (recover/create) keep the full rewrite.
_metadata_only_save = False
_needs_recover = False
entry: Optional[SessionEntry] = None
@@ -3042,20 +2416,19 @@ class SessionStore:
if session_key in self._entries and not force_new:
entry = self._entries[session_key]
# A heal rewrites entry.session_id, so it must reach the
- # sessions.json mirror too: force the full-rewrite save
- # below (the fast path persists state.db only).
+ # sessions.json mirror too (forces the full-rewrite save).
_healed = self._heal_compression_tip_locked(
entry, existing_session_id, canonical_existing_session_id
)
-
- if _is_stale and entry.session_id == _stale_session_id:
- # Stale routing self-heal (#54878): the in-memory entry
- # points at a session that has ALREADY been ended in
- # state.db. Drop it and fall through to recovery/create.
- # Recovery finder reopens ``agent_close`` and mistaken
- # ``ws_orphan_reap`` rows (preserving the transcript) but
- # returns None for other end_reasons (e.g. /new), starting
- # a fresh session.
+ # If another thread replaced the entry during our lock-free
+ # window, the stale/reset decisions no longer apply: healthy.
+ _checked = entry.session_id == _stale_session_id
+ _stale_hit = _is_stale and _checked
+ if _stale_hit:
+ # Stale routing self-heal: the entry points at a session
+ # ALREADY ended in state.db. Drop it and fall through to
+ # recovery (reopens agent_close / ws_orphan_reap rows,
+ # fresh session for other end_reasons).
logger.warning(
"gateway.session: routing key %r -> %s is ended in "
"state.db but still live in sessions.json; dropping "
@@ -3063,52 +2436,29 @@ class SessionStore:
"(#54878)",
session_key, entry.session_id,
)
- self._entries.pop(session_key, None)
- # If an expiry watcher (daily/idle reset) already finalized
- # this session, honour the reset decision instead of silently
- # reopening it via recovery.
+ if _stale_hit or (_checked and _reset_reason):
+ # Honour an expiry/reset decision instead of silently
+ # reopening the session via recovery.
if _reset_reason:
was_auto_reset = True
auto_reset_reason = _reset_reason
reset_had_activity = entry.last_prompt_tokens > 0
db_end_session_id = entry.session_id
prev_session_id = entry.session_id
+ self._entries.pop(session_key, None)
entry = None
_needs_recover = True
- elif entry.session_id != _stale_session_id:
- # Another thread handled this entry during our lock-free
- # window. Treat as healthy; internal/system events preserve
- # the prior user-activity clock used by reset policy.
+ else:
+ # Internal/system events preserve the user-activity clock.
if touch_activity:
entry.updated_at = now
_needs_save = touch_activity or _healed
_metadata_only_save = touch_activity and not _healed
- else:
- # Stale check clean. Apply reset decision.
- if _reset_reason:
- was_auto_reset = True
- auto_reset_reason = _reset_reason
- reset_had_activity = entry.last_prompt_tokens > 0
- db_end_session_id = entry.session_id
- prev_session_id = entry.session_id
- self._entries.pop(session_key, None)
- entry = None
- _needs_recover = True
- else:
- if touch_activity:
- entry.updated_at = now
- _needs_save = touch_activity or _healed
- _metadata_only_save = touch_activity and not _healed
- else:
- if not force_new:
- _needs_recover = True
+ elif not force_new:
+ _needs_recover = True
# ---- Phase 3: no-lock I/O -- recovery + create + save + DB ops ----
if _needs_recover and db_end_session_id is None:
- # The legacy (pre-workspace) Slack key fallback happens INSIDE
- # _query_recoverable_session (#20583/#66398 design): it performs
- # the exact-key legacy lookup, claims the key once per process,
- # and rewrites the peer row to the scoped key on success.
recovered = self._query_recoverable_session(
session_key=session_key, source=source, now=now,
)
@@ -3121,14 +2471,7 @@ class SessionStore:
db_end_session_id = recovered.session_id
prev_session_id = recovered.session_id
else:
- try:
- self._db_for_key(session_key).reopen_session(recovered.session_id)
- except Exception as exc:
- logger.debug(
- "Gateway session DB reopen failed for %s: %s",
- session_key,
- exc,
- )
+ self._reopen_session_row(session_key, recovered.session_id)
with self._lock:
published = self._entries.get(session_key)
if published is None:
@@ -3140,7 +2483,7 @@ class SessionStore:
if entry is None:
# Create a candidate outside the lock, then publish only if another
# worker has not already populated this routing key.
- session_id = f"{now.strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}"
+ session_id = _new_session_id(now)
candidate = SessionEntry(
session_key=session_key,
session_id=session_id,
@@ -3169,31 +2512,14 @@ class SessionStore:
entry = published
_needs_save = True
if entry is candidate:
- try:
- _origin_json = json.dumps(source.to_dict())
- except Exception:
- _origin_json = None
- db_create_kwargs = {
- "session_id": session_id,
- "source": source.platform.value,
- "user_id": source.user_id,
- "session_key": session_key,
- "chat_id": source.chat_id,
- "chat_type": source.chat_type,
- "thread_id": source.thread_id,
- "profile_name": source.profile,
- # Identity lands atomically in the INSERT (#82616): a
- # crash after this write can no longer strand the row
- # unroutable, and lineage survives resets (#12857).
- "origin_json": _origin_json,
- "display_name": source.chat_name,
- "parent_session_id": prev_session_id,
- "model_config": (
- {"_reset_from": prev_session_id}
- if prev_session_id
- else None
- ),
- }
+ db_create_kwargs = self._session_create_kwargs(
+ session_id=session_id,
+ session_key=session_key,
+ origin=source,
+ source_value=source.platform.value,
+ display_name=source.chat_name,
+ parent_session_id=prev_session_id,
+ )
if _needs_save:
if _metadata_only_save:
@@ -3201,57 +2527,82 @@ class SessionStore:
else:
self._save_entries()
- # SQLite operations outside the lock (unchanged).
+ # SQLite operations outside the lock.
if self._db_for_key(session_key) and db_end_session_id:
# Use the specific reset reason so state.db is auditable (e.g.
- # "resume_pending_expired" is distinguishable from a normal
- # "session_reset" caused by idle/daily expiry).
- _db_end_reason = auto_reset_reason if auto_reset_reason else "session_reset"
- try:
- # promote_to_session_reset, not end_session: the row may
- # already be ended with a recoverable accidental reason
- # (agent_close / ws_orphan_reap), which first-reason-wins
- # end_session would preserve — leaving the reset session
- # resurrectable by stale-route recovery (#61220, #61993).
- _promote = getattr(self._db_for_key(session_key), "promote_to_session_reset", None)
- if callable(_promote):
- _promote(db_end_session_id, _db_end_reason)
- else:
- self._db_for_key(session_key).end_session(db_end_session_id, _db_end_reason)
- except Exception as e:
- # A failed end-write leaves a zombie open row still holding
- # this chat's session_key: restart recovery will resolve the
- # chat to it and time-travel the conversation (#82616). Say
- # so loudly — this was a silent logger.debug for months.
- logger.warning(
+ # "resume_pending_expired" vs a plain idle/daily "session_reset").
+ self._promote_session_reset(
+ session_key, db_end_session_id,
+ auto_reset_reason if auto_reset_reason else "session_reset",
+ log=lambda e: logger.warning(
"Failed to end predecessor session row %s for %s: %s — "
"the old row remains open and may win restart recovery "
"until the next successful peer refresh",
db_end_session_id, session_key, e,
- )
+ ),
+ )
if self._db_for_key(session_key) and db_create_kwargs:
- try:
- self._db_for_key(session_key).create_session(**db_create_kwargs)
- self._record_gateway_session_peer(
- session_id,
- session_key,
- source,
- display_name=entry.display_name,
- )
- except Exception as e:
- # The row will be self-healed with full identity by the next
- # per-turn peer refresh (record_gateway_session_peer now
- # INSERTs on missing row, #82616) — but the failure itself is
- # a routing hazard and must be visible, not a bare print.
- logger.warning(
+ self._create_session_row(
+ session_key, db_create_kwargs, source, entry.display_name,
+ log=lambda e: logger.warning(
"Failed to create session row %s for %s: %s — deferring "
"to the self-healing peer refresh on the next turn",
db_create_kwargs.get("session_id"), session_key, e,
- )
+ ),
+ )
return entry
+ @staticmethod
+ def _session_create_kwargs(
+ *, session_id, session_key, origin, source_value, display_name, parent_session_id,
+ ) -> Dict[str, Any]:
+ """kwargs for ``SessionDB.create_session``.
+
+ Identity (origin_json) and lineage (parent/_reset_from) land atomically
+ in the INSERT so a crash right after cannot strand the row unroutable.
+ """
+ origin_json = None
+ if origin is not None:
+ try:
+ origin_json = json.dumps(origin.to_dict())
+ except Exception:
+ origin_json = None
+ return {
+ "session_id": session_id,
+ "source": source_value,
+ "user_id": origin.user_id if origin else None,
+ "session_key": session_key,
+ "chat_id": origin.chat_id if origin else None,
+ "chat_type": origin.chat_type if origin else None,
+ "thread_id": origin.thread_id if origin else None,
+ "profile_name": origin.profile if origin else None,
+ "origin_json": origin_json,
+ "display_name": display_name,
+ "parent_session_id": parent_session_id,
+ "model_config": (
+ {"_reset_from": parent_session_id} if parent_session_id else None
+ ),
+ }
+
+ def _create_session_row(self, session_key, db_create_kwargs, origin, display_name, *, log) -> None:
+ """INSERT a session row and record its routing peer; ``log(exc)`` on failure.
+
+ A failed create is a routing hazard (visible warning), but the row is
+ self-healed with full identity by the next per-turn peer refresh.
+ """
+ try:
+ self._db_for_key(session_key).create_session(**db_create_kwargs)
+ self._record_gateway_session_peer(
+ db_create_kwargs["session_id"],
+ session_key,
+ origin,
+ display_name=display_name,
+ )
+ except Exception as e:
+ log(e)
+
def update_session(
self,
session_key: str,
@@ -3264,23 +2615,19 @@ class SessionStore:
user-activity clock that drives idle and daily reset policy.
"""
with self._lock:
- self._ensure_loaded_locked()
- entry = self._entries.get(session_key)
+ entry = self._entry_locked(session_key)
if entry is None:
return
if touch_activity:
entry.updated_at = _now()
if last_prompt_tokens is not None:
entry.last_prompt_tokens = last_prompt_tokens
- # Snapshot peer fields while still holding _lock: a concurrent
- # reset/heal may rewrite the entry, and mixing old and new
- # fields would record a torn peer row.
+ # Snapshot peer fields under _lock so a concurrent reset/heal
+ # cannot produce a torn peer row.
peer_session_id = entry.session_id
peer_origin = entry.origin
peer_display_name = entry.display_name
- # Metadata-only change on one entry: single-row UPSERT instead of
- # the full index rewrite (see _save_entry). Both writes run outside
- # ``_lock`` so the SQLite commit never blocks routing lookups.
+ # Metadata-only: single-row UPSERT, outside ``_lock``.
self._save_entry(session_key)
self._record_gateway_session_peer(
peer_session_id,
@@ -3297,8 +2644,7 @@ class SessionStore:
) -> Any:
"""Return a metadata value stored on a live session entry."""
with self._lock:
- self._ensure_loaded_locked()
- entry = self._entries.get(session_key)
+ entry = self._entry_locked(session_key)
if entry is None:
return default
return entry.metadata.get(key, default)
@@ -3309,21 +2655,14 @@ class SessionStore:
key: str,
value: Any,
) -> bool:
- """Persist a metadata value on a live session entry.
+ """Persist a small, JSON-serializable metadata value on a live entry.
- Values must be small and JSON-serializable — they are written into
- the routing index (state.db gateway_routing table + the legacy
- sessions.json mirror) so they survive gateway restarts.
-
- Metadata writes are internal bookkeeping and deliberately do NOT
- advance ``updated_at``: it is the user-activity clock that drives
- idle/daily reset policy and the restart-resume freshness gate
- (#85709), and a background write must not make an idle session look
- fresh.
+ Deliberately does NOT advance ``updated_at`` (the user-activity clock
+ behind reset policy and the resume freshness gate): a background
+ write must not make an idle session look fresh.
"""
with self._lock:
- self._ensure_loaded_locked()
- entry = self._entries.get(session_key)
+ entry = self._entry_locked(session_key)
if entry is None:
return False
entry.metadata[key] = value
@@ -3333,17 +2672,10 @@ class SessionStore:
def set_model_override(
self, session_key: str, override: Optional[Dict[str, Any]]
) -> None:
- """Persist (or clear) the session-scoped /model override.
-
- Only non-secret keys (model/provider/base_url — see
- ``sanitize_model_override``) are written; ``api_key``/``api_mode``
- are re-resolved at rehydration time via the normal runtime provider
- resolution. Pass ``None`` (or a dict with no persistable values)
- to clear the persisted override, e.g. on /new.
- """
+ """Persist (or clear, with ``None``) the session-scoped /model override;
+ only non-secret keys are written (see ``sanitize_model_override``)."""
with self._lock:
- self._ensure_loaded_locked()
- entry = self._entries.get(session_key)
+ entry = self._entry_locked(session_key)
if entry is None:
return
cleaned = sanitize_model_override(override)
@@ -3355,23 +2687,18 @@ class SessionStore:
def get_model_override(self, session_key: str) -> Optional[Dict[str, str]]:
"""Return the persisted /model override for *session_key*, if any."""
with self._lock:
- self._ensure_loaded_locked()
- entry = self._entries.get(session_key)
+ entry = self._entry_locked(session_key)
if entry is None:
return None
return dict(entry.model_override) if entry.model_override else None
def suspend_session(self, session_key: str) -> bool:
- """Mark a session as suspended so it auto-resets on next access.
-
- Used by ``/stop`` to prevent stuck sessions from being resumed
- after a gateway restart (#7536). Returns True if the session
- existed and was marked.
- """
+ """Mark a session suspended so it auto-resets on next access (/stop).
+ Returns True if the session existed."""
with self._lock:
- self._ensure_loaded_locked()
- if session_key in self._entries:
- self._entries[session_key].suspended = True
+ entry = self._entry_locked(session_key)
+ if entry is not None:
+ entry.suspended = True
self._save()
return True
return False
@@ -3385,26 +2712,20 @@ class SessionStore:
"""
token = uuid.uuid4().hex
with self._lock:
- self._ensure_loaded_locked()
- entry = self._entries.get(session_key)
+ entry = self._entry_locked(session_key)
if entry is None:
return None
now = _now()
candidate = entry.to_dict()
candidate["active_turn_token"] = token
candidate["active_turn_started_at"] = now.isoformat()
- # Keep the legacy 120-second startup heuristic effective during a
- # rolling downgrade/upgrade window where an older binary cannot
- # understand the exact marker fields.
+ # Keeps the legacy 120s startup heuristic working for an older
+ # binary during a rolling downgrade/upgrade window.
candidate["updated_at"] = now.isoformat()
- # Persist before publishing the marker in memory. If the durable
- # write raises, a later unrelated save cannot leak an unowned token.
- self._save_entry(
- session_key,
- entry_data=candidate,
- lock_held=True,
- )
+ # Persist before publishing in memory so a failed write cannot
+ # leak an unowned token through a later unrelated save.
+ self._save_entry(session_key, entry_data=candidate, lock_held=True)
entry.active_turn_token = token
entry.active_turn_started_at = now
entry.updated_at = now
@@ -3416,21 +2737,15 @@ class SessionStore:
Returns ``False`` when the entry disappeared or a newer turn owns it.
"""
with self._lock:
- self._ensure_loaded_locked()
- entry = self._entries.get(session_key)
+ entry = self._entry_locked(session_key)
if entry is None or entry.active_turn_token != token:
return False
candidate = entry.to_dict()
candidate["active_turn_token"] = None
candidate["active_turn_started_at"] = None
- # Keep the live token until the clear is durable. A failed write
- # therefore remains retryable instead of becoming a false mismatch.
- self._save_entry(
- session_key,
- entry_data=candidate,
- lock_held=True,
- )
+ # Keep the live token until the clear is durable (retryable).
+ self._save_entry(session_key, entry_data=candidate, lock_held=True)
entry.active_turn_token = None
entry.active_turn_started_at = None
return True
@@ -3439,17 +2754,11 @@ class SessionStore:
self,
max_age_seconds: int = 60 * 60,
) -> int:
- """Promote exact crash-left turn markers into ``resume_pending``.
+ """Promote crash-left turn markers into ``resume_pending`` (unclean startup only).
- This must only be called by the unclean-startup path. Old or invalid
- markers are cleared without resuming so a downgrade/re-upgrade cycle
- cannot revive arbitrarily stale work. Explicitly suspended sessions
- are likewise never re-armed.
-
- Returns the number of newly promoted sessions.
+ Old/invalid markers are cleared without resuming; suspended sessions
+ are never re-armed. Returns the number of newly promoted sessions.
"""
- from datetime import timedelta
-
now = _now()
max_age = timedelta(seconds=max(0, max_age_seconds))
promoted = 0
@@ -3468,21 +2777,19 @@ class SessionStore:
or (max_age_seconds > 0 and now - started_at > max_age)
)
except TypeError:
- # Mixed aware/naive timestamps are invalid for this local
- # marker. Clear rather than risking an unsafe old resume.
+ # Mixed aware/naive timestamps: clear rather than risk an
+ # unsafe old resume.
marker_is_stale = True
if not marker_is_stale and not entry.suspended:
if entry.resume_pending:
- # A drain-timeout marker is more specific than the
- # generic crash reason; preserve it and its freshness.
+ # A drain-timeout marker is more specific; keep it.
if entry.last_resume_marked_at is None:
entry.last_resume_marked_at = now
else:
entry.resume_pending = True
entry.resume_reason = "restart_interrupted"
- # Freshness starts when recovery is discovered, not
- # when a potentially hours-long turn began.
+ # Freshness starts at discovery, not turn start.
entry.last_resume_marked_at = now
promoted += 1
@@ -3491,8 +2798,6 @@ class SessionStore:
changed = True
if changed:
- # Cold-start batch: one durable rewrite is clearer and cheaper
- # than an upsert per interrupted routing entry.
self._save()
return promoted
@@ -3517,21 +2822,12 @@ class SessionStore:
session_key: str,
reason: str = "restart_timeout",
) -> bool:
- """Mark a session as resumable after a restart interruption.
-
- Unlike ``suspend_session()``, this preserves the existing
- ``session_id`` and the transcript. The next call to
- ``get_or_create_session()`` for this key returns the same entry
- so the user auto-resumes on the same conversation lane.
-
- Returns True if the session existed and was marked.
- """
+ """Mark a session resumable after a restart interruption (keeps the
+ session_id/transcript, unlike ``suspend_session``). True if marked."""
with self._lock:
- self._ensure_loaded_locked()
- if session_key in self._entries:
- entry = self._entries[session_key]
- # Never override an explicit ``suspended`` — that is a hard
- # forced-wipe signal (from /stop or stuck-loop escalation).
+ entry = self._entry_locked(session_key)
+ if entry is not None:
+ # Never override an explicit ``suspended`` (hard forced-wipe).
if entry.suspended:
return False
entry.resume_pending = True
@@ -3543,16 +2839,9 @@ class SessionStore:
def clear_resume_pending(self, session_key: str) -> bool:
"""Clear the resume-pending flag after a successful resumed turn.
-
- Called from the gateway after ``run_conversation()`` returns a
- final response for a session that had ``resume_pending=True``,
- signalling that recovery succeeded.
-
- Returns True if a flag was cleared.
- """
+ Returns True if a flag was cleared."""
with self._lock:
- self._ensure_loaded_locked()
- entry = self._entries.get(session_key)
+ entry = self._entry_locked(session_key)
if entry is None or not entry.resume_pending:
return False
entry.resume_pending = False
@@ -3562,26 +2851,14 @@ class SessionStore:
return True
def prune_old_entries(self, max_age_days: int) -> int:
- """Drop SessionEntry records older than max_age_days.
-
- Pruning is based on ``updated_at`` (last activity), not ``created_at``.
- A session that's been active within the window is kept regardless of
- how old it is. Entries marked ``suspended`` are kept — the user
- explicitly paused them for later resume. Entries held by an active
- process (via has_active_processes_fn) are also kept so long-running
- background work isn't orphaned.
+ """Drop routing entries idle (by ``updated_at``) for more than max_age_days.
- Pruning is functionally identical to a natural reset-policy expiry:
- the transcript in SQLite stays, but the session_key → session_id
- mapping is dropped and the user starts a fresh session on return.
-
- ``max_age_days <= 0`` disables pruning; returns 0 immediately.
- Returns the number of entries removed.
+ Suspended entries and entries with active background processes are
+ kept. The SQLite transcript stays; only the key -> session_id mapping
+ is dropped. ``max_age_days <= 0`` disables. Returns the count removed.
"""
if max_age_days is None or max_age_days <= 0:
return 0
- from datetime import timedelta
-
cutoff = _now() - timedelta(days=max_age_days)
removed_keys: list[str] = []
@@ -3590,11 +2867,7 @@ class SessionStore:
for key, entry in list(self._entries.items()):
if entry.suspended:
continue
- # Never prune sessions with an active background process
- # attached — the user may still be waiting on output.
- # The callback is keyed by session_key (see process_registry.
- # has_active_for_session); passing session_id here used to
- # never match, so active sessions got pruned anyway.
+ # The callback is keyed by session_key, NOT session_id.
if self._has_active_processes_safe(entry.session_key, context="prune"):
continue
if entry.updated_at < cutoff:
@@ -3612,25 +2885,9 @@ class SessionStore:
return len(removed_keys)
def suspend_recently_active(self, max_age_seconds: int = 120) -> int:
- """Mark recently-active sessions as resumable after an unexpected exit.
-
- Called on gateway startup after a crash or fast restart to preserve
- in-flight sessions instead of destroying their conversation history
- (#7536). Only marks sessions updated within *max_age_seconds* to
- avoid touching long-idle sessions. Sets ``resume_pending=True`` so
- the next incoming message on the same session_key auto-resumes from
- the existing transcript.
-
- Entries already flagged ``resume_pending=True`` are skipped. Entries
- explicitly ``suspended=True`` (from /stop or stuck-loop escalation)
- are also skipped. Terminal escalation for genuinely stuck sessions
- is still handled by the existing ``.restart_failure_counts`` counter
- (threshold 3), which runs after this method and sets ``suspended=True``.
-
- Returns the number of sessions marked resumable.
- """
- from datetime import timedelta
-
+ """Mark sessions active within *max_age_seconds* as ``resume_pending``
+ after a crash/fast restart (already-pending and suspended entries are
+ skipped). Returns the number marked."""
cutoff = _now() - timedelta(seconds=max_age_seconds)
count = 0
with self._lock:
@@ -3654,91 +2911,66 @@ class SessionStore:
new_entry = None
with self._lock:
- self._ensure_loaded_locked()
-
- if session_key not in self._entries:
+ old_entry = self._entry_locked(session_key)
+ if old_entry is None:
return None
-
- old_entry = self._entries[session_key]
db_end_session_id = old_entry.session_id
-
now = _now()
- session_id = f"{now.strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}"
-
- new_entry = SessionEntry(
- session_key=session_key,
- session_id=session_id,
- created_at=now,
- updated_at=now,
- origin=old_entry.origin,
+ session_id = _new_session_id(now)
+ new_entry = self._replace_route_locked(
+ session_key, old_entry, session_id, now,
display_name=display_name if display_name is not None else old_entry.display_name,
- platform=old_entry.platform,
- chat_type=old_entry.chat_type,
is_fresh_reset=True,
)
-
- self._entries[session_key] = new_entry
- self._save()
- _reset_origin_json = None
- if old_entry.origin is not None:
- try:
- _reset_origin_json = json.dumps(old_entry.origin.to_dict())
- except Exception:
- _reset_origin_json = None
- db_create_kwargs = {
- "session_id": session_id,
- "source": old_entry.platform.value if old_entry.platform else "unknown",
- "user_id": old_entry.origin.user_id if old_entry.origin else None,
- "session_key": session_key,
- "chat_id": old_entry.origin.chat_id if old_entry.origin else None,
- "chat_type": old_entry.origin.chat_type if old_entry.origin else None,
- "thread_id": old_entry.origin.thread_id if old_entry.origin else None,
- "profile_name": old_entry.origin.profile if old_entry.origin else None,
- # Identity + lineage land atomically in the INSERT (#82616,
- # #12857) — see the get_or_create twin path.
- "origin_json": _reset_origin_json,
- "display_name": old_entry.display_name,
- "parent_session_id": db_end_session_id,
- "model_config": {"_reset_from": db_end_session_id},
- }
+ db_create_kwargs = self._session_create_kwargs(
+ session_id=session_id,
+ session_key=session_key,
+ origin=old_entry.origin,
+ source_value=old_entry.platform.value if old_entry.platform else "unknown",
+ display_name=old_entry.display_name,
+ parent_session_id=db_end_session_id,
+ )
+ db_create_kwargs["model_config"] = {"_reset_from": db_end_session_id}
if self._db_for_key(session_key) and db_end_session_id:
- try:
- # Promote (not plain end_session): an accidental
- # agent_close/ws_orphan_reap end must not survive an explicit
- # user reset, or recovery resurrects the reset session
- # (#61993 — the user's /new was silently undone).
- _promote = getattr(self._db_for_key(session_key), "promote_to_session_reset", None)
- if callable(_promote):
- _promote(db_end_session_id, "session_reset")
- else:
- self._db_for_key(session_key).end_session(db_end_session_id, "session_reset")
- except Exception as e:
- # Zombie hazard — see the get_or_create twin path (#82616).
- logger.warning(
+ self._promote_session_reset(
+ session_key, db_end_session_id, "session_reset",
+ log=lambda e: logger.warning(
"Failed to end predecessor session row %s for %s during "
"reset: %s — the old row remains open and may win restart "
"recovery until the next successful peer refresh",
db_end_session_id, session_key, e,
- )
+ ),
+ )
if self._db_for_key(session_key) and db_create_kwargs:
- try:
- self._db_for_key(session_key).create_session(**db_create_kwargs)
- self._record_gateway_session_peer(
- session_id,
- session_key,
- old_entry.origin,
- display_name=new_entry.display_name if new_entry else None,
- )
- except Exception as e:
- logger.warning(
+ self._create_session_row(
+ session_key, db_create_kwargs, old_entry.origin,
+ new_entry.display_name if new_entry else None,
+ log=lambda e: logger.warning(
"Failed to create session row %s for %s during reset: %s "
"— deferring to the self-healing peer refresh on the next "
"turn",
session_id, session_key, e,
- )
+ ),
+ )
+
+ return new_entry
+ def _replace_route_locked(self, session_key, old_entry, session_id, now, **fields) -> SessionEntry:
+ """Publish a fresh entry (inheriting origin/platform/chat_type) and save. Lock held."""
+ new_entry = SessionEntry(
+ session_key=session_key,
+ session_id=session_id,
+ created_at=now,
+ updated_at=now,
+ origin=old_entry.origin,
+ platform=old_entry.platform,
+ chat_type=old_entry.chat_type,
+ **fields,
+ )
+ self._entries[session_key] = new_entry
+ self._save()
return new_entry
def advance_compression_session(
@@ -3749,18 +2981,15 @@ class SessionStore:
) -> Optional[SessionEntry]:
"""CAS-advance one route along an already-verified compression lineage.
- Unlike ``switch_session``, this does not end or reopen SQLite rows. The
- compression transaction already owns that lifecycle; this method only
- repairs the persisted gateway key→session mapping. Returning ``None``
- means the route moved after the caller's snapshot (for example /new),
- so the caller must fail closed instead of overwriting the newer route.
+ Unlike ``switch_session`` this never ends/reopens SQLite rows (the
+ compression transaction owns that). ``None`` means the route moved
+ after the caller's snapshot (e.g. /new) — caller must fail closed.
"""
if not session_key or not expected_session_id or not target_session_id:
return None
with self._lock:
- self._ensure_loaded_locked()
- entry = self._entries.get(session_key)
+ entry = self._entry_locked(session_key)
if entry is None:
return None
if entry.session_id == target_session_id:
@@ -3773,67 +3002,33 @@ class SessionStore:
target_session_id,
):
return None
- # Compression repoint is store bookkeeping, not user activity —
- # leave ``updated_at`` alone so a background compression on an
- # idle session cannot make it look fresh to reset policy or the
- # restart-resume freshness gate (#85709).
+ # Bookkeeping, not user activity: leave ``updated_at`` alone.
self._save()
return entry
def switch_session(self, session_key: str, target_session_id: str) -> Optional[SessionEntry]:
- """Switch a session key to point at an existing session ID.
-
- Used by ``/resume`` to restore a previously-named session.
- Ends the current session in SQLite (like reset), but instead of
- generating a fresh session ID, re-uses ``target_session_id`` so the
- old transcript is loaded on the next message. If the target session was
- previously ended, re-open it so gateway resume semantics match the CLI.
- """
+ """Point a session key at an existing session ID (``/resume``): ends
+ the current row, reopens the target so resume matches the CLI."""
db_end_session_id = None
new_entry = None
with self._lock:
- self._ensure_loaded_locked()
-
- if session_key not in self._entries:
+ old_entry = self._entry_locked(session_key)
+ if old_entry is None:
return None
-
- old_entry = self._entries[session_key]
-
- # Don't switch if already on that session
if old_entry.session_id == target_session_id:
return old_entry
-
db_end_session_id = old_entry.session_id
-
- now = _now()
- new_entry = SessionEntry(
- session_key=session_key,
- session_id=target_session_id,
- created_at=now,
- updated_at=now,
- origin=old_entry.origin,
+ new_entry = self._replace_route_locked(
+ session_key, old_entry, target_session_id, _now(),
display_name=old_entry.display_name,
- platform=old_entry.platform,
- chat_type=old_entry.chat_type,
)
- self._entries[session_key] = new_entry
- self._save()
-
if self._db_for_key(session_key) and db_end_session_id:
- try:
- # Promote (not plain end_session): a stale agent_close /
- # ws_orphan_reap end on the outgoing session must be upgraded
- # to the explicit switch boundary, or recovery can resurrect
- # it over the user's /resume choice (#61220 bug class).
- _promote = getattr(self._db_for_key(session_key), "promote_to_session_reset", None)
- if callable(_promote):
- _promote(db_end_session_id, "session_switch")
- else:
- self._db_for_key(session_key).end_session(db_end_session_id, "session_switch")
- except Exception as e:
- logger.debug("Session DB end_session failed: %s", e)
+ self._promote_session_reset(
+ session_key, db_end_session_id, "session_switch",
+ log=lambda e: logger.debug("Session DB end_session failed: %s", e),
+ )
if self._db_for_key(session_key):
try:
@@ -3855,13 +3050,10 @@ class SessionStore:
with self._lock:
self._ensure_loaded_locked()
entries = list(self._entries.values())
-
if active_minutes is not None:
cutoff = _now() - timedelta(minutes=active_minutes)
entries = [e for e in entries if e.updated_at >= cutoff]
-
entries.sort(key=lambda e: e.updated_at, reverse=True)
-
return entries
def lookup_by_session_id(self, session_id: str) -> Optional[SessionEntry]:
@@ -3880,70 +3072,48 @@ class SessionStore:
if not session_key:
return None
with self._lock:
- self._ensure_loaded_locked()
- return self._entries.get(session_key)
+ return self._entry_locked(session_key)
def peek_session_id(self, session_key: str) -> Optional[str]:
- """Return the persisted session_id currently bound to a session key.
-
- Public, lock-held accessor for the key→session_id mapping. Callers that
- need to resolve the session row for a source (e.g. the webhook
- delivery-close path) should use this rather than reaching into the
- private ``_entries`` dict without holding ``self._lock``. Returns None
- when the key is unknown or has no session_id yet.
- """
+ """Lock-held accessor for the key -> session_id mapping (None if unknown)."""
if not session_key:
return None
with self._lock:
- self._ensure_loaded_locked()
- entry = self._entries.get(session_key)
+ entry = self._entry_locked(session_key)
return getattr(entry, "session_id", None) if entry else None
def _get_transcript_drain_lock(self):
"""Return the lock that serializes pending-queue drain boundaries."""
- drain_lock = getattr(self, "_transcript_drain_lock", None)
- if drain_lock is None:
- # Compatibility for old in-memory/test instances created via
- # object.__new__ before this field existed.
- drain_lock = threading.RLock()
- self._transcript_drain_lock = drain_lock
- return drain_lock
+ return self._lazy("_transcript_drain_lock", threading.RLock)
def append_to_transcript(self, session_id: str, message: Dict[str, Any], skip_db: bool = False) -> None:
"""Serialize transcript draining across queue migration boundaries."""
if not self._db_for_session_id(session_id) or skip_db:
return
with self._get_transcript_drain_lock():
- reroutes = getattr(self, "_transcript_reroutes", None)
- if reroutes is None:
- reroutes = {}
- self._transcript_reroutes = reroutes
- seen = set()
- while session_id in reroutes and session_id not in seen:
- seen.add(session_id)
- session_id = reroutes[session_id]
- self._append_to_transcript_serialized(session_id, message)
+ self._append_to_transcript_serialized(
+ self._follow_reroutes(session_id), message
+ )
+
+ def _follow_reroutes(self, session_id: str) -> str:
+ """Follow the compression reroute chain (cycle-guarded)."""
+ reroutes = self._lazy("_transcript_reroutes", dict)
+ seen = set()
+ while session_id in reroutes and session_id not in seen:
+ seen.add(session_id)
+ session_id = reroutes[session_id]
+ return session_id
def _append_to_transcript_serialized(
self, session_id: str, message: Dict[str, Any]
) -> None:
- """Append a message to a session's transcript (SQLite).
-
- Args:
- skip_db: When True, skip the SQLite write. Used when the agent
- already persisted messages to SQLite via its own
- _flush_messages_to_session_db(), preventing the
- duplicate-write bug (#860).
- """
+ """Append a message to a session's transcript (SQLite), draining the
+ per-session retry queue."""
with self._transcript_retry_lock:
pending = self._dirty_transcripts.setdefault(session_id, [])
pending.append(dict(message))
- # Cap pending messages per session to avoid unbounded memory
- # growth when the DB is persistently broken. Spool the evicted
- # oldest message to the on-disk pending spool (same machinery
- # flush_pending_to_file uses at shutdown) so a runtime cap
- # rotation does not silently discard it (#78182); it is
- # replayed on the next successful transcript flush.
+ # Cap the queue; spool the evicted oldest message to disk (same
+ # machinery as shutdown flush) for replay after DB recovery.
if len(pending) > self._MAX_PENDING_PER_SESSION:
dropped = pending.pop(0)
spool_path = None
@@ -3957,13 +3127,7 @@ class SessionStore:
except Exception:
spool_path = None
if spool_path is not None:
- spooled_sessions = getattr(
- self, "_spooled_drop_sessions", None
- )
- if spooled_sessions is None:
- spooled_sessions = set()
- self._spooled_drop_sessions = spooled_sessions
- spooled_sessions.add(session_id)
+ self._lazy("_spooled_drop_sessions", set).add(session_id)
logger.warning(
"Session DB transcript pending queue full for %s "
"(cap=%d); spooled oldest message to %s for replay "
@@ -3977,12 +3141,20 @@ class SessionStore:
"(on-disk spool unavailable)",
session_id, self._MAX_PENDING_PER_SESSION,
)
- # Snapshot the first pending message, then release the lock
- # before the DB write so other sessions are not blocked.
msg = pending[0]
queue_session_id = session_id
- # DB write outside the retry lock — other sessions can append
- # concurrently. We re-acquire the lock only to update the queue.
+
+ def _ack_head() -> bool:
+ """Pop the acknowledged head (retry lock held). True if queue drained."""
+ if pending and pending[0] is msg:
+ pending.pop(0)
+ if not pending:
+ self._dirty_transcripts.pop(queue_session_id, None)
+ self._transcript_append_failures.pop(session_id, None)
+ return True
+ return False
+
+ # DB write outside the retry lock so other sessions can append.
while True:
try:
self._append_transcript_message(session_id, msg)
@@ -3994,11 +3166,9 @@ class SessionStore:
)
if isinstance(exc, (StateDbReplacedError, StateDbCorruptError)):
- # Both classes mean "this handle must not touch the file
- # again": replaced generation (#89332) or structural
- # corruption (quarantine). Retrying cannot succeed, and
- # the FTS one-shot rebuild below must never run on a
- # damaged file. Divert instead.
+ # This handle must not touch the file again (replaced
+ # generation / quarantined corruption): retrying cannot
+ # succeed and the FTS rebuild must never run on it. Divert.
logger.error(
"Session DB refused further writes on this handle for "
"%s (%s); stopping SQLite writes and diverting pending "
@@ -4035,21 +3205,12 @@ class SessionStore:
return
if isinstance(exc, CompressionSessionClosedError):
- # Resolve the full continuation chain via the canonical
- # transitive API — a depth-1 live-child lookup misses
- # lineages with >=2 compression hops (root -> mid -> tip).
- # ``get_compression_tip`` returns the input id when no
- # continuation exists; adopt only a different, still-live
- # tip, otherwise fail closed as before.
- #
- # The parent's id IS published in the routing index, so
- # its owner is already proven; the continuation's id is
- # not published until after the child write succeeds
- # (below), so resolving the child by id would miss and
- # fall back to the ambient store. Carry the proven handle
- # instead of re-deriving it from an id nothing points at
- # yet. ``_owner_db`` cannot be None here — the parent
- # append above just reached a real DB to raise this.
+ # Resolve the transitive compression tip (a depth-1 lookup
+ # misses multi-hop lineages); adopt only a different,
+ # still-live tip, else fail closed. Use the PARENT's proven
+ # owner handle: the child's id is not published until
+ # after its write succeeds, so a by-id lookup would fall
+ # back to the ambient store.
_owner_key = self._owner_key_for_session_id(session_id)
_owner_db = self._db_for_session_id(session_id)
child_id = ""
@@ -4060,19 +3221,11 @@ class SessionStore:
if tip_row is not None and tip_row.get("ended_at") is None:
child_id = str(tip)
if child_id:
- # Record the child's owner BEFORE writing to it. The
- # reroute and the _entries update are published only
- # after this write succeeds — that ordering is
- # load-bearing for backlog order — so an index lookup
- # here would miss and fall back to the ambient store,
- # which is a live handle and would slip past the
- # fail-closed guard.
+ # Record the child's owner BEFORE writing to it (the
+ # reroute is published only after the write succeeds
+ # — load-bearing for backlog order).
if _owner_key:
- _hints = getattr(self, "_session_owner_hints", None)
- if _hints is None:
- _hints = {}
- self._session_owner_hints = _hints
- _hints[child_id] = _owner_key
+ self._lazy("_session_owner_hints", dict)[child_id] = _owner_key
try:
self._append_transcript_message(child_id, msg)
except Exception as reroute_exc:
@@ -4109,8 +3262,7 @@ class SessionStore:
if entry.session_id == session_id:
entry.session_id = child_id
self._save()
- # Routing now points at the child, so the index is
- # authoritative again and the hint has no more work.
+ # The index is authoritative again; drop the hint.
_hints = getattr(self, "_session_owner_hints", None)
if _hints:
_hints.pop(child_id, None)
@@ -4120,15 +3272,10 @@ class SessionStore:
session_id = child_id
continue
else:
- # This is a permanent routing invariant failure, not a
- # transient DB outage. Drop it from the retry queue so it
- # cannot poison later transcript writes indefinitely.
+ # Permanent routing invariant failure, not a transient
+ # outage: drop it so it cannot poison later writes.
with self._transcript_retry_lock:
- if pending and pending[0] is msg:
- pending.pop(0)
- if not pending:
- self._dirty_transcripts.pop(queue_session_id, None)
- self._transcript_append_failures.pop(session_id, None)
+ _ack_head()
logger.error(
"Session DB transcript append rejected for compression-ended "
"%s with no unique live child; not retrying",
@@ -4142,11 +3289,7 @@ class SessionStore:
exc = retry_exc
else:
with self._transcript_retry_lock:
- if pending and pending[0] is msg:
- pending.pop(0)
- if not pending:
- self._dirty_transcripts.pop(queue_session_id, None)
- self._transcript_append_failures.pop(session_id, None)
+ _ack_head()
continue
with self._transcript_retry_lock:
failures = self._transcript_append_failures.get(session_id, 0) + 1
@@ -4159,19 +3302,11 @@ class SessionStore:
return
else:
with self._transcript_retry_lock:
- if pending and pending[0] is msg:
- pending.pop(0)
- if not pending:
- self._dirty_transcripts.pop(queue_session_id, None)
- self._transcript_append_failures.pop(session_id, None)
- queue_empty = True
- else:
- queue_empty = False
+ queue_empty = _ack_head()
+ if not queue_empty:
msg = pending[0]
if queue_empty:
- # DB write just succeeded and the in-memory backlog is
- # clear: replay any cap-dropped messages spooled to disk
- # for this session (#78182).
+ # Backlog clear: replay cap-dropped messages spooled to disk.
self._drain_spooled_drops(session_id)
return
continue
@@ -4197,20 +3332,18 @@ class SessionStore:
if not remaining:
spooled_sessions.discard(session_id)
except Exception as exc:
- logger.warning(
- "Failed to drain transcript spool for %s: %s", session_id, exc
- )
+ logger.warning("Failed to drain transcript spool for %s: %s", session_id, exc)
def _append_transcript_message(self, session_id: str, message: Dict[str, Any]) -> None:
"""Write one transcript row. Caller handles retry queuing."""
_db = self._db_for_session_id(session_id)
if _db is None:
- # A named profile with no resolvable home yet. Defer instead of
- # writing the row into the ambient store — the caller queues the
- # message and a later attempt lands it once the profile exists.
+ # Named profile with no resolvable home yet: defer (caller queues)
+ # instead of writing into the ambient store.
raise RuntimeError(
f"no owning session store for {session_id}; deferring transcript write"
)
+ is_assistant = message.get("role") == "assistant"
_db.append_message(
session_id=session_id,
role=message.get("role", "unknown"),
@@ -4218,43 +3351,33 @@ class SessionStore:
tool_name=message.get("tool_name"),
tool_calls=message.get("tool_calls"),
tool_call_id=message.get("tool_call_id"),
- reasoning=message.get("reasoning") if message.get("role") == "assistant" else None,
- reasoning_content=message.get("reasoning_content") if message.get("role") == "assistant" else None,
- reasoning_details=message.get("reasoning_details") if message.get("role") == "assistant" else None,
- codex_reasoning_items=message.get("codex_reasoning_items") if message.get("role") == "assistant" else None,
- codex_message_items=message.get("codex_message_items") if message.get("role") == "assistant" else None,
+ reasoning=message.get("reasoning") if is_assistant else None,
+ reasoning_content=message.get("reasoning_content") if is_assistant else None,
+ reasoning_details=message.get("reasoning_details") if is_assistant else None,
+ codex_reasoning_items=message.get("codex_reasoning_items") if is_assistant else None,
+ codex_message_items=message.get("codex_message_items") if is_assistant else None,
platform_message_id=(message.get("platform_message_id") or message.get("message_id")),
observed=bool(message.get("observed")),
timestamp=message.get("timestamp"),
- # api_content sidecar: the exact bytes sent to the API for
- # this message (prompt-cache-stable replay). Must survive
- # any gateway-side persistence path or the next turn's
- # replay diverges at this row.
+ # Exact bytes sent to the API (prompt-cache-stable replay); must
+ # survive every persistence path or the next replay diverges.
api_content=extract_api_content_sidecar(message),
- # Presentation typing (e.g. "internal_notification" for
- # self-injected async-delegation/background notification turns,
- # #82888). DB-only; stripped from provider-bound payloads.
+ # Presentation typing (e.g. "internal_notification"); DB-only.
display_kind=message.get("display_kind"),
display_metadata=message.get("display_metadata"),
)
- # Maximum in-memory pending messages per session before dropping the
- # oldest. Prevents unbounded growth when the DB is persistently broken.
+ # Max in-memory pending messages per session (DB persistently broken).
_MAX_PENDING_PER_SESSION = 200
@staticmethod
def _is_fts_corruption_error(exc: Exception) -> bool:
"""True only when the failure is provably scoped to the FTS index.
- A generic ``database disk image is malformed`` (bare SQLITE_CORRUPT)
- can mean structural damage to canonical B-trees, not just the FTS
- shadow tables — treating it as FTS-only here made the store rebuild
- the index and retry transcript writes against a structurally corrupt
- database (#97940). Only errors that name ``messages_fts`` or carry
- FTS provenance per ``SessionDB._is_fts_write_corruption_error``
- (``SQLITE_CORRUPT_VTAB`` result code, or explicit ``fts5:`` corrupt
- structure text) may authorize the one-shot rebuild-and-retry.
- Everything else falls through to the bounded retry/backoff path.
+ A bare SQLITE_CORRUPT can mean structural B-tree damage; only errors
+ naming ``messages_fts`` or carrying FTS provenance (per
+ ``SessionDB._is_fts_write_corruption_error``) may authorize the
+ one-shot rebuild-and-retry. Everything else takes the retry path.
"""
text = str(exc).lower()
if "messages_fts" in text:
@@ -4268,21 +3391,14 @@ class SessionStore:
return False
def _rebuild_fts_once(self) -> bool:
- """Attempt FTS5 ``rebuild`` command once per store lifetime.
-
- Delegates to ``SessionDB.rebuild_fts()`` which handles locking and
- table-existence checks internally. Returns ``True`` when at least
- one index was rebuilt.
- """
+ """Attempt FTS5 ``rebuild`` once per store lifetime; True if any index was rebuilt."""
if self._fts_rebuild_attempted:
return False
self._fts_rebuild_attempted = True
db = self._db
if db is None or not hasattr(db, "rebuild_fts"):
return False
- # Guard against the same WAL split-brain risk as the automatic
- # rebuild paths: skip when a foreign process holds state.db or
- # its WAL sidecars open.
+ # WAL split-brain guard: skip when a foreign process holds state.db.
if hasattr(db, "_foreign_state_db_holders"):
foreign_holders = db._foreign_state_db_holders()
if foreign_holders:
@@ -4306,13 +3422,7 @@ class SessionStore:
return rebuilt > 0
def _clear_dirty_transcript(self, session_id: str) -> None:
- """Drop queued pending messages for a session.
-
- Called by ``rewrite_transcript`` and ``rewind_session`` so that
- /retry, /undo, /compress — which replace or truncate the transcript —
- don't leave stale messages that would be re-inserted on the next
- append.
- """
+ """Drop queued pending messages so a rewrite/rewind doesn't re-insert them."""
with self._transcript_retry_lock:
self._dirty_transcripts.pop(session_id, None)
self._transcript_append_failures.pop(session_id, None)
@@ -4320,16 +3430,12 @@ class SessionStore:
def has_platform_message_id(
self, session_id: str, platform_message_id: str
) -> bool:
- """Check if a message with the given platform_message_id is persisted.
-
- Thin wrapper over SessionDB.has_platform_message_id(). Returns False
- when no DB is available (in-memory sessions). Used by the gateway's
- transient-failure dedupe guard (#47237).
- """
- if not self._db_for_session_id(session_id):
+ """Whether a message with this platform_message_id is persisted (False without a DB)."""
+ db = self._db_for_session_id(session_id)
+ if not db:
return False
try:
- return self._db_for_session_id(session_id).has_platform_message_id(
+ return db.has_platform_message_id(
session_id, platform_message_id
)
except Exception:
@@ -4343,35 +3449,22 @@ class SessionStore:
active_only: bool = False,
reject_active_turn_lease: bool = False,
) -> bool:
- """Replace the entire transcript for a session with new messages.
-
- Used by /retry and /compress to persist modified conversation
- history. state.db is the canonical store. (/undo is not a caller:
- it soft-archives rows via rewind_session / rewind_to_message.)
-
- DESTRUCTIVE by default: ``replace_messages(active_only=False)``
- DELETEs every row for the session, including the soft-archived
- compaction history that archive_and_compact() keeps on disk
- (#38763). Callers rewriting the live transcript of a session that
- may carry archived rows must pass ``active_only=True`` so only the
- live rows are replaced.
-
- Returns ``True`` when the write lands (or there is no DB to write to)
- and ``False`` when the canonical write fails. Most callers can ignore
- the result, but callers that would otherwise commit a destructive state
- change on top of a failed write — e.g. /compress repointing the live
- session onto a fresh session_id — must check it so they can surface an
- error instead of silently dropping the conversation.
-
- ``reject_active_turn_lease`` is for user-initiated rewrites that do not
- own the cross-process turn lease. It leaves internal rewrite policy
- unchanged for existing callers unless they opt in explicitly.
+ """Replace a session's transcript (/retry, /compress).
+
+ DESTRUCTIVE by default: ``active_only=False`` DELETEs every row
+ including soft-archived compaction history; pass ``active_only=True``
+ for sessions that may carry archived rows. Returns ``True`` when the
+ write lands (or there is no DB), ``False`` on failure — callers about
+ to commit a destructive change on top (e.g. /compress repointing)
+ must check it. ``reject_active_turn_lease`` is for user-initiated
+ rewrites that do not own the cross-process turn lease.
"""
- if not self._db_for_session_id(session_id):
+ db = self._db_for_session_id(session_id)
+ if not db:
return True
with self._get_transcript_drain_lock():
try:
- self._db_for_session_id(session_id).replace_messages(
+ db.replace_messages(
session_id,
messages,
active_only=active_only,
@@ -4384,48 +3477,31 @@ class SessionStore:
return True
def load_transcript(self, session_id: str) -> List[Dict[str, Any]]:
- """Load all messages from a session's transcript.
-
- state.db is the canonical store. The legacy JSONL fallback was removed
- in spec 002 — pre-DB sessions on existing disks have already been
- migrated (their DB row holds the full message history).
-
- Reads follow the same routing writes use (#82616): the in-memory
- reroute map installed after a compression rotation, then the durable
- compression tip in state.db. Before this, writes followed the reroute
- chain while reads queried the stale id directly — the transcript
- "vanished" (disk=0) even though every message sat healthy under the
- child session.
+ """Load all messages from a session's transcript (state.db is canonical).
+
+ Reads follow the same routing writes use: the in-memory reroute map
+ (compression rotation), then the durable compression tip — otherwise
+ the transcript "vanishes" while every message sits under the child.
"""
if not self._db_for_session_id(session_id):
return []
- # Follow the write-side reroute chain (cycle-guarded, same shape as
- # append_to_transcript).
- reroutes = getattr(self, "_transcript_reroutes", None) or {}
- seen = set()
- while session_id in reroutes and session_id not in seen:
- seen.add(session_id)
- session_id = reroutes[session_id]
+ session_id = self._follow_reroutes(session_id)
try:
- # Durable successor: a compression child published to state.db
- # survives restart even though the in-memory reroute map doesn't.
+ # Durable successor survives restart; the reroute map doesn't.
tip = self._db_for_session_id(session_id).get_compression_tip(session_id)
if tip:
session_id = tip
except Exception:
pass
try:
- # repair_alternation: this load feeds LIVE REPLAY. A durable
- # user;user wedge (e.g. a turn that persisted no assistant row)
- # would otherwise re-trigger the pre-request repair on every
- # request forever — heal it once at the restore boundary.
+ # repair_alternation: this feeds LIVE REPLAY; heal a durable
+ # user;user wedge once here instead of on every request.
return self._db_for_session_id(session_id).get_messages_as_conversation(
session_id, repair_alternation=True
)
except Exception as e:
- # Empty history is valid data; a failed canonical read is not.
- # Preserve that distinction so live-replay callers can fail closed
- # instead of starting the model with a plausible-looking [].
+ # Empty history is valid data; a failed canonical read is not —
+ # live-replay callers must fail closed, not start from [].
logger.error(
"Transcript read failed for session %s; refusing to treat the "
"conversation as empty: %s",
@@ -4442,21 +3518,16 @@ class SessionStore:
*,
require_retryable_composite: bool = False,
) -> Optional[Dict[str, Any]]:
- """Back up ``n`` user turns via soft-delete, keeping rows for audit.
-
- Unlike :meth:`rewrite_transcript` (a hard replace used by /retry),
- this flips the truncated rows to ``active=0`` in state.db so they
- survive for audit and stay hidden from re-prompts and search. Mirrors
- the CLI/TUI ``/undo [N]`` behavior via ``SessionDB.rewind_to_message``.
+ """Back up ``n`` user turns via soft-delete (``active=0``), mirroring CLI ``/undo [N]``.
- Returns a dict ``{"rewound_count", "turns_undone", "target_text"}`` on
- success, or ``None`` if there's no DB or no user message to back up to.
- ``n`` clamps to the oldest user turn when it exceeds the turn count.
+ Returns ``{"rewound_count", "turns_undone", "target_text"}`` or ``None``
+ (no DB / no user turn). ``n`` clamps to the oldest user turn.
``require_retryable_composite`` is the gateway ``/retry`` guard: the
- selected current turn must still be a composite carrier, and its live
- payload must be losslessly replayable as text before anything changes.
+ selected turn must be a composite carrier whose live payload is
+ losslessly replayable as text before anything changes.
"""
- if not self._db_for_session_id(session_id):
+ db = self._db_for_session_id(session_id)
+ if not db:
return None
with self._get_transcript_drain_lock():
if n < 1:
@@ -4468,8 +3539,8 @@ class SessionStore:
)
try:
- expected_active_ids = self._db_for_session_id(session_id).get_active_message_ids(session_id)
- durable = self._db_for_session_id(session_id).get_messages_as_conversation(
+ expected_active_ids = db.get_active_message_ids(session_id)
+ durable = db.get_messages_as_conversation(
session_id,
include_row_ids=True,
)
@@ -4498,7 +3569,7 @@ class SessionStore:
# so /retry can explain why the selected carrier is unsafe.
target_text = retryable_user_text(target_view.get("content"))
try:
- result = self._db_for_session_id(session_id).rewind_to_message(
+ result = db.rewind_to_message(
session_id,
target_id,
preserve_compaction_handoff=handoff is not None,
@@ -4512,9 +3583,8 @@ class SessionStore:
logger.debug("rewind_session: rewind_to_message failed: %s", e)
return None
self._clear_dirty_transcript(session_id)
- # ``target_view`` is the canonical live projection of the physical DB
- # row. For a composite carrier, the raw target contains the historical
- # summary wrapper and must never be echoed back as the editable prompt.
+ # ``target_view`` is the live projection; a composite carrier's raw
+ # row holds the summary wrapper and must not be echoed as prompt.
if not require_retryable_composite:
content = target_view.get("content") or ""
if isinstance(content, list):
@@ -4540,13 +3610,9 @@ def build_session_context(
config: GatewayConfig,
session_entry: Optional[SessionEntry] = None
) -> SessionContext:
- """
- Build a full session context from a source and config.
-
- This is used to inject context into the agent's system prompt.
- """
+ """Build a full session context (for system prompt injection)."""
connected = config.get_connected_platforms()
-
+
home_channels = {}
for platform in connected:
home = config.get_home_channel(platform)
diff --git a/gateway/shutdown_flush.py b/gateway/shutdown_flush.py
index 07bcf7e86fc..afe1d812767 100644
--- a/gateway/shutdown_flush.py
+++ b/gateway/shutdown_flush.py
@@ -3,24 +3,19 @@
When FTS5 index corruption prevents ``INSERT INTO messages``, the gateway
accumulates messages in ``_pending_messages`` (memory-only) and the live
``agent._session_messages`` cannot be flushed via ``_flush_messages_to_session_db``.
-On shutdown, ``.clear()`` discards the only surviving copy — permanent user data loss.
-
-This module provides three hooks:
-
-1. ``flush_pending_to_file()`` — called BEFORE ``_pending_messages.clear()``
- during shutdown. Serialises any non-empty pending slots to a JSON file
- under ``<hermes_home>/pending_messages/``.
-
-2. ``recover_pending_to_db()`` — called AFTER ``runner.start()`` on startup.
- Reads flush files, inserts messages into state.db via ``SessionDB.append_message``
- (so FTS indexing, session metadata, and display_kind are handled correctly),
- then deletes the flush file on success.
-
-3. ``flush_agent_history_to_file()`` — called from ``_finalize_shutdown_agents``
- when ``_flush_messages_to_session_db`` raises. Dumps the live
- ``agent._session_messages`` to the same atomic JSON recovery directory.
-
-See issue #72680 for the full incident report.
+On shutdown, ``.clear()`` would discard the only surviving copy.
+
+Hooks (all write atomic JSON payloads under ``<hermes_home>/pending_messages/``):
+
+* ``flush_pending_to_file()`` / ``flush_overflow_to_file()`` — called BEFORE
+ ``_pending_messages.clear()`` during shutdown (queue head / FIFO tail).
+* ``recover_pending_to_db()`` — called AFTER ``runner.start()`` on startup;
+ replays payloads via ``SessionDB.append_message`` (so FTS indexing, session
+ metadata and display_kind are handled), deleting each file on success.
+* ``flush_agent_history_to_file()`` — called from ``_finalize_shutdown_agents``
+ when ``_flush_messages_to_session_db`` raises; dumps ``agent._session_messages``.
+* ``spool_dropped_transcript_message()`` / ``drain_transcript_spool()`` — live
+ spool for transcript messages evicted by the in-memory pending cap.
"""
from __future__ import annotations
@@ -36,6 +31,13 @@ from typing import Any, Dict, Optional
logger = logging.getLogger(__name__)
+# Reason tag for transcript messages dropped by the in-memory pending cap during
+# live operation. Payloads carry the full transcript message dict for verbatim replay.
+TRANSCRIPT_CAP_DROP_REASON = "transcript_cap_drop"
+
+# Monotonic tiebreaker so same-second spool files replay in drop order.
+_TRANSCRIPT_SPOOL_SEQ = itertools.count()
+
def _get_flush_dir():
"""Return the pending-messages flush directory under the active HERMES_HOME."""
@@ -60,30 +62,33 @@ def _fsync_directory(path: Path) -> None:
def _write_payload(flush_dir: Path, payload: Dict[str, Any]) -> Path:
- """Atomically write one private, uniquely named recovery payload.
-
- Returns the path of the published payload file.
- """
+ """Atomically write one private, uniquely named recovery payload; return its path."""
from utils import atomic_json_write
- file_id = uuid.uuid4().hex
- final_path = flush_dir / f"pending-{file_id}.json"
- atomic_json_write(
- final_path,
- payload,
- mode=0o600,
- default=str,
- )
-
+ final_path = flush_dir / f"pending-{uuid.uuid4().hex}.json"
+ atomic_json_write(final_path, payload, mode=0o600, default=str)
try:
_fsync_directory(flush_dir)
except OSError as exc:
- # The atomically published file is still the only recovery copy.
- # Keep it even if this filesystem cannot persist directory entries.
+ # The published file is still the only recovery copy; keep it even if
+ # this filesystem cannot persist directory entries.
logger.debug("Failed to fsync pending-message directory: %s", exc)
return final_path
+def _flush_value(flush_dir: Path, kind: str, session_key: str, value: Any, **extra: Any) -> bool:
+ """Serialise and write one pending value; return True when a payload was written."""
+ try:
+ serialised = _serialise_value(value)
+ if serialised is None:
+ return False
+ _write_payload(flush_dir, {"session_key": session_key, **extra, "data": serialised})
+ return True
+ except Exception as exc:
+ logger.debug("Failed to flush %s message for %s: %s", kind, session_key, exc)
+ return False
+
+
def flush_pending_to_file(
pending: Dict[str, Any],
*,
@@ -91,18 +96,8 @@ def flush_pending_to_file(
) -> int:
"""Serialise non-empty ``_pending_messages`` slots to disk.
- Parameters
- ----------
- pending:
- The adapter or runner ``_pending_messages`` dict. Values may be
- ``MessageEvent`` objects (adapter) or plain strings (runner).
- reason:
- Logged context (``shutdown``, ``restart``, etc.).
-
- Returns
- -------
- int
- Number of sessions flushed.
+ ``pending`` values may be ``MessageEvent`` objects (adapter) or plain
+ strings (runner). Returns the number of sessions flushed.
"""
if not pending:
return 0
@@ -110,35 +105,13 @@ def flush_pending_to_file(
flush_dir = _get_flush_dir()
ts = int(time.time())
flushed = 0
-
for session_key, value in list(pending.items()):
if value is None:
continue
- try:
- serialised = _serialise_value(value)
- if serialised is None:
- continue
- _write_payload(
- flush_dir,
- {
- "session_key": session_key,
- "reason": reason,
- "ts": ts,
- "data": serialised,
- },
- )
- flushed += 1
- except Exception as exc:
- logger.debug(
- "Failed to flush pending message for %s: %s",
- session_key, exc,
- )
+ flushed += _flush_value(flush_dir, "pending", session_key, value, reason=reason, ts=ts)
if flushed:
- logger.info(
- "Flushed %d pending message(s) to %s (reason=%s)",
- flushed, flush_dir, reason,
- )
+ logger.info("Flushed %d pending message(s) to %s (reason=%s)", flushed, flush_dir, reason)
return flushed
@@ -149,15 +122,10 @@ def flush_overflow_to_file(
) -> int:
"""Serialise the FIFO overflow tails (``queued_events``) to disk.
- Sibling of :func:`flush_pending_to_file` for the second half of the
- gateway FIFO (#99882): the adapter slot holds the queue head, and the
- per-session ``SessionState.conversation.queued_events`` list holds the
- tail. Shutdown flushed only the slot, so every follow-up parked in
- overflow at restart time vanished with the process. Each overflow
- event is written as its own payload in the same shape as a slot flush
- so ``recover_pending_to_db`` replays them unchanged; a ``seq`` field
- preserves arrival order within a session.
-
+ The adapter slot holds the queue head and ``SessionState.conversation
+ .queued_events`` holds the tail; both must survive restart. Each event
+ is its own payload in the slot-flush shape so ``recover_pending_to_db``
+ replays them unchanged; ``seq`` preserves arrival order within a session.
Returns the number of events flushed.
"""
if not overflow_by_session:
@@ -166,104 +134,51 @@ def flush_overflow_to_file(
flush_dir = _get_flush_dir()
ts = int(time.time())
flushed = 0
-
for session_key, events in list(overflow_by_session.items()):
if not session_key or not events:
continue
for seq, value in enumerate(list(events)):
if value is None:
continue
- try:
- serialised = _serialise_value(value)
- if serialised is None:
- continue
- _write_payload(
- flush_dir,
- {
- "session_key": session_key,
- "reason": reason,
- "ts": ts,
- "seq": seq,
- "data": serialised,
- },
- )
- flushed += 1
- except Exception as exc:
- logger.debug(
- "Failed to flush overflow message for %s: %s",
- session_key, exc,
- )
+ flushed += _flush_value(flush_dir, "overflow", session_key, value, reason=reason, ts=ts, seq=seq)
if flushed:
- logger.info(
- "Flushed %d queued overflow message(s) to %s (reason=%s)",
- flushed, flush_dir, reason,
- )
+ logger.info("Flushed %d queued overflow message(s) to %s (reason=%s)", flushed, flush_dir, reason)
return flushed
-# Reason tag for transcript messages dropped by the in-memory pending cap
-# during live operation (#78182). These payloads carry the full transcript
-# message dict so they can be replayed verbatim once the DB recovers.
-TRANSCRIPT_CAP_DROP_REASON = "transcript_cap_drop"
-
-
-def spool_dropped_transcript_message(
- session_id: str,
- message: Dict[str, Any],
-) -> Optional[Path]:
+def spool_dropped_transcript_message(session_id: str, message: Dict[str, Any]) -> Optional[Path]:
"""Spool a transcript message evicted by the runtime pending cap.
- Uses the same on-disk pending spool as :func:`flush_pending_to_file`
- (one atomic JSON payload per message under
- ``<hermes_home>/pending_messages/``), so a runtime cap rotation no
- longer silently discards user data while the process stays up
- (#78182).
-
Returns the written spool path, or ``None`` when spooling failed —
- callers must degrade to the previous drop-and-log behaviour.
+ callers must degrade to drop-and-log.
"""
try:
- flush_dir = _get_flush_dir()
return _write_payload(
- flush_dir,
+ _get_flush_dir(),
{
"session_key": session_id,
"reason": TRANSCRIPT_CAP_DROP_REASON,
"ts": int(time.time()),
"seq": next(_TRANSCRIPT_SPOOL_SEQ),
- "data": {
- "session_id": session_id,
- "message": message,
- },
+ "data": {"session_id": session_id, "message": message},
},
)
except Exception as exc:
- logger.debug(
- "Failed to spool cap-dropped transcript message for %s: %s",
- session_id, exc,
- )
+ logger.debug("Failed to spool cap-dropped transcript message for %s: %s", session_id, exc)
return None
-# Monotonic tiebreaker so same-second spool files replay in drop order.
-_TRANSCRIPT_SPOOL_SEQ = itertools.count()
-
-
def drain_transcript_spool(session_id: str, replay) -> tuple[int, int]:
"""Replay cap-dropped transcript messages spooled for *session_id*.
- ``replay(message_dict)`` is invoked for each spooled message in drop
- order; the spool file is deleted only after a successful replay. On
- the first replay failure the drain stops and remaining files are kept
- for the next attempt (the DB is likely still unhealthy).
-
- Returns ``(replayed, remaining)`` — messages replayed and spool files
- left behind for a later retry.
+ ``replay(message_dict)`` runs per message in drop order; a spool file is
+ deleted only after its replay succeeds. The first failure stops the
+ drain (the DB is likely still unhealthy) and keeps the rest for retry.
+ Returns ``(replayed, remaining)``.
"""
try:
- flush_dir = _get_flush_dir()
- candidates = list(flush_dir.glob("pending-*.json"))
+ candidates = list(_get_flush_dir().glob("pending-*.json"))
except Exception as exc:
logger.debug("Cannot scan transcript spool: %s", exc)
return 0, 0
@@ -274,24 +189,20 @@ def drain_transcript_spool(session_id: str, replay) -> tuple[int, int]:
payload = json.loads(path.read_text(encoding="utf-8"))
except Exception:
continue
- if payload.get("reason") != TRANSCRIPT_CAP_DROP_REASON:
- continue
- if payload.get("session_key") != session_id:
+ if (
+ payload.get("reason") != TRANSCRIPT_CAP_DROP_REASON
+ or payload.get("session_key") != session_id
+ ):
continue
message = (payload.get("data") or {}).get("message")
if not isinstance(message, dict):
- logger.warning(
- "Removing structurally invalid transcript spool file %s", path,
- )
+ logger.warning("Removing structurally invalid transcript spool file %s", path)
path.unlink(missing_ok=True)
continue
- entries.append(
- (payload.get("ts", 0), payload.get("seq", 0), path.name, path, message)
- )
+ entries.append((payload.get("ts", 0), payload.get("seq", 0), path.name, path, message))
- replayed = 0
ordered = sorted(entries, key=lambda e: e[:3])
- remaining = 0
+ replayed = remaining = 0
for idx, (_ts, _seq, _name, path, message) in enumerate(ordered):
try:
replay(message)
@@ -307,19 +218,14 @@ def drain_transcript_spool(session_id: str, replay) -> tuple[int, int]:
replayed += 1
if replayed:
- logger.info(
- "Replayed %d spooled transcript message(s) for %s after DB recovery",
- replayed, session_id,
- )
+ logger.info("Replayed %d spooled transcript message(s) for %s after DB recovery", replayed, session_id)
return replayed, remaining
def _serialise_value(value: Any) -> Optional[dict]:
"""Convert a pending message value to a JSON-serialisable dict."""
- # MessageEvent objects have a .text attribute and other fields
- if hasattr(value, "text"):
+ if hasattr(value, "text"): # MessageEvent-like object
result: Dict[str, Any] = {"text": getattr(value, "text", "")}
- # Preserve additional fields if present
for attr in ("session_id", "platform", "sender_id", "sender_name",
"reply_to", "media", "raw_event"):
val = getattr(value, attr, None)
@@ -330,10 +236,8 @@ def _serialise_value(value: Any) -> Optional[dict]:
except (TypeError, ValueError):
result[attr] = str(val)
return result
- # Plain string (runner-level _pending_messages)
- if isinstance(value, str):
+ if isinstance(value, str): # runner-level _pending_messages
return {"text": value}
- # Dict — try direct serialisation
if isinstance(value, dict):
try:
json.dumps(value)
@@ -343,60 +247,34 @@ def _serialise_value(value: Any) -> Optional[dict]:
return {"text": str(value)}
-def recover_pending_to_db(
- session_db=None,
-) -> int:
+def recover_pending_to_db(session_db=None) -> int:
"""Recover flushed pending messages into state.db via SessionDB.
- Reads all ``*.json`` files from the flush directory, inserts messages
- using ``SessionDB.append_message`` (so FTS indexing, session metadata
- updates, and all required columns are handled correctly), and deletes
- the flush file on success.
-
- Parameters
- ----------
- session_db:
- An existing ``SessionDB`` instance. If ``None``, a new one is
- opened on the default ``state.db`` path.
-
- Returns
- -------
- int
- Number of messages recovered.
+ Reads all ``*.json`` files from the flush directory, inserts messages via
+ ``SessionDB.append_message`` and deletes each flush file on success.
+ ``session_db=None`` opens (and afterwards releases) the shared default
+ ``state.db``. Returns the number of messages recovered.
"""
flush_dir = _get_flush_dir()
flush_files = sorted(flush_dir.glob("*.json"))
if not flush_files:
return 0
- # Use the provided SessionDB or open one on the default path.
- own_db = False
- if session_db is None:
+ own_db = session_db is None
+ if own_db:
from hermes_state import get_shared_session_db
session_db = get_shared_session_db()
- own_db = True
-
- def _close_owned_db() -> None:
- if not own_db:
- return
- try:
- from hermes_state import release_or_close
- release_or_close(session_db)
- except Exception:
- pass
recovered = 0
- for path in flush_files:
- try:
+ try:
+ for path in flush_files:
payload = json.loads(path.read_text(encoding="utf-8"))
- # Agent-history snapshots use a different schema (reason +
- # messages list) and are meant for manual operator recovery,
- # not automatic DB insertion. Skip them silently.
+ # Agent-history snapshots (reason + messages list) are for manual
+ # operator recovery, not automatic DB insertion.
if payload.get("reason") == "shutdown-with-unpersisted-agent-history":
continue
- # Cap-dropped transcript payloads carry the full message dict
- # keyed by session_id — replay directly (#78182). This handles
- # spool files that were never drained before a restart.
+ # Cap-dropped transcript payloads carry the full message dict keyed
+ # by session_id — replay directly (spool never drained before restart).
if payload.get("reason") == TRANSCRIPT_CAP_DROP_REASON:
data = payload.get("data", {}) or {}
spooled_sid = data.get("session_id", "")
@@ -428,19 +306,11 @@ def recover_pending_to_db(
)
continue
- # The session_key is a gateway routing key (e.g.
- # "agent:main:telegram:supergroup:..."). We need the actual
- # session_id (e.g. "20260728_120000_abc123") to append a
- # message row. Try the session_id field from the serialised
- # data first; fall back to scanning sessions for a matching
- # session_key in the source column.
+ # session_key is a gateway routing key (e.g. "agent:main:telegram:...");
+ # appending a row needs the real session_id, which only the
+ # serialised data can supply at this recovery stage.
session_id = data.get("session_id", "")
-
if not session_id:
- # Try to extract from the session_key itself — gateway
- # session keys contain the session_id as the last segment
- # in some formats, but that's not guaranteed. Log and
- # skip if we can't resolve it.
logger.warning(
"Cannot recover pending message for %s: no session_id "
"in flush file and session_key-to-id resolution is not "
@@ -451,48 +321,32 @@ def recover_pending_to_db(
continue
session_db.append_message(
- session_id=session_id,
- role="user",
- content=text,
+ session_id=session_id, role="user", content=text,
timestamp=payload.get("ts", int(time.time())),
)
recovered += 1
path.unlink(missing_ok=True)
- except BaseException:
- # Shutdown cancellation/interrupt must not strand an owned DB.
- _close_owned_db()
- raise
- except Exception as exc:
- logger.warning(
- "Failed to recover pending message from %s: %s",
- path, exc,
- )
- # Leave the file for next startup retry.
-
- _close_owned_db()
+ finally:
+ # Shutdown cancellation/interrupt must not strand an owned DB.
+ if own_db:
+ try:
+ from hermes_state import release_or_close
+ release_or_close(session_db)
+ except Exception:
+ pass
if recovered:
- logger.info(
- "Recovered %d pending message(s) from shutdown flush", recovered,
- )
+ logger.info("Recovered %d pending message(s) from shutdown flush", recovered)
return recovered
-def flush_agent_history_to_file(
- session_id: Optional[str],
- history: list,
-) -> None:
+def flush_agent_history_to_file(session_id: Optional[str], history: list) -> None:
"""Best-effort dump of an agent's in-memory transcript before teardown.
Used when ``_flush_messages_to_session_db`` raises (e.g. FTS/SQLite
- index corruption, #72680): the live ``agent._session_messages`` could
- not be written to disk, and a plain debug log would lose it permanently
- when the process exits. Serialize to an atomic JSON file outside the
- broken DB so an operator can salvage the conversation after repairing
- state.db.
-
- Failures are swallowed — shutdown must never block on a best-effort
- backup.
+ corruption): the transcript is written outside the broken DB so an
+ operator can salvage it after repairing state.db. Failures are
+ swallowed — shutdown must never block on a best-effort backup.
"""
if not history:
return
@@ -507,24 +361,17 @@ def flush_agent_history_to_file(
)
except Exception:
continue
- _write_payload(
- flush_dir,
- {
- "reason": "shutdown-with-unpersisted-agent-history",
- "issue": "#72680",
- "session_id": session_id,
- "count": len(snapshot),
- "messages": snapshot,
- },
- )
+ _write_payload(flush_dir, {
+ "reason": "shutdown-with-unpersisted-agent-history",
+ "issue": "#72680",
+ "session_id": session_id,
+ "count": len(snapshot),
+ "messages": snapshot,
+ })
logger.warning(
"Preserved %d in-memory message(s) for session %s "
"(possible FTS corruption — recover after repairing state.db)",
- len(snapshot),
- session_id,
+ len(snapshot), session_id,
)
except Exception as _e:
- logger.warning(
- "Agent-history shutdown preservation failed for session %s: %s",
- session_id, _e,
- )
+ logger.warning("Agent-history shutdown preservation failed for session %s: %s", session_id, _e)
diff --git a/gateway/shutdown_forensics.py b/gateway/shutdown_forensics.py
index b13ef4476a4..ac0f7d3edf2 100644
--- a/gateway/shutdown_forensics.py
+++ b/gateway/shutdown_forensics.py
@@ -1,18 +1,10 @@
"""Shutdown forensics — capture context when the gateway receives SIGTERM/SIGINT.
-The gateway's ``shutdown_signal_handler`` runs synchronously inside the
-asyncio event loop. We can't safely block it for long, but we DO want a
-durable record of who/what triggered the shutdown so that "the gateway
-keeps dying" incidents can be diagnosed after the fact.
-
-This module exposes :func:`snapshot_shutdown_context`, a fast (<10ms),
-non-blocking probe that returns a structured dict the signal handler can
-log immediately, plus :func:`spawn_async_diagnostic`, a fire-and-forget
-``ps`` walk that runs as a detached subprocess so it can't block teardown
-even if /proc is wedged.
-
-Anything that needs to wait (e.g. shelling out to ``ps aux``) belongs in
-the async helper, never in the synchronous probe.
+``shutdown_signal_handler`` runs synchronously inside the asyncio loop, so
+:func:`snapshot_shutdown_context` is a fast (<10ms) non-blocking probe it can log
+immediately, and :func:`spawn_async_diagnostic` is a fire-and-forget ``ps`` walk in
+a detached subprocess so it can't block teardown even if /proc is wedged. Anything
+that waits belongs in the async helper, never in the synchronous probe.
"""
from __future__ import annotations
@@ -26,18 +18,15 @@ import time
from pathlib import Path
from typing import Any, Dict, List, Optional
-from gateway.restart import (
- DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT,
- resolve_systemd_timeout_stop_sec,
-)
+from gateway.restart import DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT, resolve_systemd_timeout_stop_sec
import contextlib
-_SIGNAL_NAME_BY_NUM: Dict[int, str] = {}
-for _name in ("SIGTERM", "SIGINT", "SIGHUP", "SIGQUIT", "SIGUSR1", "SIGUSR2"):
- _val = getattr(signal, _name, None)
- if _val is not None:
- _SIGNAL_NAME_BY_NUM[int(_val)] = _name
+_SIGNAL_NAME_BY_NUM: Dict[int, str] = {
+ int(getattr(signal, _name)): _name
+ for _name in ("SIGTERM", "SIGINT", "SIGHUP", "SIGQUIT", "SIGUSR1", "SIGUSR2")
+ if getattr(signal, _name, None) is not None
+}
def _signal_name(sig: Any) -> str:
@@ -64,7 +53,7 @@ def _read_proc_field(pid: int, key: str) -> Optional[str]:
def _read_proc_cmdline(pid: int) -> Optional[str]:
- """Read /proc/<pid>/cmdline as a printable string. Linux only; None elsewhere."""
+ """Read /proc/<pid>/cmdline (NUL-separated) as a printable string. Linux only."""
try:
with open(f"/proc/{pid}/cmdline", "rb") as fh:
data = fh.read()
@@ -72,24 +61,18 @@ def _read_proc_cmdline(pid: int) -> Optional[str]:
return None
if not data:
return None
- # cmdline uses NUL separators
return data.replace(b"\x00", b" ").decode("utf-8", errors="replace").strip()
def _proc_summary(pid: int) -> Dict[str, Any]:
- """Compact /proc/<pid> snapshot: pid, ppid, state, uid, cmdline.
-
- Best-effort. Missing fields are simply omitted rather than raising.
- """
+ """Compact /proc/<pid> snapshot (pid, ppid, state, uid, cmdline); missing fields omitted."""
summary: Dict[str, Any] = {"pid": pid}
if pid <= 0:
return summary
- name = _read_proc_field(pid, "Name")
- if name is not None:
- summary["name"] = name
- state = _read_proc_field(pid, "State")
- if state is not None:
- summary["state"] = state
+ for out_key, proc_key in (("name", "Name"), ("state", "State")):
+ value = _read_proc_field(pid, proc_key)
+ if value is not None:
+ summary[out_key] = value
ppid = _read_proc_field(pid, "PPid")
if ppid is not None:
with contextlib.suppress(ValueError):
@@ -105,28 +88,29 @@ def _proc_summary(pid: int) -> Dict[str, Any]:
return summary
-def snapshot_shutdown_context(received_signal: Any = None) -> Dict[str, Any]:
- """Fast (<10ms) snapshot of who/what is asking us to shut down.
+def _read_marker(path: Path) -> Optional[str]:
+ """Return the marker file's text, or None if absent/unreadable."""
+ if not path.exists():
+ return None
+ try:
+ return path.read_text(encoding="utf-8")
+ except OSError:
+ return None
- Captures:
- * The signal number/name (so SIGINT vs SIGTERM is visible)
- * Our own PID/ppid + parent process info from /proc (Linux)
- * Whether systemd is our parent (``ppid==1`` or ``INVOCATION_ID`` set)
- * Whether takeover/planned-stop markers exist (consumed lazily by the caller)
- * /proc/self limits + load average (1-min)
- * Wall-clock and monotonic timestamps for cross-correlating later phases
+def snapshot_shutdown_context(received_signal: Any = None) -> Dict[str, Any]:
+ """Fast (<10ms) snapshot of who/what is asking us to shut down.
- Pure stdlib, never raises, never blocks on subprocesses.
+ Signal name/number, own + parent /proc summaries, systemd parentage,
+ takeover/planned-stop markers, TracerPid, 1-min load, wall/monotonic
+ timestamps. Pure stdlib, never raises, never blocks on subprocesses.
"""
- now = time.time()
- monotonic = time.monotonic()
pid = os.getpid()
ppid = os.getppid()
ctx: Dict[str, Any] = {
- "ts": now,
- "ts_monotonic": monotonic,
+ "ts": time.time(),
+ "ts_monotonic": time.monotonic(),
"signal": _signal_name(received_signal),
"signal_num": int(received_signal) if received_signal is not None else None,
"pid": pid,
@@ -135,8 +119,7 @@ def snapshot_shutdown_context(received_signal: Any = None) -> Dict[str, Any]:
"self": _proc_summary(pid),
}
- # systemd context. If we were started by a systemd unit, INVOCATION_ID
- # is set in our env. ppid==1 (init) is also a strong signal that
+ # INVOCATION_ID is set by systemd units; ppid==1 also strongly suggests
# systemd reaped+forwarded the SIGTERM.
invocation_id = os.environ.get("INVOCATION_ID")
if invocation_id:
@@ -146,14 +129,11 @@ def snapshot_shutdown_context(received_signal: Any = None) -> Dict[str, Any]:
ctx["systemd_journal_stream"] = journal_stream
ctx["under_systemd"] = bool(invocation_id) or ppid == 1
- # Load average — high load points the finger at "something else
- # crushing the box" rather than "external killer".
+ # High load points at "something crushing the box" rather than an external killer.
with contextlib.suppress(OSError, AttributeError):
ctx["loadavg_1m"] = os.getloadavg()[0]
- # /proc/self/status TracerPid: nonzero means a debugger / strace is
- # attached. Useful when "phantom SIGKILL" turns out to be a manual
- # gdb session.
+ # Nonzero TracerPid means a debugger/strace is attached.
try:
tracer = _read_proc_field(pid, "TracerPid")
if tracer is not None and tracer != "0":
@@ -162,34 +142,22 @@ def snapshot_shutdown_context(received_signal: Any = None) -> Dict[str, Any]:
except (TypeError, ValueError):
pass
- # Race-detection hint: did somebody recently start a sibling gateway
- # with --replace? We can't see the new process directly here, but if
- # there's a takeover marker on disk that DOESN'T name us, that's a
- # smoking gun for "another --replace instance is killing us".
- # Filenames mirror gateway.status (._TAKEOVER_MARKER_FILENAME /
- # _PLANNED_STOP_MARKER_FILENAME); we use string literals here so the
- # signal-handler path stays import-light.
+ # Race hint: a takeover marker on disk that does NOT name us is a smoking
+ # gun for "another --replace instance is killing us". Filenames mirror
+ # gateway.status; literals keep the signal-handler path import-light.
try:
hermes_home_str = os.environ.get("HERMES_HOME")
if hermes_home_str:
- takeover_path = Path(hermes_home_str) / ".gateway-takeover.json"
- if takeover_path.exists():
- try:
- raw = takeover_path.read_text(encoding="utf-8")
- ctx["takeover_marker"] = raw[:300]
- ctx["takeover_marker_for_self"] = (
- f'"target_pid": {pid}' in raw
- or f"'target_pid': {pid}" in raw
- )
- except OSError:
- pass
- planned_stop_path = Path(hermes_home_str) / ".gateway-planned-stop.json"
- if planned_stop_path.exists():
- try:
- raw = planned_stop_path.read_text(encoding="utf-8")
- ctx["planned_stop_marker"] = raw[:300]
- except OSError:
- pass
+ raw = _read_marker(Path(hermes_home_str) / ".gateway-takeover.json")
+ if raw is not None:
+ ctx["takeover_marker"] = raw[:300]
+ ctx["takeover_marker_for_self"] = (
+ f'"target_pid": {pid}' in raw
+ or f"'target_pid': {pid}" in raw
+ )
+ raw = _read_marker(Path(hermes_home_str) / ".gateway-planned-stop.json")
+ if raw is not None:
+ ctx["planned_stop_marker"] = raw[:300]
except Exception: # noqa: BLE001 — never raise from a signal handler
pass
@@ -202,29 +170,18 @@ def spawn_async_diagnostic(
*,
timeout_seconds: float = 5.0,
) -> Optional[int]:
- """Fire-and-forget ``ps``-style snapshot written to ``log_path``.
-
- Runs as a detached subprocess so it can't block the asyncio event loop
- or compete with platform teardown. The subprocess uses its own
- ``timeout`` so a wedged ``ps`` still self-cleans within
- ``timeout_seconds``.
-
- Returns the subprocess PID on success, ``None`` on failure. Never
- raises.
+ """Fire-and-forget ``ps``-style snapshot appended to ``log_path``.
- We deliberately avoid ``subprocess.run(["ps", "aux"])`` from inside the
- signal handler (the pre-existing pattern): on a busy host with hundreds
- of processes, ``ps aux`` can take >2s to walk /proc, during which the
- asyncio loop is frozen and adapter teardown can't begin.
+ A detached subprocess (own ``timeout`` so a wedged ``ps`` self-cleans) rather
+ than a blocking ``ps aux`` in the signal handler, which can freeze the loop >2s
+ on a busy host. Returns the subprocess PID, or ``None`` on failure / Windows.
"""
try:
log_path.parent.mkdir(parents=True, exist_ok=True)
except OSError:
return None
- # Inline shell so we don't have to ship a helper script. bash -c is
- # available on every POSIX target we support; on Windows we just skip
- # the snapshot (the platform doesn't ship ps anyway).
+ # bash -c is available on every POSIX target; Windows has no ps anyway.
if sys.platform == "win32":
return None
@@ -243,26 +200,18 @@ def spawn_async_diagnostic(
)
try:
- # Open the log file in append mode and let the subprocess inherit.
- # We use os.O_APPEND so concurrent diagnostics from rapid signals
- # don't trample each other.
+ # O_APPEND so concurrent diagnostics from rapid signals don't trample each other.
fd = os.open(str(log_path), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o644)
except OSError:
return None
try:
- # Detach from our process group so the subprocess survives even
- # if systemd kills our cgroup with KillMode=control-group (which
- # would also reap us anyway, but defense in depth). Without
- # start_new_session, a SIGKILL on our cgroup takes the diag down
- # before it can flush.
+ # start_new_session: survive systemd killing our cgroup (KillMode=control-group)
+ # long enough to flush.
proc = subprocess.Popen(
["timeout", f"{timeout_seconds:.0f}", "bash", "-c", script],
- stdout=fd,
- stderr=subprocess.STDOUT,
- stdin=subprocess.DEVNULL,
- start_new_session=True,
- close_fds=True,
+ stdout=fd, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
+ start_new_session=True, close_fds=True,
)
except (FileNotFoundError, OSError):
with contextlib.suppress(OSError):
@@ -289,9 +238,7 @@ def format_context_for_log(ctx: Dict[str, Any]) -> str:
extras: List[str] = []
if ctx.get("takeover_marker") is not None:
for_self = ctx.get("takeover_marker_for_self")
- extras.append(
- f"takeover_marker_present={'self' if for_self else 'other'}"
- )
+ extras.append(f"takeover_marker_present={'self' if for_self else 'other'}")
if ctx.get("planned_stop_marker") is not None:
extras.append("planned_stop_marker_present=yes")
if ctx.get("tracer_pid"):
@@ -299,12 +246,8 @@ def format_context_for_log(ctx: Dict[str, Any]) -> str:
extras_str = (" " + " ".join(extras)) if extras else ""
# Parent cmdline is the most useful single signal — log it prominently.
return (
- f"signal={sig} "
- f"under_systemd={under_systemd} "
- f"parent_pid={parent_pid} "
- f"parent_name={parent_name} "
- f"loadavg_1m={load_str}"
- f"{extras_str} "
+ f"signal={sig} under_systemd={under_systemd} parent_pid={parent_pid} "
+ f"parent_name={parent_name} loadavg_1m={load_str}{extras_str} "
f"parent_cmdline={parent_cmd!r}"
)
@@ -323,48 +266,32 @@ def check_systemd_timing_alignment(
) -> Optional[Dict[str, Any]]:
"""At startup, sanity-check that systemd's TimeoutStopSec covers stop.
- When the gateway is run under a stale systemd unit file (e.g. the user
- upgraded hermes-agent but never re-ran ``hermes setup`` to regenerate
- the unit), ``TimeoutStopSec`` can be smaller than the full stop budget
- (``restart_drain_timeout`` vs ``cron_drain_timeout`` + cleanup reserve,
- plus headroom). Result: SIGTERM arrives, the drain starts, and systemd
- SIGKILLs the cgroup mid-drain — looks like a phantom kill in the journal
- because the journal only logs ``code=killed status=9``.
-
- Returns ``None`` when the alignment is fine OR we can't determine it
- (not running under systemd, ``systemctl`` unavailable, etc.). Returns
- a dict with ``timeout_stop_sec`` + ``drain_timeout`` + ``mismatch``
- bool when we have data to report.
-
- Best-effort. Never raises.
+ A stale unit file (upgraded without re-running ``hermes setup``) can have
+ ``TimeoutStopSec`` below the stop budget, so systemd SIGKILLs the cgroup
+ mid-drain — a phantom ``code=killed status=9`` in the journal. Returns ``None``
+ when aligned OR undeterminable (not under systemd, no ``systemctl``); otherwise
+ a dict with ``timeout_stop_sec``/``drain_timeout``/``expected_min``/``mismatch``.
"""
invocation_id = os.environ.get("INVOCATION_ID")
if not invocation_id:
return None # Not running under systemd (or at least not directly)
- # Try to identify our unit name and ask systemctl for its config.
+ # /proc/self/cgroup: "0::/user.slice/.../hermes-gateway.service"
unit_name: Optional[str] = None
try:
- # /proc/self/cgroup gives us "0::/user.slice/.../hermes-gateway.service"
with open("/proc/self/cgroup", encoding="utf-8") as fh:
for line in fh:
- # systemd cgroup line ends with the unit name
- if ".service" in line:
- parts = line.strip().split("/")
- for p in reversed(parts):
- if p.endswith(".service"):
- unit_name = p
- break
- if unit_name:
- break
+ unit_name = next(
+ (p for p in reversed(line.strip().split("/")) if p.endswith(".service")), None
+ )
+ if unit_name:
+ break
except (OSError, FileNotFoundError):
pass
if not unit_name:
return None
- # Query systemctl for TimeoutStopUSec. Use --user OR system depending
- # on which manager actually owns the unit. Try user first since
- # that's the common case for hermes.
+ # Try --user first (the common case for hermes), then the system manager.
timeout_us: Optional[int] = None
for flag in (["--user"], []):
try:
@@ -380,11 +307,9 @@ def check_systemd_timing_alignment(
for line in result.stdout.splitlines():
if line.startswith("TimeoutStopUSec="):
value = line.split("=", 1)[1].strip()
- # Try numeric microseconds first
- if value.isdigit():
- timeout_us = int(value)
- else:
- timeout_us = parse_systemd_duration_to_us(value)
+ timeout_us = (
+ int(value) if value.isdigit() else parse_systemd_duration_to_us(value)
+ )
if timeout_us is not None:
break
if timeout_us is not None:
@@ -394,9 +319,7 @@ def check_systemd_timing_alignment(
return None
timeout_stop_sec = timeout_us / 1_000_000.0
- expected = float(
- resolve_systemd_timeout_stop_sec(drain_timeout, cron_drain_timeout)
- )
+ expected = float(resolve_systemd_timeout_stop_sec(drain_timeout, cron_drain_timeout))
return {
"unit": unit_name,
"timeout_stop_sec": timeout_stop_sec,
@@ -410,58 +333,45 @@ def check_systemd_timing_alignment(
def parse_systemd_duration_to_us(raw: str) -> Optional[int]:
"""Parse 'TimeoutStopUSec=1min 30s' / '90s' style values to microseconds.
- systemd accepts a wide grammar; we cover the common cases (s, ms, min,
- h) and return None on anything unexpected. Never raises.
+ Covers the common units (us, ms, s, min, h); a bare number is seconds.
+ Returns None on anything unexpected. Never raises.
Public: also consumed by hermes_cli.gateway's restart-wait sizing.
"""
if not raw:
return None
units = {
- "us": 1,
- "ms": 1_000,
- "s": 1_000_000,
- "sec": 1_000_000,
- "min": 60_000_000,
- "h": 3_600_000_000,
- "hr": 3_600_000_000,
+ "us": 1, "ms": 1_000, "s": 1_000_000, "sec": 1_000_000,
+ "min": 60_000_000, "h": 3_600_000_000, "hr": 3_600_000_000,
}
total_us = 0
token = ""
digits = ""
+
+ def _flush() -> bool:
+ """Fold the pending ``digits``/``token`` pair into ``total_us``."""
+ nonlocal total_us, token, digits
+ multiplier = units.get(token.lower()) if token else 1_000_000
+ if multiplier is None or not digits:
+ return False
+ try:
+ total_us += int(float(digits) * multiplier)
+ except ValueError:
+ return False
+ digits = ""
+ token = ""
+ return True
+
for ch in raw + " ":
if ch.isdigit() or ch == ".":
- if token:
- # End previous unit, start new number
- multiplier = units.get(token.lower())
- if multiplier is None or not digits:
- return None
- try:
- total_us += int(float(digits) * multiplier)
- except ValueError:
- return None
- digits = ""
- token = ""
+ # A digit after a unit ends the previous number
+ if token and not _flush():
+ return None
digits += ch
elif ch.isalpha():
token += ch
- elif digits and token:
- multiplier = units.get(token.lower())
- if multiplier is None:
- return None
- try:
- total_us += int(float(digits) * multiplier)
- except ValueError:
- return None
- digits = ""
- token = ""
- elif digits and not token:
- # Bare number = seconds (rare but valid)
- try:
- total_us += int(float(digits) * 1_000_000)
- except ValueError:
- return None
- digits = ""
+ elif digits and not _flush():
+ return None
return total_us if total_us > 0 else None
diff --git a/gateway/shutdown_watchdog.py b/gateway/shutdown_watchdog.py
index 1218e4b3d97..0f629b6945b 100644
--- a/gateway/shutdown_watchdog.py
+++ b/gateway/shutdown_watchdog.py
@@ -1,24 +1,13 @@
-"""Out-of-loop shutdown and event-loop liveness backstops (#66892, #69089).
-
-When the asyncio loop freezes mid-drain, every asyncio-based recovery path is
-structurally unable to fire: the drain deadline, status rewrites, and forensics
-all need the same loop that is stuck. launchd/systemd KeepAlive only restarts a
-*dead* process, so a wedged-but-alive gateway sits as a zombie until manual
-SIGKILL.
-
-This module provides:
-
-1. A plain OS-thread shutdown watchdog armed at ``stop()``. If shutdown has not
- completed within ``restart_drain_timeout + grace``, it dumps all-thread
- stacks via ``faulthandler`` plus a metadata snapshot, then ``os._exit`` so
- the service manager can revive the process.
-2. An event-loop heartbeat file at ``<HERMES_HOME>/state/gateway.heartbeat`` so
- external supervision can distinguish "process alive" from "loop frozen"
- (``gateway_state.json`` alone can't — it only rewrites on transitions/turns).
-3. A lifetime thread watchdog that can still diagnose and hard-exit when the
- event loop is too frozen to run its own heartbeat or timeout callbacks.
-4. A self-rescheduling floor timer that keeps the loop selector's timeout
- finite, giving existing async recovery tasks a chance to resume.
+"""Out-of-loop shutdown and event-loop liveness backstops.
+
+A frozen asyncio loop takes every asyncio-based recovery path down with it, and
+launchd/systemd KeepAlive only restarts a *dead* process. Hence: (1) an OS-thread
+shutdown watchdog that dumps stacks and ``os._exit``s past ``restart_drain_timeout
++ grace``; (2) a heartbeat file at ``<HERMES_HOME>/state/gateway.heartbeat`` so
+supervisors can tell "process alive" from "loop frozen" (``gateway_state.json``
+only rewrites on transitions/turns); (3) a lifetime thread watchdog that hard-exits
+when the loop is too frozen to run its own callbacks; (4) a self-rescheduling floor
+timer that keeps the selector timeout finite so async recovery tasks can resume.
"""
from __future__ import annotations
@@ -43,23 +32,27 @@ import contextlib
logger = logging.getLogger(__name__)
# Extra leash beyond ``agent.restart_drain_timeout`` so a slow-but-progressing
-# drain is not cut short. Matches the issue #66892 suggested hardening.
+# drain is not cut short.
DEFAULT_SHUTDOWN_WATCHDOG_GRACE_S = 60.0
DEFAULT_HEARTBEAT_INTERVAL_S = 30.0
DEFAULT_LOOP_FLOOR_TIMER_INTERVAL_S = 5.0
DEFAULT_LOOP_WATCHDOG_INTERVAL_S = 30.0
DEFAULT_LOOP_WATCHDOG_TIMEOUT_S = 10.0
-# 3 sustained misses (~90-120s of loop block) escalate. The false-positive
-# class that motivated raising this (the watchdog's own on-loop heartbeat
-# fsync stalling the loop it monitors) is fixed at the root by the off-loop
-# heartbeat write + two-witness probe (#90502), so the default stays tight
-# for genuine wedges. Deployments with legitimately slow loops can tune via
-# gateway.loop_watchdog_* in config.yaml.
+# 3 sustained misses (~90-120s of loop block) escalate; stays tight because the
+# heartbeat write is off-loop. Slow loops tune gateway.loop_watchdog_* in config.yaml.
DEFAULT_LOOP_WATCHDOG_MAX_STRIKES = 3
_HEARTBEAT_RELATIVE = ("state", "gateway.heartbeat")
_WATCHDOG_DUMP_RELATIVE = ("logs", "gateway-shutdown-watchdog.log")
+def _coerce_float(value: Any, default: float, floor: float = 0.0) -> float:
+ """``max(float(value), floor)``, or ``default`` when not coercible."""
+ try:
+ return max(float(value), floor)
+ except (TypeError, ValueError):
+ return default
+
+
class _LoopFloorTimerHandle:
"""Cancelable owner for the currently scheduled selector floor timer."""
@@ -68,14 +61,11 @@ class _LoopFloorTimerHandle:
self._interval = interval
self._cancelled = False
self._timer: Optional[asyncio.TimerHandle] = None
- self._schedule()
-
- def _schedule(self) -> None:
- self._timer = self._loop.call_later(self._interval, self._tick)
+ self._tick()
def _tick(self) -> None:
if not self._cancelled:
- self._schedule()
+ self._timer = self._loop.call_later(self._interval, self._tick)
def cancel(self) -> None:
self._cancelled = True
@@ -89,16 +79,12 @@ class _LoopLivenessWatchdogHandle:
def __init__(self, stop_event: threading.Event, thread: threading.Thread):
self._stop_event = stop_event
self._thread = thread
+ self.join = thread.join
+ self.is_alive = thread.is_alive
def stop(self) -> None:
self._stop_event.set()
- def join(self, timeout: Optional[float] = None) -> None:
- self._thread.join(timeout=timeout)
-
- def is_alive(self) -> bool:
- return self._thread.is_alive()
-
def _arm_loop_floor_timer(
loop: asyncio.AbstractEventLoop,
@@ -124,18 +110,13 @@ def start_loop_liveness_watchdog(
) -> Optional[_LoopLivenessWatchdogHandle]:
"""Start an out-of-loop watchdog that hard-exits after missed probes.
- The guard is on by default; operators opt out with
- ``gateway.loop_watchdog: false`` in config.yaml (enforced by the caller,
- ``GatewayRunner._start_loop_liveness_guards`` — this module stays
- config-agnostic so bare-loop tests can drive it directly).
+ The ``gateway.loop_watchdog: false`` opt-out is enforced by the caller
+ (``GatewayRunner._start_loop_liveness_guards``) so this stays config-agnostic.
"""
- interval = probe_interval
- timeout = probe_timeout
- strikes_limit = max_strikes
stop_event = threading.Event()
def _wait_for_probe(probe_event: threading.Event) -> Optional[bool]:
- deadline = time.monotonic() + timeout
+ deadline = time.monotonic() + probe_timeout
while True:
if stop_event.is_set():
return None
@@ -147,18 +128,15 @@ def start_loop_liveness_watchdog(
def _watchdog() -> None:
strikes = 0
- while not stop_event.wait(timeout=interval):
+ while not stop_event.wait(timeout=probe_interval):
probe_event = threading.Event()
try:
loop.call_soon_threadsafe(probe_event.set)
except RuntimeError:
- # A normally closed loop cannot be probed and no longer needs
- # a process-liveness backstop.
+ # Normally closed loop: nothing left to backstop.
return
except Exception:
- logger.debug(
- "Failed to schedule gateway loop liveness probe", exc_info=True
- )
+ logger.debug("Failed to schedule gateway loop liveness probe", exc_info=True)
return
responded = _wait_for_probe(probe_event)
@@ -171,7 +149,7 @@ def start_loop_liveness_watchdog(
if stop_event.is_set():
return
strikes += 1
- if strikes < strikes_limit:
+ if strikes < max_strikes:
continue
if stop_event.is_set():
@@ -190,9 +168,8 @@ def start_loop_liveness_watchdog(
logger.debug("Loop liveness faulthandler dump failed", exc_info=True)
if stop_event.is_set():
return
- # Record the watchdog exit in the lifecycle sentinel so the next
- # boot reports "watchdog hard-exit" instead of misclassifying
- # this as an unclean SIGKILL/OOM death (NS-608).
+ # Record the exit in the lifecycle sentinel so the next boot reports
+ # "watchdog hard-exit" rather than an unclean SIGKILL/OOM death.
try:
from gateway.lifecycle_ledger import mark_exited
mark_exited(exit_code, reason="loop_liveness_watchdog")
@@ -201,11 +178,7 @@ def start_loop_liveness_watchdog(
os._exit(exit_code)
return
- thread = threading.Thread(
- target=_watchdog,
- daemon=True,
- name="gateway-loop-liveness-watchdog",
- )
+ thread = threading.Thread(target=_watchdog, daemon=True, name="gateway-loop-liveness-watchdog")
try:
thread.start()
except Exception:
@@ -217,39 +190,33 @@ def start_loop_liveness_watchdog(
def _process_hermes_home() -> Path:
"""HERMES_HOME for process-level identity files (ignore profile overrides)."""
val = os.environ.get("HERMES_HOME", "").strip()
- if val:
- return Path(val)
- return get_hermes_home()
+ return Path(val) if val else get_hermes_home()
+
+
+def _home(home: Optional[Path]) -> Path:
+ return home if home is not None else _process_hermes_home()
def get_loop_heartbeat_path(home: Optional[Path] = None) -> Path:
"""Return ``<HERMES_HOME>/state/gateway.heartbeat``."""
- base = home if home is not None else _process_hermes_home()
- return base.joinpath(*_HEARTBEAT_RELATIVE)
+ return _home(home).joinpath(*_HEARTBEAT_RELATIVE)
-def get_loop_tick_socket_path(
- home: Optional[Path] = None, pid: Optional[int] = None
-) -> Path:
- """Return the loop-scheduling witness socket for ``pid``.
-
- ``<HERMES_HOME>/state/gateway.loop-tick.<pid>.sock`` — PID-suffixed so a
- leftover node from a previous process can never be mistaken for this
- gateway's witness. Served by the gateway loop itself (see
- ``_tick_socket_handler``): an answer is direct proof that the loop is
- dispatching, which is exactly the property the heartbeat file lost when
- its write moved off-loop (#90502).
+def get_loop_tick_socket_path(home: Optional[Path] = None, pid: Optional[int] = None) -> Path:
+ """Return ``<HERMES_HOME>/state/gateway.loop-tick.<pid>.sock``.
+
+ PID-suffixed so a stale node from a previous process is never mistaken for
+ this gateway's witness. Served by the loop itself (``_tick_socket_handler``),
+ so an answer proves the loop dispatches — what the off-loop heartbeat can't.
"""
- base = home if home is not None else _process_hermes_home()
- return base.joinpath(
+ return _home(home).joinpath(
"state", f"gateway.loop-tick.{int(pid if pid is not None else os.getpid())}.sock"
)
def get_shutdown_watchdog_dump_path(home: Optional[Path] = None) -> Path:
"""Return the faulthandler / metadata dump path for a fired watchdog."""
- base = home if home is not None else _process_hermes_home()
- return base.joinpath(*_WATCHDOG_DUMP_RELATIVE)
+ return _home(home).joinpath(*_WATCHDOG_DUMP_RELATIVE)
def write_loop_heartbeat(
@@ -259,10 +226,9 @@ def write_loop_heartbeat(
home: Optional[Path] = None,
extra: Optional[Dict[str, Any]] = None,
) -> Path:
- """Atomically rewrite the loop-liveness heartbeat file.
+ """Atomically rewrite the loop-liveness heartbeat file. Never raises.
- ``start_time`` is the gateway process start (``time.time()`` epoch seconds)
- so supervisors can detect PID reuse. Best-effort — never raises.
+ ``start_time`` (process start, epoch seconds) lets supervisors detect PID reuse.
"""
path = get_loop_heartbeat_path(home)
payload: Dict[str, Any] = {
@@ -272,14 +238,10 @@ def write_loop_heartbeat(
}
if start_time is not None:
payload["start_time"] = float(start_time)
- # Embed a cheap memory sample (own RSS + MemAvailable + swap) so the
- # heartbeat doubles as a rolling pre-death telemetry snapshot: after an
- # unclean death (SIGKILL/OOM/VM loss) the last heartbeat is the closest
- # surviving record of memory pressure — see gateway.lifecycle_ledger
- # (NS-608). Best-effort; <1ms of /proc reads on Linux, {} elsewhere.
+ # Cheap memory sample (RSS + MemAvailable + swap): after an unclean death the
+ # last heartbeat is the closest surviving record of memory pressure.
try:
from gateway.lifecycle_ledger import sample_memory
-
mem = sample_memory()
if mem:
payload["mem"] = mem
@@ -300,23 +262,10 @@ def resolve_shutdown_watchdog_delay(
grace_s: float = DEFAULT_SHUTDOWN_WATCHDOG_GRACE_S,
) -> float:
"""Return the wall-clock leash for the shutdown watchdog thread."""
- try:
- drain = max(float(drain_timeout), 0.0)
- except (TypeError, ValueError):
- drain = 0.0
- try:
- grace = max(float(grace_s), 0.0)
- except (TypeError, ValueError):
- grace = DEFAULT_SHUTDOWN_WATCHDOG_GRACE_S
- return drain + grace
+ return _coerce_float(drain_timeout, 0.0) + _coerce_float(grace_s, DEFAULT_SHUTDOWN_WATCHDOG_GRACE_S)
-def _write_watchdog_dump(
- dump_path: Path,
- *,
- delay_s: float,
- snapshot: Optional[Dict[str, Any]],
-) -> None:
+def _write_watchdog_dump(dump_path: Path, *, delay_s: float, snapshot: Optional[Dict[str, Any]]) -> None:
"""Best-effort faulthandler + metadata dump before hard-exit."""
try:
dump_path.parent.mkdir(parents=True, exist_ok=True)
@@ -344,8 +293,7 @@ def _write_watchdog_dump(
except Exception:
pass
- # Also dump to stderr so journald/launchd capture it even if the file
- # write failed (wedged disk was one of the #66892 hypotheses).
+ # Also to stderr so journald/launchd capture it even if the disk is wedged.
try:
sys.stderr.write(
f"Gateway shutdown watchdog fired after {delay_s:.0f}s "
@@ -368,25 +316,16 @@ def arm_shutdown_watchdog(
) -> threading.Event:
"""Arm a daemon-thread hard-exit backstop for a wedged shutdown path.
- If ``done_event`` is set before ``delay_s`` elapses, the thread exits
- quietly (normal / progressing shutdown completed). Otherwise it dumps
- diagnostics and calls ``os._exit(exit_code)``.
-
- Never raises. Returns the ``done_event`` (creating one when omitted) so
- the caller can disarm on successful completion.
+ Exits quietly if ``done_event`` is set within ``delay_s``, else dumps diagnostics
+ and ``os._exit(exit_code)``. Never raises; returns ``done_event`` for disarming.
"""
done = done_event if done_event is not None else threading.Event()
- try:
- delay = max(float(delay_s), 0.0)
- except (TypeError, ValueError):
- delay = DEFAULT_SHUTDOWN_WATCHDOG_GRACE_S
-
+ delay = _coerce_float(delay_s, DEFAULT_SHUTDOWN_WATCHDOG_GRACE_S)
if delay <= 0:
return done
def _watchdog() -> None:
- # Wait with interruptible chunks so a late disarm doesn't need the
- # full remaining sleep to observe done_event.
+ # Chunked wait so a late disarm is observed within ~1s.
deadline = time.monotonic() + delay
while time.monotonic() < deadline:
remaining = deadline - time.monotonic()
@@ -416,10 +355,9 @@ def arm_shutdown_watchdog(
for stream in (sys.stdout, sys.stderr):
with contextlib.suppress(Exception):
stream.flush()
- # Mirror _exit_after_graceful_shutdown: release PID file + runtime
- # lock BEFORE the log drain (locks must never be stranded), then
- # drain the async log queue so the logger.critical above actually
- # reaches the file before os._exit bypasses atexit. (#66892)
+ # Mirror _exit_after_graceful_shutdown: release PID file + runtime lock
+ # BEFORE the log drain (locks must never be stranded), then drain the async
+ # log queue so logger.critical reaches the file before os._exit skips atexit.
try:
from gateway.status import remove_pid_file, release_gateway_runtime_lock
remove_pid_file()
@@ -431,8 +369,7 @@ def arm_shutdown_watchdog(
drain_log_queue(timeout=1.0)
except Exception:
pass
- # Record the watchdog exit so the next boot's unclean-death detector
- # reports "shutdown watchdog fired" instead of SIGKILL/OOM (NS-608).
+ # So the next boot reports "shutdown watchdog fired", not SIGKILL/OOM.
try:
from gateway.lifecycle_ledger import mark_exited
mark_exited(exit_code, reason="shutdown_watchdog")
@@ -447,17 +384,11 @@ def arm_shutdown_watchdog(
return done
-async def _tick_socket_handler(
- reader: asyncio.StreamReader, writer: asyncio.StreamWriter
-) -> None:
- """Answer a liveness ping with one byte.
-
- Runs on the gateway loop: the reply is produced only while the loop is
- actually dispatching, so a successful read is a witness of loop
- schedulability that no executor thread and no filesystem stall can
- refresh. A UNIX-socket write is a socket-buffer copy — no fsync, no
- disk I/O — so the witness keeps working on the exact filesystem that
- stalls the heartbeat write. Best-effort; never raises.
+async def _tick_socket_handler(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ """Answer a liveness ping with one byte. Never raises.
+
+ Runs on the gateway loop, so a reply witnesses loop schedulability; the write
+ is a socket-buffer copy (no fsync), immune to the stalls that age the heartbeat.
"""
try:
writer.write(b"1")
@@ -478,57 +409,25 @@ async def loop_heartbeat_forever(
) -> None:
"""Rewrite the loop heartbeat file on a cadence until cancelled / gated off.
- Runs as an asyncio task on the gateway loop — if the loop freezes, this task
- stops and the file mtime/updated_at goes stale for external monitors. That
- property is load-bearing and is preserved below: the write is still
- *initiated* by the loop, so a frozen loop still lets the file age.
-
- The write itself is handed to a thread, because it is not free. It ends in
- ``atomic_json_write`` -> ``os.fsync``, and on a filesystem that stalls, that
- fsync blocks whatever thread runs it. Doing it inline meant the loop-liveness
- watchdog's own heartbeat could block the loop it exists to monitor: the probe
- times out at ``DEFAULT_LOOP_WATCHDOG_TIMEOUT_S`` (10s) and gives up after
- ``DEFAULT_LOOP_WATCHDOG_MAX_STRIKES`` (3), a ~90-120s budget, while a WSL2
- VHDX under io pressure was measured stalling a trivial stat-and-fsync probe
- at p99 31s and max 112s. So the watchdog killed the loop for being
- unresponsive at the moment it was blocked inside the watchdog's own write.
-
- Awaited, not fire-and-forget: an unawaited task would keep the file fresh
- while the loop was wedged, which is exactly the signal the docstring above
- promises. And a single in-flight write at a time, so a 112s stall cannot pile
- up one queued thread per interval behind it.
-
- Because the write is now off-loop, file freshness is no longer *proof* of
- loop schedulability: a stalled write or a saturated executor can age the file
- while the loop runs, and a write that lands after the loop froze can keep it
- fresh. The file therefore stops being sufficient authority on its own. This
- task also arms a loop-scheduling witness — a UNIX socket answered by the
- loop itself (``_tick_socket_handler``) — and records whether it is armed in
- the heartbeat payload (``loop_tick_socket``). External probes must require
- the witness to agree with file staleness before classifying a loop as
- wedged; see ``hermes_cli.gateway.probe_gateway_loop_liveness`` for the
- two-witness contract.
+ Runs on the gateway loop so a frozen loop lets the file age for monitors. The
+ write (``atomic_json_write`` -> ``os.fsync``) goes to a thread: inline, a stalled
+ filesystem blocked the loop inside its own heartbeat and the liveness watchdog
+ killed it (WSL2 fsync stalls measured at p99 31s / max 112s vs a ~90-120s
+ budget). The thread write is *awaited*, never fire-and-forget: an unawaited
+ task would keep the file fresh while the loop was wedged, and one in-flight
+ write at a time keeps a long stall from queuing a thread per interval.
+
+ Off-loop, file freshness alone no longer proves loop schedulability, so this
+ task also arms a loop-scheduling witness (``_tick_socket_handler``) and records
+ it as ``loop_tick_socket``. Probes must require the witness to agree with file
+ staleness before classifying WEDGED; see ``probe_gateway_loop_liveness``.
"""
- try:
- interval = max(float(interval_s), 1.0)
- except (TypeError, ValueError):
- interval = DEFAULT_HEARTBEAT_INTERVAL_S
-
- # Arm the loop-scheduling witness. Best-effort: a failed bind (permissions,
- # path length) must not abort the gateway or the file heartbeat — it only
- # disables the witness, and the payload flag tells probes that staleness is
- # no longer sufficient authority to escalate.
- #
- # Windows (non-POSIX generally): asyncio AF_UNIX support is POSIX-only, so
- # the AF_UNIX arm below is gated to POSIX — an ungated call raised
- # AttributeError on every native-Windows gateway start (#96956). Instead of
- # leaving the witness permanently absent there, the non-POSIX arm binds a
- # TCP loopback server on 127.0.0.1 with an OS-assigned port and publishes
- # the port in the heartbeat payload (``loop_tick_tcp_port``) so probes know
- # where to connect. Same protocol, same loop-owned semantics. If that bind
- # fails, the payload records loop_tick_socket=False and probes classify
- # UNKNOWN, never WEDGED — the graceful-drain backstop stays in place. (WSL2
- # — the #90502 incident environment — is Linux and arms the socket.)
+ interval = _coerce_float(interval_s, DEFAULT_HEARTBEAT_INTERVAL_S, floor=1.0)
+
+ # Arm the witness. Best-effort: a failed bind only disables it, and the payload
+ # flag makes probes classify UNKNOWN, never WEDGED (drain backstop stays). asyncio
+ # AF_UNIX is POSIX-only (ungated it raised AttributeError on native Windows), so
+ # non-POSIX binds TCP loopback on 127.0.0.1 and publishes ``loop_tick_tcp_port``.
tick_server = None
tick_socket_path = None
tick_tcp_port = None
@@ -536,21 +435,12 @@ async def loop_heartbeat_forever(
if os.name == "posix":
tick_socket_path = get_loop_tick_socket_path(home)
tick_socket_path.parent.mkdir(parents=True, exist_ok=True)
- # Re-bind over a leftover node from a dead process (os._exit(75) /
- # SIGKILL skip the finally-unlink; PID reuse re-lands on this
- # PID-suffixed path) is handled by asyncio itself:
- # create_unix_server os.remove()s an existing socket node before
- # binding — guarded by test_producer_rebinds_over_stale_socket_node.
- # What asyncio does NOT do is clean up SIBLING nodes from other
- # dead PIDs, so sweep those to keep state/ from accumulating
- # gateway.loop-tick.*.sock nodes across crash-restart cycles.
- # POSIX-only: os.kill(pid, 0) is a liveness probe here, but on
- # Windows os.kill calls TerminateProcess for non-CTRL signals —
- # and AF_UNIX server nodes are never created there anyway.
+ # create_unix_server removes a leftover node at OUR path (os._exit /
+ # SIGKILL skip the finally-unlink) but not SIBLING nodes from other dead
+ # PIDs, so sweep those. os.kill(pid, 0) is a liveness probe only on
+ # POSIX (Windows would TerminateProcess), hence inside this gate.
try:
- for _stale in tick_socket_path.parent.glob(
- "gateway.loop-tick.*.sock"
- ):
+ for _stale in tick_socket_path.parent.glob("gateway.loop-tick.*.sock"):
if _stale == tick_socket_path:
continue
try:
@@ -563,26 +453,11 @@ async def loop_heartbeat_forever(
except OSError:
_stale.unlink(missing_ok=True)
except Exception:
- logger.debug(
- "stale loop-tick socket sweep failed", exc_info=True
- )
- tick_server = await asyncio.start_unix_server(
- _tick_socket_handler, path=str(tick_socket_path)
- )
+ logger.debug("stale loop-tick socket sweep failed", exc_info=True)
+ tick_server = await asyncio.start_unix_server(_tick_socket_handler, path=str(tick_socket_path))
else:
- # Windows / non-POSIX: no AF_UNIX support, so use a TCP loopback
- # server on 127.0.0.1 as the loop-scheduling witness instead.
- # Same protocol (connect → read one byte "1"), same semantics
- # (pure in-memory, zero disk I/O, answered only when the loop
- # is dispatching). Port is dynamic (assigned by the OS) and
- # published via the heartbeat payload so external probes know
- # where to connect.
- tick_server = await asyncio.start_server(
- _tick_socket_handler, host="127.0.0.1", port=0
- )
- # Get the actual port assigned by the OS
- _sock_addrs = tick_server.sockets if hasattr(tick_server, "sockets") else []
- for _s in _sock_addrs:
+ tick_server = await asyncio.start_server(_tick_socket_handler, host="127.0.0.1", port=0)
+ for _s in tick_server.sockets or []:
try:
_sname = _s.getsockname()
if isinstance(_sname, tuple) and len(_sname) >= 2:
@@ -607,23 +482,15 @@ async def loop_heartbeat_forever(
write_loop_heartbeat,
start_time=start_time,
home=home,
- extra={
- "loop_tick_socket": tick_server is not None,
- "loop_tick_tcp_port": tick_tcp_port,
- },
+ extra={"loop_tick_socket": tick_server is not None, "loop_tick_tcp_port": tick_tcp_port},
)
- except asyncio.CancelledError:
- raise
except Exception:
logger.debug("Loop heartbeat write failed off-loop", exc_info=True)
try:
- # Immediate first write so monitors see a fresh file as soon as the
- # gateway is running, not after the first interval.
+ # Immediate first write so monitors see a fresh file at once.
await _write_off_loop()
- while True:
- if should_continue is not None and not should_continue():
- return
+ while should_continue is None or should_continue():
await asyncio.sleep(interval)
if should_continue is not None and not should_continue():
return
diff --git a/gateway/slash_access.py b/gateway/slash_access.py
index e4a398dc14a..ac80c6338c5 100644
--- a/gateway/slash_access.py
+++ b/gateway/slash_access.py
@@ -1,52 +1,33 @@
"""Per-platform slash command access control.
-This module sits beside the existing per-platform allowlist (``allow_from``)
-and adds a second axis: of the users who are *allowed to talk to the
-gateway*, which ones can run *which slash commands*.
-
-Two lists per platform scope (DM vs group, mirroring ``allow_from`` vs
-``group_allow_from``):
+A second axis beside ``allow_from``: of the users allowed to talk to the
+gateway, which ones may run which slash commands. Two lists per scope (DM vs
+group, mirroring ``allow_from`` / ``group_allow_from``):
- ``allow_admin_from`` — user IDs that get every registered slash
command (built-in + plugin-registered).
- - ``user_allowed_commands`` — slash command names non-admin users may
- run. Empty / unset → non-admins get no
- slash commands.
-
-Backward compatibility:
-
- If ``allow_admin_from`` is not set for a scope, slash command gating
- is disabled entirely for that scope. Every allowed user can run every
- slash command, exactly like before. This means existing installs are
- unaffected until an operator opts in by listing at least one admin.
-
-The gate is applied at the slash command dispatch site in
-``gateway/run.py`` so it covers BOTH built-in and plugin-registered
-commands via the live registry. Gating slash commands does not affect
-plain chat — non-admin users can still talk to the agent normally,
-they just can't trigger commands outside ``user_allowed_commands``.
-
-Authored as a slimmed-down salvage of PR #4443's permission tiers
-(co-authored by @ReqX). The full tier system, audit log, usage
-tracking, rate limiting, and tool filtering from that PR are not
-included here — only the slash-command access split.
+ - ``user_allowed_commands`` — command names non-admins may run. Empty /
+ unset → non-admins get no slash commands
+ (beyond the ``_ALWAYS_ALLOWED_FOR_USERS`` floor).
+
+Backward compatibility: if ``allow_admin_from`` is not set for a scope,
+gating is disabled for that scope and every allowed user can run every
+command, so existing installs are unaffected until an operator lists an admin.
+
+The gate is applied at the dispatch site in ``gateway/run.py`` so it covers
+both built-in and plugin commands via the live registry. It never affects
+plain chat — non-admins still talk to the agent normally.
"""
from __future__ import annotations
from dataclasses import dataclass
-from typing import Any, FrozenSet, Iterable, Optional, Tuple
-
-
-# Slash commands that MUST stay reachable for any allowed user, even when
-# slash gating is enabled and the user has no commands listed. Without this
-# carve-out, a non-admin user has no way to discover what they can or
-# can't do (``/help``, ``/whoami``) and no way to see what state the agent
-# is in (``/status``). These mirror the smallest set of read-only commands
-# we'd hand to a guest. Operators can still narrow this further by writing
-# their own ``user_allowed_commands`` (this set is only the implicit
-# fallback floor — anything in ``user_allowed_commands`` overrides it
-# additively, never restrictively).
+from typing import Any, Callable, FrozenSet, Iterable, Optional, Tuple
+
+
+# Floor of read-only commands every allowed user keeps even under gating, so a
+# non-admin can still discover what they can do. ``user_allowed_commands`` only
+# adds to this set, never restricts it.
_ALWAYS_ALLOWED_FOR_USERS: FrozenSet[str] = frozenset({
"help",
"whoami",
@@ -57,9 +38,8 @@ _ALWAYS_ALLOWED_FOR_USERS: FrozenSet[str] = frozenset({
class SlashAccessPolicy:
"""Resolved access policy for a single (platform, scope) pair.
- ``scope`` is ``"dm"`` for direct messages and ``"group"`` for groups,
- channels, threads, and any other multi-user context. The mapping from
- SessionSource.chat_type → scope happens in ``policy_for_source``.
+ ``scope`` is ``"dm"`` for direct messages and ``"group"`` for every other
+ multi-user context; ``policy_for_source`` maps chat_type → scope.
"""
enabled: bool # gating active for this scope?
@@ -67,36 +47,27 @@ class SlashAccessPolicy:
user_allowed_commands: FrozenSet[str]
def is_admin(self, user_id: Optional[str]) -> bool:
+ # Gating disabled → everyone is admin so callers can use is_admin/can_run uniformly.
if not self.enabled:
- # Gating disabled → treat every allowed user as admin so
- # downstream code can keep using ``is_admin`` / ``can_run``
- # uniformly.
return True
if not user_id:
return False
return str(user_id) in self.admin_user_ids
def can_run(self, user_id: Optional[str], canonical_cmd: str) -> bool:
- if not self.enabled:
- return True
if self.is_admin(user_id):
return True
if not canonical_cmd:
return False
- if canonical_cmd in _ALWAYS_ALLOWED_FOR_USERS:
- return True
- return canonical_cmd in self.user_allowed_commands
+ return canonical_cmd in _ALWAYS_ALLOWED_FOR_USERS or canonical_cmd in self.user_allowed_commands
_DM_CHAT_TYPES = frozenset({"dm", "direct", "private", ""})
-def _coerce_id_list(raw: Any) -> FrozenSet[str]:
- """Normalize a YAML-loaded admin/user list into a frozenset of strings.
-
- Accepts ``None``, list, tuple, or comma-separated string. Stringifies
- each entry and strips whitespace; empty entries are dropped.
- """
+def _coerce_list(raw: Any, normalize: Callable[[str], str]) -> FrozenSet[str]:
+ """Normalize a YAML-loaded value (None, list/tuple/set, comma string, or scalar)
+ into a frozenset of stripped, non-empty strings, applying ``normalize`` to each."""
if raw is None:
return frozenset()
if isinstance(raw, (list, tuple, set, frozenset)):
@@ -104,37 +75,19 @@ def _coerce_id_list(raw: Any) -> FrozenSet[str]:
elif isinstance(raw, str):
items = (s for s in raw.split(",") if s.strip())
else:
- # single scalar (int user id, etc.)
- items = (raw,)
- out: list[str] = []
- for it in items:
- s = str(it).strip()
- if s:
- out.append(s)
- return frozenset(out)
+ items = (raw,) # single scalar (int user id, etc.)
+ return frozenset(s for s in (normalize(str(it).strip()) for it in items) if s)
-def _coerce_command_list(raw: Any) -> FrozenSet[str]:
- """Normalize a slash command allowlist.
+def _coerce_id_list(raw: Any) -> FrozenSet[str]:
+ """Normalize an admin/user id list into a frozenset of strings."""
+ return _coerce_list(raw, lambda s: s)
- Strips leading slashes so YAML can read either ``["help", "status"]``
- or ``["/help", "/status"]``. Lowercase canonicalization matches how
- ``resolve_command()`` stores names.
- """
- if raw is None:
- return frozenset()
- if isinstance(raw, (list, tuple, set, frozenset)):
- items: Iterable[Any] = raw
- elif isinstance(raw, str):
- items = (s for s in raw.split(",") if s.strip())
- else:
- items = (raw,)
- out: list[str] = []
- for it in items:
- s = str(it).strip().lstrip("/").lower()
- if s:
- out.append(s)
- return frozenset(out)
+
+def _coerce_command_list(raw: Any) -> FrozenSet[str]:
+ """Normalize a command allowlist: strip leading slashes (accepts ``/help`` or
+ ``help``) and lowercase to match how ``resolve_command()`` stores names."""
+ return _coerce_list(raw, lambda s: s.lstrip("/").lower())
def _scope_for_chat_type(chat_type: Optional[str]) -> str:
@@ -144,18 +97,14 @@ def _scope_for_chat_type(chat_type: Optional[str]) -> str:
def _platform_extra(platform_config: Any) -> dict:
- """Return the ``extra`` dict from a PlatformConfig-like object.
-
- Defensively handles None and non-PlatformConfig shapes so calling
- code can stay simple.
- """
+ """Return the ``extra`` dict from a PlatformConfig-like object (or a bare
+ dict, as some test harnesses pass); {} for None/unknown shapes."""
if platform_config is None:
return {}
extra = getattr(platform_config, "extra", None)
if isinstance(extra, dict):
return extra
if isinstance(platform_config, dict):
- # Some test harnesses pass dicts directly.
return platform_config
return {}
@@ -170,39 +119,30 @@ def _keys_for_scope(scope: str) -> Tuple[str, str]:
def policy_from_extra(extra: dict, scope: str) -> SlashAccessPolicy:
"""Build a policy from a platform's ``extra`` dict for one scope.
- DM scope falls back to group scope keys ONLY for ``user_allowed_commands``
- when the DM scope didn't specify its own. This keeps the common case
- (operator wants the same command set DM and group) ergonomic without
- forcing duplication. Admin lists are NOT cross-scope: an admin in
- DMs is not implicitly an admin in a group.
+ DM scope falls back to ``group_user_allowed_commands`` ONLY for the command
+ list, and only when DM didn't set its own, so operators list a shared set
+ once. Admin lists are NOT cross-scope: a DM admin is not a group admin.
"""
admin_key, cmd_key = _keys_for_scope(scope)
admin_ids = _coerce_id_list(extra.get(admin_key))
cmds = _coerce_command_list(extra.get(cmd_key))
if scope == "dm" and not cmds:
- # DM didn't specify — let group's user_allowed_commands fall through
- # so operators only need to list it once if it's the same.
cmds = _coerce_command_list(extra.get("group_user_allowed_commands"))
- enabled = bool(admin_ids)
return SlashAccessPolicy(
- enabled=enabled,
+ enabled=bool(admin_ids),
admin_user_ids=admin_ids,
user_allowed_commands=cmds,
)
def policy_for_source(gateway_config: Any, source: Any) -> SlashAccessPolicy:
- """Resolve the access policy for a SessionSource.
-
- Returns a "disabled" policy (gating off, allow everything) when:
- - gateway_config is None
- - the platform has no PlatformConfig
- - the platform's PlatformConfig has no admin list set for the scope
+ """Resolve the slash-gating policy for a SessionSource.
- Callers should treat the returned policy as authoritative for slash
- command gating only. It does not gate plain chat messages.
+ Returns a disabled (allow-everything) policy when gateway_config/source is
+ None, the platform has no PlatformConfig, or no admin list is set for the
+ scope. Gates slash commands only, never plain chat.
"""
if gateway_config is None or source is None:
return SlashAccessPolicy(
diff --git a/gateway/startup_watchdog.py b/gateway/startup_watchdog.py
index a7fe9abc24e..229315ad914 100644
--- a/gateway/startup_watchdog.py
+++ b/gateway/startup_watchdog.py
@@ -1,14 +1,11 @@
"""Compatibility shim — the real implementation is ``hermes_startup_watchdog``.
-The startup-liveness watchdog (OOF-298) must be armable *before* the
-``gateway`` package is imported: ``gateway/__init__`` eagerly pulls in the
-config/session/delivery graph, and an import-time deadlock is squarely inside
-the watchdog's coverage mandate. The implementation therefore lives at the
-repository top level as a stdlib-only module.
-
-This shim keeps the intuitive ``gateway.startup_watchdog`` import path
-working for code that runs after the package is loaded (the disarm site in
-``gateway.run``, tests, operators poking at a REPL).
+The startup-liveness watchdog must be armable *before* the ``gateway`` package
+is imported (``gateway/__init__`` eagerly pulls in the config/session/delivery
+graph, and an import-time deadlock is inside the watchdog's coverage mandate),
+so the implementation lives at the repository top level as a stdlib-only
+module. This shim keeps ``gateway.startup_watchdog`` importable for code that
+runs after the package is loaded (the disarm site in ``gateway.run``, tests).
"""
from hermes_startup_watchdog import ( # noqa: F401
diff --git a/gateway/status.py b/gateway/status.py
index 5ce7187cc08..94b1cd03350 100644
--- a/gateway/status.py
+++ b/gateway/status.py
@@ -1,14 +1,8 @@
-"""
-Gateway runtime status helpers.
-
-Provides PID-file based detection of whether the gateway daemon is running,
-used by send_message's check_fn to gate availability in the CLI.
+"""Gateway runtime status helpers.
-The PID file lives at ``{HERMES_HOME}/gateway.pid``. HERMES_HOME defaults to
-``~/.hermes`` but can be overridden via the environment variable. This means
-separate HERMES_HOME directories naturally get separate PID files — a property
-that will be useful when we add named profiles (multiple agents running
-concurrently under distinct configurations).
+PID-file based detection of whether the gateway daemon is running (used by
+send_message's check_fn to gate CLI availability). The PID file lives at
+``{HERMES_HOME}/gateway.pid``, so separate homes/profiles get separate files.
"""
import copy
@@ -55,8 +49,7 @@ logger = logging.getLogger(__name__)
class StormInfo(NamedTuple):
- """Result of a respawn-storm check: how many starts, over what window, and
- the backoff the caller should sleep to break the storm."""
+ """Respawn-storm check result: start count, window, and backoff to sleep."""
count: int
window_s: float
@@ -64,24 +57,16 @@ class StormInfo(NamedTuple):
def _get_starts_log_path() -> Path:
- """Path to the append-only gateway-start ledger used by the respawn-storm
- breaker. Distinct from ``restart_loop.json`` (the auto-resume guard) — no
- collision."""
+ """Append-only start ledger for the respawn-storm breaker (distinct from ``restart_loop.json``)."""
return get_hermes_home() / "gateway-starts.log"
def record_start_and_check_storm(
max_starts: int = 5, window_s: float = 120.0, *, backoff_cap_s: float = 300.0
) -> Optional[StormInfo]:
- """Record this gateway start and report whether a respawn storm is underway.
+ """Record this start; return :class:`StormInfo` when > ``max_starts`` landed in ``window_s``.
- Appends the current UTC timestamp to the starts-log, prunes entries older
- than ``window_s``, and ring-buffers the file so it can't grow unbounded.
- Returns a :class:`StormInfo` when more than ``max_starts`` starts landed in
- the window (with an exponential backoff capped at ``backoff_cap_s``), else
- ``None``.
-
- Best-effort: any bookkeeping failure is logged and swallowed so a broken
+ Best-effort: bookkeeping failures are logged and swallowed so a broken
ledger can never crash gateway startup.
"""
try:
@@ -103,11 +88,8 @@ def record_start_and_check_storm(
existing.append(now)
- # Keep only starts within the sliding window for the storm decision.
recent = [ts for ts in existing if now - ts <= window_s]
-
- # Ring-buffer what we persist so the file stays bounded even if the
- # window is wide or starts are frequent.
+ # Ring-buffer the persisted file so it stays bounded.
keep = max(max_starts * 4, 40)
to_write = existing[-keep:]
@@ -131,14 +113,11 @@ def record_start_and_check_storm(
def _get_process_hermes_home() -> Path:
- """Return the process-level HERMES_HOME, skipping context-local overrides.
-
- Gateway identity files (PID, lock, runtime status, takeover/stop markers)
- must always live in the directory the gateway process was launched with.
- ``get_hermes_home()`` honors ``_HERMES_HOME_OVERRIDE`` contextvar used for
- per-session profile dispatch, which would route these files into the wrong
- profile directory when a profile-context task happens to be active at write
- time. See issue #56986.
+ """Process-level HERMES_HOME, skipping context-local overrides.
+
+ Gateway identity files (PID, lock, runtime status, markers) must live in the
+ home the process was launched with; ``get_hermes_home()`` honors the
+ per-session ``_HERMES_HOME_OVERRIDE`` contextvar and would misroute them.
"""
val = os.environ.get("HERMES_HOME", "").strip()
if val:
@@ -165,21 +144,15 @@ def recorded_gateway_home_conflicts(
) -> bool:
"""True when a persisted gateway record names a DIFFERENT HERMES_HOME.
- Cross-profile kill refusal (#89315): a poisoned/contaminated PID record
- inside one profile's home can truthfully name ANOTHER profile's live
- gateway (its ``hermes_home`` stamp records the real owner). Any
- destructive caller about to signal the recorded PID must consult this
- first and refuse when the record positively proves the target belongs to
- a different profile — otherwise ``gateway stop``/``restart``/``profile
- delete`` from profile B SIGTERMs profile A's gateway and the supervisors
- enter the mutual restart loop from the issue report.
-
- ``expected_home`` overrides the comparison base (e.g. ``profile delete``
- stopping a TARGET profile's gateway rather than the current process's).
- Legacy records without a ``hermes_home`` stamp return False — they prove
- nothing either way, and destructive callers already pair this with the
- exact PID + start-time identity guards. A comparison failure returns True
- (destructive action + unprovable ownership ⇒ fail closed).
+ Cross-profile kill refusal: a contaminated PID record in one profile's home
+ can truthfully name another profile's live gateway. Destructive callers must
+ refuse when the record proves foreign ownership, or profile B's stop/restart
+ SIGTERMs profile A's gateway and the supervisors enter a mutual restart loop.
+
+ ``expected_home`` overrides the comparison base (e.g. ``profile delete`` on a
+ target profile). Legacy records without ``hermes_home`` return False (they
+ prove nothing; callers pair this with PID + start-time guards). A comparison
+ failure returns True: destructive action + unprovable ownership => fail closed.
"""
if not isinstance(record, dict):
return False
@@ -199,12 +172,9 @@ _PROFILE_LABEL_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
def _profile_label_for_home(home: Path | str) -> Optional[str]:
- """Best-effort profile label for a HERMES_HOME path.
+ """Best-effort profile label: ``<root>/profiles/<name>`` -> name, root home -> "default", else None.
- Returns the profile name for ``<root>/profiles/<name>`` layouts (both
- ``~/.hermes/profiles/coder`` and Docker ``/opt/data/profiles/coder``),
- ``"default"`` for the deployment's root home, and ``None`` when no label
- can be inferred. Never raises — this feeds diagnostics only.
+ Never raises -- diagnostics only.
"""
try:
canonical = _canonical_hermes_home(home)
@@ -228,21 +198,18 @@ def _profile_label_for_home(home: Path | str) -> Optional[str]:
def scoped_lock_owner_label(record: Optional[dict[str, Any]]) -> Optional[str]:
- """Profile label for the gateway that owns a scoped credential lock.
-
- Scoped locks are machine-global, so the holder may belong to a different
- HERMES_HOME profile than the caller. Prefers the explicit ``profile``
- field stamped by :func:`acquire_scoped_lock`; falls back to inferring the
- label from the persisted ``hermes_home`` for locks written before the
- profile field existed. Returns ``None`` for legacy or malformed records
- so callers keep their PID-only wording.
+ """Profile label for the gateway owning a (machine-global) scoped lock.
+
+ Prefers the ``profile`` field stamped by :func:`acquire_scoped_lock`, then
+ infers from ``hermes_home`` for older locks. None for legacy/malformed
+ records so callers keep PID-only wording.
"""
if not isinstance(record, dict):
return None
profile = record.get("profile")
if isinstance(profile, str) and _PROFILE_LABEL_RE.match(profile.strip()):
- # Validate the persisted label — lock files are plain JSON on disk,
- # and this string flows into log lines and a suggested CLI command.
+ # Validated: lock files are plain JSON and this flows into log lines
+ # and a suggested CLI command.
return profile.strip()
home = record.get("hermes_home")
if isinstance(home, str) and home.strip():
@@ -252,16 +219,14 @@ def scoped_lock_owner_label(record: Optional[dict[str, Any]]) -> Optional[str]:
def _get_pid_path() -> Path:
"""Return the path to the gateway PID file, respecting HERMES_HOME."""
- home = _get_process_hermes_home()
- return home / "gateway.pid"
+ return _get_process_hermes_home() / "gateway.pid"
def _get_gateway_lock_path(pid_path: Optional[Path] = None) -> Path:
"""Return the path to the runtime gateway lock file."""
if pid_path is not None:
return pid_path.with_name(_GATEWAY_LOCK_FILENAME)
- home = _get_process_hermes_home()
- return home / _GATEWAY_LOCK_FILENAME
+ return _get_process_hermes_home() / _GATEWAY_LOCK_FILENAME
def _get_runtime_status_path() -> Path:
@@ -282,33 +247,19 @@ def _utc_now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
-# Reject epoch values before 2000-01-01T00:00:00Z: nothing in Hermes' lifetime
-# legitimately produced a gateway heartbeat last century, so anything older is
-# a corrupt or hand-edited state file (e.g. an accidental 0 / tiny int).
+# Epochs before 2000-01-01 are corrupt/hand-edited state (e.g. an accidental 0).
_EPOCH_MIN_PLAUSIBLE = 946684800.0 # 2000-01-01T00:00:00Z
def normalize_updated_at(value: Any) -> Optional[str]:
"""Coerce a persisted ``updated_at`` value to an RFC3339 string or ``None``.
- The ``gateway_state.json`` writers all emit RFC3339 via :func:`_utc_now_iso`,
- but the file can also be produced by legacy gateways (which wrote unix
- epoch floats), hand edits, or partial corruption. Every read/emit surface
- (``/api/status``'s ``gateway_updated_at``, the gateway's
- ``/health/detailed`` ``updated_at``) promises consumers ``string | null``
- (see ``web/src/lib/api.ts``), so this funnel enforces that contract:
-
- - ``str``: accepted iff :meth:`datetime.fromisoformat` parses it (a
- trailing ``Z`` is tolerated). Naive timestamps are coerced to UTC.
- Returns the canonical ``datetime.isoformat()`` rendering.
- - ``int`` / ``float``: treated as unix epoch **seconds** and converted to
- a UTC ISO string. Implausible values — before 2000-01-01, more than a
- day in the future, or non-finite — return ``None``.
- - ``bool``: returns ``None``. Although ``bool`` is an ``int`` subclass,
- ``True``/``False`` as a timestamp is always garbage (epoch 0/1 would be
- rejected by the range guard anyway); rejecting explicitly keeps the
- behaviour documented rather than incidental.
- - anything else (``None``, dict, list, ...): ``None``.
+ ``/api/status`` and ``/health/detailed`` promise ``string | null`` (see
+ ``web/src/lib/api.ts``), but the file may come from legacy gateways (epoch
+ floats), hand edits, or corruption. ``str``: accepted iff fromisoformat
+ parses it (trailing ``Z`` tolerated; naive -> UTC). ``int``/``float``:
+ epoch seconds; before 2000-01-01, > 1 day in the future, or non-finite ->
+ None. ``bool`` (an int subclass) and anything else -> None.
"""
if isinstance(value, bool):
return None
@@ -366,25 +317,18 @@ def terminate_pid(
force: bool = False,
expected_start_time: Optional[float] = None,
) -> None:
- """Terminate a PID with platform-appropriate force semantics.
+ """Terminate a PID; POSIX SIGTERM/SIGKILL, Windows taskkill /T /F for force.
- POSIX uses SIGTERM/SIGKILL. Windows uses taskkill /T /F for true force-kill
- because os.kill(..., SIGTERM) is not equivalent to a tree-killing hard stop.
-
- Identity guard: on Windows, ``force=True`` REQUIRES a matching
- ``expected_start_time`` (fail closed — taskkill /T /F on a recycled PID
- has killed svchost.exe and blue-screened the host, #89614). On POSIX an
- expectation is optional, but when the caller provides one and it no
- longer matches the live process, the kill is refused on every platform —
- a mismatched fingerprint always means the PID was recycled.
+ Identity guard: on Windows ``force=True`` REQUIRES a matching
+ ``expected_start_time`` (taskkill /T /F on a recycled PID has killed
+ svchost.exe). On POSIX it is optional, but a provided, mismatched
+ fingerprint refuses the kill everywhere -- the PID was recycled.
"""
- if force and expected_start_time is not None and not _IS_WINDOWS:
+ if force and (_IS_WINDOWS or expected_start_time is not None):
_assert_process_start_time_matches(pid, expected_start_time)
if force and _IS_WINDOWS:
- _assert_process_start_time_matches(pid, expected_start_time)
- # CREATE_NO_WINDOW: terminate_pid runs from the windowless pythonw.exe
- # gateway/desktop backend, so a bare taskkill spawn would flash a
- # conhost window on every force-kill.
+ # Hide flags: a bare taskkill spawn from windowless pythonw.exe would
+ # flash a conhost window on every force-kill.
from hermes_cli._subprocess_compat import windows_hide_flags
try:
@@ -417,33 +361,18 @@ def _get_scope_lock_path(scope: str, identity: str) -> Path:
def _get_process_start_time(pid: int) -> Optional[int]:
- """Return a stable per-process start-time fingerprint, or None.
-
- Used as a PID-reuse guard: a ``(pid, start_time)`` pair uniquely identifies
- a process, so a recycled PID (same number, different process) yields a
- different value and is never mistaken for the original.
-
- On Linux this is field 22 of ``/proc/<pid>/stat`` (start time in clock
- ticks since boot, an int). On platforms without ``/proc`` (macOS, Windows)
- we fall back to ``psutil.Process(pid).create_time()`` — a float epoch
- timestamp — quantized to an int (centiseconds) for stable equality.
-
- The two sources are never mixed on a single platform: ``/proc`` always
- succeeds first on Linux, and always fails on macOS/Windows so psutil is
- always used there. Because the guard only compares the value recorded at
- spawn against the live value *on the same host*, the differing units across
- platforms are irrelevant — only same-source equality matters.
+ """Stable per-process start-time fingerprint (PID-reuse guard), or None.
+
+ Linux: field 22 of ``/proc/<pid>/stat`` (clock ticks since boot). Without
+ ``/proc`` (macOS/Windows): psutil ``create_time()`` quantized to
+ centiseconds for stable equality. Units differ per platform but the guard
+ only ever compares same-host, same-source values.
"""
stat_path = Path(f"/proc/{pid}/stat")
try:
- # Field 22 in /proc/<pid>/stat is process start time (clock ticks).
return int(stat_path.read_text(encoding="utf-8").split()[21])
except (FileNotFoundError, IndexError, PermissionError, ValueError, OSError):
pass
-
- # No /proc (macOS / Windows): psutil is a hard dependency and exposes a
- # cross-platform creation time. Quantize to centiseconds so repeated reads
- # of the same process compare equal without float-precision fragility.
try:
import psutil # type: ignore
return int(round(psutil.Process(pid).create_time() * 100))
@@ -457,12 +386,7 @@ def get_process_start_time(pid: int) -> Optional[int]:
def _read_process_cmdline(pid: int) -> Optional[str]:
- """Return the process command line as a space-separated string.
-
- On Linux, reads /proc/<pid>/cmdline directly. On macOS and other
- platforms without /proc, falls back to ``ps -p <pid> -o command=``.
- On Windows (no /proc, no ps), uses psutil.
- """
+ """Process command line as one string: /proc, then ``ps``, then psutil (Windows)."""
cmdline_path = Path(f"/proc/{pid}/cmdline")
try:
raw = cmdline_path.read_bytes()
@@ -485,7 +409,6 @@ def _read_process_cmdline(pid: int) -> Optional[str]:
except (OSError, subprocess.TimeoutExpired):
pass
- # Windows fallback: psutil (already used by _pid_exists)
try:
import psutil # type: ignore
proc = psutil.Process(pid)
@@ -501,22 +424,14 @@ def _read_process_cmdline(pid: int) -> Optional[str]:
def _gateway_command_subcommand(command: str | None) -> str | None:
"""Return the Hermes gateway lifecycle subcommand from a command line.
- Lifecycle decisions (is the gateway up? did restart relaunch it?) must not
- fire on loose substring matches. The previous ``"... gateway" in cmdline``
- test also matched ``hermes_cli.main gateway status`` and even unrelated
- processes like ``python -m tui_gateway`` -- which made ``restart()`` race
- against a still-draining old process and ``status``/``start`` report false
- positives. This requires the actual ``gateway`` subcommand followed by
- ``run`` (or one of the gateway-dedicated entrypoints), excluding the other
- ``gateway`` management subcommands and any process that merely contains the
- word "gateway".
-
- Tokenizes quote-aware (``shlex``) so quoted Windows paths with spaces
- (``"C:\\Program Files\\...\\hermes-gateway.exe"``) survive, and strips
- ``--profile``/``-p`` selectors from anywhere in argv -- Hermes's
- ``_apply_profile_override`` removes them before argparse, so the profile
- flag (and a profile literally named ``gateway``) can legally appear on
- either side of the ``gateway`` subcommand.
+ Lifecycle decisions must not fire on loose substring matches: ``"gateway"
+ in cmdline`` also matched ``gateway status`` and ``python -m tui_gateway``,
+ making ``restart()`` race a draining process and ``status`` report false
+ positives. Requires a Hermes entrypoint plus the ``gateway`` subcommand (or
+ a gateway-dedicated entrypoint). Tokenizes quote-aware so Windows paths with
+ spaces survive, and strips ``--profile``/``-p`` selectors from anywhere in
+ argv -- ``_apply_profile_override`` removes them before argparse, so they
+ (and a profile literally named ``gateway``) can appear on either side.
"""
if not command:
return None
@@ -534,8 +449,7 @@ def _gateway_command_subcommand(command: str | None) -> str | None:
for token in tokens:
if token == "gateway/run.py" or token.endswith("/gateway/run.py"):
return "run"
- basename = token.rsplit("/", 1)[-1]
- if basename in ("hermes-gateway", "hermes-gateway.exe"):
+ if token.rsplit("/", 1)[-1] in ("hermes-gateway", "hermes-gateway.exe"):
return "run"
joined = " ".join(tokens)
@@ -547,9 +461,7 @@ def _gateway_command_subcommand(command: str | None) -> str | None:
if not has_gateway_entry:
return None
- # Drop profile selectors anywhere: --profile X / -p X / --profile=X / -p=X.
- # This consumes a profile VALUE of "gateway" too, so the real subcommand
- # token is the one we land on below.
+ # Drop --profile X / -p X / --profile=X / -p=X (consumes a VALUE of "gateway" too).
filtered: list[str] = []
skip_next = False
for token in tokens:
@@ -578,15 +490,12 @@ def looks_like_gateway_command_line(command: str | None) -> bool:
def looks_like_gateway_runtime_command_line(command: str | None) -> bool:
- """Return True for command lines that can host the gateway runtime.
-
- ``gateway restart`` is normally a management command, not the gateway
- runtime. On hosts without a service manager, though, the manual restart
- fallback executes ``run_gateway()`` in that same process, so its argv stays
- as ``gateway restart`` while it owns the webhook port and writes runtime
- state. Keep the public ``looks_like_gateway_command_line()`` strict, and
- use this broader matcher only when validating Hermes-owned runtime records
- or no-supervisor cleanup scans.
+ """True for command lines that can host the gateway runtime (``run`` or ``restart``).
+
+ Without a service manager the manual restart fallback runs ``run_gateway()``
+ in-process, so argv stays ``gateway restart`` while it owns the runtime.
+ Use only for validating Hermes-owned records / no-supervisor cleanup scans;
+ ``looks_like_gateway_command_line()`` stays strict.
"""
return _gateway_command_subcommand(command) in {"run", "restart"}
@@ -594,53 +503,37 @@ def looks_like_gateway_runtime_command_line(command: str | None) -> bool:
def _looks_like_gateway_process(pid: int) -> bool:
"""Return True when the live PID still looks like the Hermes gateway."""
cmdline = _read_process_cmdline(pid)
- if not cmdline:
- return False
- return looks_like_gateway_command_line(cmdline)
+ return bool(cmdline) and looks_like_gateway_command_line(cmdline)
def _record_looks_like_gateway(record: dict[str, Any]) -> bool:
"""Validate gateway identity from PID-file metadata when cmdline is unavailable."""
if record.get("kind") != _GATEWAY_KIND:
return False
-
argv = record.get("argv")
if not isinstance(argv, list) or not argv:
return False
-
- cmdline = " ".join(str(part) for part in argv)
- return looks_like_gateway_runtime_command_line(cmdline)
+ return looks_like_gateway_runtime_command_line(" ".join(str(part) for part in argv))
def _profile_name_for_home(profile_home: Path) -> Optional[str]:
- """Return the profile id a HERMES_HOME directory represents, or None.
-
- A named profile's home is ``<root>/profiles/<name>`` (immediate parent is
- ``profiles``). The root/default home (``~/.hermes`` or ``$HERMES_HOME``)
- has no such parent, so it maps to the default profile (``None`` here, which
- callers treat as "the bare, flag-less gateway").
- """
+ """Profile id for ``<root>/profiles/<name>``; None for the root/default home (bare gateway)."""
if profile_home.parent.name == "profiles":
return profile_home.name
return None
def _command_line_belongs_to_profile(command: str, profile_home: Path) -> bool:
- """Return True when a gateway command line belongs to ``profile_home``.
-
- Mirrors ``hermes_cli.gateway._matches_current_profile`` so the dashboard's
- cross-profile liveness fallback scopes a live PID to the *right* profile.
- In a per-profile container, one profile's stale ``gateway_state.json`` can
- record a PID that the OS has since recycled onto a DIFFERENT profile's live
- gateway. That recycled PID's command line still ``looks_like_gateway`` —
- so without a profile check the dead profile is reported running. A named
- profile gateway carries ``-p <name>``/``--profile <name>`` (or, rarely, an
- explicit ``HERMES_HOME=<path>``) on its argv; the default/root gateway runs
- bare with no profile flag.
+ """True when a gateway command line belongs to ``profile_home``.
+
+ Mirrors ``hermes_cli.gateway._matches_current_profile``: a stale state file
+ can record a PID the OS recycled onto a DIFFERENT profile's live gateway,
+ which still looks like a gateway -- so the dead profile would read running.
+ Named profiles carry ``-p``/``--profile <name>`` (or explicit
+ ``HERMES_HOME=``) on argv; the default gateway runs bare.
"""
- # Normalize separators before the substring match: on Windows,
- # str(Path) renders backslashes while a HERMES_HOME= value on the argv
- # may carry forward slashes (Git Bash, JSON configs) — and vice versa.
+ # Normalize separators: Windows str(Path) uses backslashes while an argv
+ # HERMES_HOME= value may use forward slashes (Git Bash, JSON) -- or vice versa.
command_lc = command.lower().replace("\\", "/")
profile_name = _profile_name_for_home(profile_home)
home_lc = str(profile_home).lower().replace("\\", "/")
@@ -653,11 +546,9 @@ def _command_line_belongs_to_profile(command: str, profile_home: Path) -> bool:
or f"hermes_home={home_lc}" in command_lc
)
- # Default/root profile: the gateway runs with no profile flag. Accept unless
- # the command advertises *some other* profile (an explicit -p/--profile) or
- # a non-matching explicit HERMES_HOME= on the argv. HERMES_HOME is usually
- # passed via the environment (not visible on the command line), so its mere
- # absence is not disqualifying — only a conflicting explicit value is.
+ # Default profile: accept unless argv names some other profile or a
+ # conflicting explicit HERMES_HOME= (its absence is not disqualifying --
+ # HERMES_HOME usually arrives via the environment).
if "--profile " in command_lc or " -p " in command_lc:
return False
return not ("hermes_home=" in command_lc and f"hermes_home={home_lc}" not in command_lc)
@@ -669,19 +560,12 @@ def _record_matches_live_gateway_pid(
*,
expected_home: Optional[Path] = None,
) -> bool:
- """Return True when a live PID still identifies as this gateway record.
-
- Prefer the live command line whenever it is readable. Runtime status files
- can outlive the gateway process they describe; if PID reuse leaves the same
- PID occupied by an s6 supervisor/log process, the stale record's argv should
- not make that unrelated process count as a running gateway.
-
- When ``expected_home`` is provided (the dashboard enumerating a specific
- profile's state file), the readable live command line must additionally
- belong to *that* profile — otherwise a PID recycled onto a different
- profile's live gateway would make the dead profile look alive. When the
- live command line cannot be read (Windows/permission), fall back to the
- persisted record so cross-platform behavior is preserved.
+ """True when a live PID still identifies as this gateway record.
+
+ Prefer the live command line: a stale record's argv must not make an
+ unrelated process (PID reuse) count as a gateway. With ``expected_home``
+ the live command line must also belong to that profile. When the command
+ line is unreadable (Windows/permission), fall back to the persisted record.
"""
live_cmdline = _read_process_cmdline(pid)
if live_cmdline:
@@ -697,24 +581,18 @@ def _build_pid_record() -> dict:
"kind": _GATEWAY_KIND,
"argv": list(sys.argv),
"start_time": _get_process_start_time(os.getpid()),
- # Scoped credential locks are machine-global rather than
- # HERMES_HOME-local. Persist the owning gateway's process home so an
- # explicit cross-profile --replace can place its planned-takeover
- # marker where the target process will actually read it.
+ # Scoped locks are machine-global; the owner's home lets a cross-profile
+ # --replace place its takeover marker where the target will read it.
"hermes_home": str(_canonical_hermes_home(_get_process_hermes_home())),
}
def _get_code_identity_fields() -> dict[str, Any]:
- """Code identity of THIS gateway process, for fleet version checks.
-
- Lazy import so ``gateway.status`` keeps no import-time dependency on
- ``hermes_cli``; the helper itself is cached per process. A gateway
- keeps serving the module versions it imported at startup, so stamping
- the identity into ``gateway_state.json`` lets `hermes update` (and the
- dashboard) prove whether a running gateway actually picked up new code
- after the restart phase — instead of assuming it did (#88654, #69754).
- Never raises; degrades to absent fields.
+ """Code identity of THIS process, stamped into ``gateway_state.json``.
+
+ Lets ``hermes update``/the dashboard prove a restarted gateway picked up new
+ code. Lazy import keeps ``gateway.status`` free of ``hermes_cli`` at import
+ time. Never raises; degrades to absent fields.
"""
try:
from hermes_cli.build_info import get_code_identity
@@ -731,23 +609,16 @@ def _get_code_identity_fields() -> dict[str, Any]:
def _pid_record_belongs_to_current_profile(
record: Optional[dict[str, Any]],
) -> bool:
- """Return True when the PID record's ``hermes_home`` matches the current process.
+ """True when the record's ``hermes_home`` matches the current process.
- PID records written by ``_build_pid_record()`` include the gateway's
- ``hermes_home`` at write time. If a profile gateway was started (or recorded)
- under a different HERMES_HOME, the record belongs to a different profile
- and must be ignored — otherwise the default-profile gateway can mistakenly
- assume the identity of another profile (issue #74872).
-
- Records that predate the ``hermes_home`` field (pre-#74872 gateways) are
- accepted conservatively (no field → assume current profile).
+ A record written under a different HERMES_HOME belongs to another profile
+ and must be ignored, or the default gateway assumes that profile's identity.
+ Legacy records without the field are accepted conservatively.
"""
if not isinstance(record, dict):
return False
record_home = record.get("hermes_home")
if not record_home:
- # Records without hermes_home belong to a pre-#74872 gateway;
- # accept them conservatively.
return True
return _same_hermes_home(record_home, _get_process_hermes_home())
@@ -767,17 +638,24 @@ def _build_runtime_status_record() -> dict[str, Any]:
return payload
-def _read_json_file(path: Path) -> Optional[dict[str, Any]]:
+def _read_text_file(path: Path) -> Optional[str]:
+ """Stripped file text, or None when absent/empty/unreadable.
+
+ OSError: vanished or permission flipped between exists() and read.
+ UnicodeDecodeError: non-UTF-8 / binary garbage (truncated or clobbered file).
+ """
if not path.exists():
return None
try:
raw = path.read_text(encoding="utf-8").strip()
except (OSError, UnicodeDecodeError):
- # OSError: file vanished or permission flipped between exists() and
- # read. UnicodeDecodeError: file holds non-UTF-8 / binary garbage
- # (a truncated or clobbered status file). Either way it's unusable.
return None
- if not raw:
+ return raw or None
+
+
+def _read_json_file(path: Path) -> Optional[dict[str, Any]]:
+ raw = _read_text_file(path)
+ if raw is None:
return None
try:
payload = json.loads(raw)
@@ -790,20 +668,16 @@ def _write_json_file(path: Path, payload: dict[str, Any]) -> None:
atomic_json_write(path, payload, indent=None, separators=(",", ":"))
-def _read_pid_record(pid_path: Optional[Path] = None) -> Optional[dict]:
- pid_path = pid_path or _get_pid_path()
- if not pid_path.exists():
- return None
+def _unlink_quietly(path: Path) -> None:
+ with contextlib.suppress(OSError):
+ path.unlink(missing_ok=True)
- try:
- raw = pid_path.read_text(encoding="utf-8").strip()
- except (OSError, UnicodeDecodeError):
- # File was deleted between exists() and read_text(), permission
- # flipped, or it holds non-UTF-8 / binary garbage.
- return None
- if not raw:
- return None
+def _read_pid_record(pid_path: Optional[Path] = None) -> Optional[dict]:
+ """PID record as a dict; legacy bare-integer files become ``{"pid": N}``."""
+ raw = _read_text_file(pid_path or _get_pid_path())
+ if raw is None:
+ return None
try:
payload = json.loads(raw)
except json.JSONDecodeError:
@@ -811,7 +685,6 @@ def _read_pid_record(pid_path: Optional[Path] = None) -> Optional[dict]:
return {"pid": int(raw)}
except ValueError:
return None
-
if isinstance(payload, int):
return {"pid": payload}
if isinstance(payload, dict):
@@ -832,6 +705,13 @@ def _pid_from_record(record: Optional[dict[str, Any]]) -> Optional[int]:
return None
+def _start_time_conflicts(record: dict[str, Any], pid: int) -> bool:
+ """PID-reuse guard: True only when BOTH start times are known and differ."""
+ recorded_start = record.get("start_time")
+ current_start = _get_process_start_time(pid)
+ return recorded_start is not None and current_start is not None and current_start != recorded_start
+
+
def _clear_running_pid_cache() -> None:
with _gateway_running_pid_cache_lock:
_gateway_running_pid_cache.clear()
@@ -860,14 +740,10 @@ def _running_pid_cache_signature(
def _cleanup_invalid_pid_path(pid_path: Path, *, cleanup_stale: bool) -> None:
- """Delete a stale gateway PID file (and its sibling lock metadata).
-
- Called from ``get_running_pid()`` after the runtime lock has already been
- confirmed inactive, so the on-disk metadata is known to belong to a dead
- process. Unlike ``remove_pid_file()`` (which defensively refuses to delete
- a PID file whose ``pid`` field differs from ``os.getpid()`` to protect
- ``--replace`` handoffs), this path force-unlinks both files so the next
- startup sees a clean slate.
+ """Force-unlink a stale PID file and its sibling lock file.
+
+ Called only after the runtime lock is confirmed inactive (dead owner), so
+ unlike ``remove_pid_file()`` it does not check the recorded pid.
"""
if not cleanup_stale:
return
@@ -906,39 +782,20 @@ def _try_acquire_file_lock(handle) -> bool:
def _pid_exists(pid: int) -> bool:
"""Cross-platform "is this PID alive" check that does NOT kill the target.
- CRITICAL on Windows: Python's ``os.kill(pid, 0)`` is NOT a no-op like it
- is on POSIX. CPython's Windows implementation
- (``Modules/posixmodule.c::os_kill_impl``) treats ``sig=0`` as
- ``CTRL_C_EVENT`` because the two values collide at the C level, and
- routes it through ``GenerateConsoleCtrlEvent(0, pid)`` — which sends
- a Ctrl+C to the entire console process group containing the target
- PID, not just the PID itself. Any caller that wanted to "check if
- this PID is alive" via ``os.kill(pid, 0)`` on Windows was silently
- killing that process (and often unrelated processes in the same
- console group). Long-standing Python quirk; see bpo-14484.
-
- Implementation: prefer :mod:`psutil` (hard dependency — the canonical
- cross-platform answer, maintained by Giampaolo Rodolà, uses
- ``OpenProcess + GetExitCodeProcess`` on Windows internally). Fall back
- to a hand-rolled ctypes ``OpenProcess`` / ``WaitForSingleObject`` pair
- on Windows + ``os.kill(pid, 0)`` on POSIX if psutil is somehow
- unavailable — e.g. stripped-down install or import error during the
- scaffold phase before ``psutil`` is pip-installed.
+ CRITICAL on Windows: ``os.kill(pid, 0)`` is NOT a no-op -- CPython maps
+ ``sig=0`` to ``CTRL_C_EVENT`` and ``GenerateConsoleCtrlEvent`` sends Ctrl+C
+ to the target's whole console group (bpo-14484). Prefer psutil; fall back
+ to ctypes ``OpenProcess``/``WaitForSingleObject`` on Windows and
+ ``os.kill(pid, 0)`` on POSIX when psutil is unavailable (stripped install /
+ scaffold phase).
"""
try:
import psutil # type: ignore
- # A zombie (defunct) process is still in the process table, so
- # ``psutil.pid_exists()`` returns True for it — but it is already
- # dead: SIGKILL has no effect and it cannot be a running gateway.
- # Treating a zombie as alive makes ``--replace`` wait for the old
- # PID to die (it never does, until its parent reaps it), then abort
- # with exit 1 — a silent crash loop under systemd ``Restart=always``,
- # which respawns the gateway before reaping the previous process
- # (issue #42126). Report zombies as dead so the takeover proceeds.
- # Best-effort: any failure to read status (partial/stub psutil,
- # access denied, transient race) falls through to the authoritative
- # ``pid_exists()`` below rather than raising.
+ # Zombies are still in the process table (pid_exists() -> True) but are
+ # dead: treating one as alive makes --replace wait forever under systemd
+ # Restart=always, which respawns before reaping. Report them as dead.
+ # Best-effort: status-read failures fall through to pid_exists().
try:
if psutil.Process(int(pid)).status() == psutil.STATUS_ZOMBIE:
return False
@@ -954,8 +811,7 @@ def _pid_exists(pid: int) -> bool:
try:
import ctypes
kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
- # Pin return types — default ctypes restype is c_int (signed),
- # which mangles WAIT_* DWORD return codes into negative numbers.
+ # Pin restypes: default c_int mangles WAIT_* DWORDs into negatives.
kernel32.OpenProcess.restype = ctypes.c_void_p
kernel32.WaitForSingleObject.restype = ctypes.c_uint
kernel32.GetLastError.restype = ctypes.c_uint
@@ -975,27 +831,21 @@ def _pid_exists(pid: int) -> bool:
return True # Exists but owned by another user/session
return False # Conservative default for unknown errors
try:
- wait_result = kernel32.WaitForSingleObject(handle, 0)
- # WAIT_TIMEOUT = still running; anything else (WAIT_OBJECT_0
- # via exit, WAIT_FAILED via handle issue) = treat as gone.
- return wait_result == WAIT_TIMEOUT
+ # WAIT_TIMEOUT = still running; anything else = gone.
+ return kernel32.WaitForSingleObject(handle, 0) == WAIT_TIMEOUT
finally:
kernel32.CloseHandle(handle)
except (OSError, AttributeError):
return False
else:
- # psutil missing (stripped install / scaffold phase). Catch the same
- # zombie case as the psutil path above (issue #42126): a zombie
- # answers os.kill(pid, 0) successfully, so without this check
- # ``--replace`` would wait on a dead PID and abort with exit 1.
+ # Same zombie case as the psutil path: a zombie answers os.kill(pid, 0).
try:
stat_fields = (
Path(f"/proc/{int(pid)}/stat").read_text(encoding="utf-8").split()
)
if len(stat_fields) > 2 and stat_fields[2] == "Z":
return False
- except FileNotFoundError:
- # No /proc (macOS/BSD) — fall back to ps state.
+ except FileNotFoundError: # No /proc (macOS/BSD): use ps state.
try:
r = subprocess.run(
["ps", "-o", "state=", "-p", str(int(pid))],
@@ -1015,12 +865,18 @@ def _pid_exists(pid: int) -> bool:
except ProcessLookupError:
return False
except PermissionError:
- # Process exists but we can't signal it — still alive.
- return True
+ return True # Exists but we can't signal it.
except OSError:
return False
+def _lock_is_held(handle) -> bool:
+ """Probe: True when another process holds the lock (a won probe is released)."""
+ if _try_acquire_file_lock(handle):
+ _release_file_lock(handle)
+ return False
+ return True
+
def _release_file_lock(handle) -> None:
try:
@@ -1034,11 +890,7 @@ def _release_file_lock(handle) -> None:
def acquire_gateway_runtime_lock() -> bool:
- """Claim the cross-process runtime lock for the gateway.
-
- Unlike the PID file, the lock is owned by the live process itself. If the
- process dies abruptly, the OS releases the lock automatically.
- """
+ """Claim the cross-process runtime lock; the OS releases it if the process dies."""
global _gateway_lock_handle
if _gateway_lock_handle is not None:
return True
@@ -1048,11 +900,8 @@ def acquire_gateway_runtime_lock() -> bool:
try:
handle = open(path, "a+", encoding="utf-8")
except PermissionError:
- # Stale root-owned lock file from a previous launchd Background
- # session that ran as root (same failure mode handled in
- # is_gateway_runtime_lock_active). The parent directory owner can
- # unlink files even when they don't own them, so remove the stale
- # lock and retry once with a fresh file.
+ # Stale root-owned lock from a launchd Background session that ran as
+ # root. The directory owner can unlink it; retry once with a fresh file.
try:
path.unlink()
except OSError:
@@ -1084,15 +933,11 @@ def release_gateway_runtime_lock() -> None:
def owns_gateway_runtime_lock() -> bool:
- """Return True when THIS process holds the gateway runtime lock.
-
- ``is_gateway_runtime_lock_active`` answers "does *anyone* hold the lock?"
- and deliberately returns True for the lock's own owner — a caller deciding
- whether to yield to a *fresh* gateway (e.g. the cron tick's stale-code
- gate) must distinguish self-ownership from another process's lock, and
- re-probing the lock file cannot: acquiring a probe handle on a lock this
- process already holds succeeds on POSIX. The in-process handle is the only
- discriminator, so expose it as a tiny predicate.
+ """True when THIS process holds the runtime lock.
+
+ ``is_gateway_runtime_lock_active`` answers "does anyone hold it?" and a
+ file re-probe cannot tell self-ownership apart (a probe on our own flock
+ succeeds on POSIX); the in-process handle is the only discriminator.
"""
return _gateway_lock_handle is not None
@@ -1110,18 +955,13 @@ def is_gateway_runtime_lock_active(lock_path: Optional[Path] = None) -> bool:
try:
handle = open(resolved_lock_path, "a+", encoding="utf-8")
except PermissionError:
- # Stale root-owned lock file from a previous launchd Background
- # session that ran as root. The parent directory owner can unlink
- # files even when they don't own them, so remove the stale lock
- # and report inactive — the new process will create a fresh one.
+ # Stale root-owned lock (launchd session that ran as root): the
+ # directory owner can unlink it; report inactive so a fresh one is made.
with contextlib.suppress(OSError):
resolved_lock_path.unlink()
return False
try:
- if _try_acquire_file_lock(handle):
- _release_file_lock(handle)
- return False
- return True
+ return _lock_is_held(handle)
finally:
with contextlib.suppress(OSError):
handle.close()
@@ -1146,10 +986,7 @@ def _is_gateway_runtime_lock_active_strict(lock_path: Path) -> bool:
except OSError as exc:
raise RuntimeError(f"gateway runtime lock is not inspectable: {exc}") from exc
try:
- if _try_acquire_file_lock(handle):
- _release_file_lock(handle)
- return False
- return True
+ return _lock_is_held(handle)
except OSError as exc:
raise RuntimeError(f"gateway runtime lock probe failed: {exc}") from exc
finally:
@@ -1158,26 +995,18 @@ def _is_gateway_runtime_lock_active_strict(lock_path: Path) -> bool:
def write_pid_file() -> None:
- """Write the current process PID and metadata to the gateway PID file.
-
- Uses atomic O_CREAT | O_EXCL creation so that concurrent --replace
- invocations race: exactly one process wins and the rest get
- FileExistsError.
- """
+ """Write this process's PID record via O_CREAT|O_EXCL (concurrent racers get FileExistsError)."""
path = _get_pid_path()
path.parent.mkdir(parents=True, exist_ok=True)
record = json.dumps(_build_pid_record())
- try:
- fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
- except FileExistsError:
- raise # Let caller decide: another gateway is racing us
+ # FileExistsError propagates: another gateway is racing us; caller decides.
+ fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(record)
_clear_running_pid_cache()
except Exception:
- with contextlib.suppress(OSError):
- path.unlink(missing_ok=True)
+ _unlink_quietly(path)
raise
@@ -1204,11 +1033,9 @@ def write_runtime_status(
current_record = _build_pid_record()
payload.setdefault("platforms", {})
if clear_profile_platforms:
- # Secondary-profile adapter health is stored in the process-level
- # status file as ``<profile>:<platform>``. A fresh gateway process
- # must not inherit those entries from the prior process: they would
- # otherwise keep /api/status degraded until every old adapter emitted
- # a new state (and removed profiles would remain degraded forever).
+ # Secondary-profile entries are keyed ``<profile>:<platform>``. A fresh
+ # process must not inherit them or /api/status stays degraded until
+ # every old adapter re-emits (removed profiles: forever).
platforms = payload["platforms"]
if not isinstance(platforms, dict):
platforms = {}
@@ -1217,28 +1044,22 @@ def write_runtime_status(
for key, value in platforms.items()
if not isinstance(key, str) or ":" not in key
}
- payload["kind"] = current_record["kind"]
- payload["pid"] = current_record["pid"]
- payload["argv"] = current_record["argv"]
- payload["start_time"] = current_record["start_time"]
+ for key in ("kind", "pid", "argv", "start_time"):
+ payload[key] = current_record[key]
payload["updated_at"] = _utc_now_iso()
- # Re-stamp code identity on every write: the file can outlive the process
- # that created it, and the top-level record must always describe the
- # CURRENT writer's code (per-process cached, so this is a dict copy).
+ # Re-stamp on every write: the file can outlive its creator and the top-level
+ # record must describe the CURRENT writer's code.
payload.update(_get_code_identity_fields())
- if gateway_state is not _UNSET:
- payload["gateway_state"] = gateway_state
- if exit_reason is not _UNSET:
- payload["exit_reason"] = exit_reason
+ for key, value in (("gateway_state", gateway_state), ("exit_reason", exit_reason)):
+ if value is not _UNSET:
+ payload[key] = value
if restart_requested is not _UNSET:
payload["restart_requested"] = bool(restart_requested)
if active_agents is not _UNSET:
payload["active_agents"] = parse_active_agents(active_agents)
if served_profiles is not _UNSET:
- # Profiles this gateway multiplexes (multi-profile mode). Absent/empty
- # for a single-profile gateway. Lets `hermes status` show per-profile
- # coverage without a second probe.
+ # Multiplexed profiles; absent/empty for a single-profile gateway.
payload["served_profiles"] = list(served_profiles or [])
if session_store is not _UNSET:
state = "unknown"
@@ -1250,33 +1071,26 @@ def write_runtime_status(
if platform is not _UNSET:
platform_payload = payload["platforms"].get(platform, {})
- if platform_state is not _UNSET:
- platform_payload["state"] = platform_state
- if error_code is not _UNSET:
- platform_payload["error_code"] = error_code
- if error_message is not _UNSET:
- platform_payload["error_message"] = error_message
+ for key, value in (
+ ("state", platform_state),
+ ("error_code", error_code),
+ ("error_message", error_message),
+ ):
+ if value is not _UNSET:
+ platform_payload[key] = value
if needs_attention is not _UNSET:
- # Long-lived reconnect-loop escalation (OOF-156): True once a
- # platform has been continuously failing/retrying past the
- # attention threshold. Retry never stops — this is a signal for
- # owners and fleet monitoring, not a circuit breaker. Cleared
- # (False) on successful reconnect.
+ # Reconnect-loop escalation past the attention threshold: a signal
+ # for owners/fleet monitoring, not a circuit breaker (retry never
+ # stops). Cleared on successful reconnect.
platform_payload["needs_attention"] = bool(needs_attention)
if retrying_since is not _UNSET:
- # ISO timestamp of when the platform entered its current
- # continuous retry episode; None clears it on reconnect.
+ # ISO start of the current retry episode; None clears it.
platform_payload["retrying_since"] = retrying_since
platform_payload["updated_at"] = _utc_now_iso()
- # Writer identity: which PROCESS wrote this entry. The top-level
- # pid/start_time are refreshed on every write, so they only identify
- # the file's most recent writer — per-entry provenance is what lets
- # a reader (the /api/status cross-profile aggregation) distinguish
- # "written by the current live process" from "preserved from a prior
- # process" with exact (pid, start_time) equality instead of clock
- # heuristics. start_time is the same PID-reuse fingerprint the
- # liveness checks use, so a recycled PID never masquerades as the
- # original writer.
+ # Per-entry writer provenance: top-level pid/start_time only identify
+ # the most recent writer, so /api/status distinguishes "written by the
+ # live process" from "preserved from a prior one" by exact
+ # (pid, start_time) equality rather than clock heuristics.
platform_payload["writer_pid"] = current_record["pid"]
platform_payload["writer_start_time"] = current_record["start_time"]
payload["platforms"][platform] = platform_payload
@@ -1290,21 +1104,13 @@ def write_runtime_status(
def read_runtime_status(path: Optional[Path] = None) -> Optional[dict[str, Any]]:
- """Read the persisted gateway runtime health/status information.
-
- ``path`` is optional so callers that need to inspect a *different*
- profile's state file (e.g. the dashboard enumerating every profile)
- can do so without mutating ``HERMES_HOME`` in-process. Defaults to
- the active profile's ``gateway_state.json``.
- """
+ """Read ``gateway_state.json``; ``path`` lets callers inspect another profile's file."""
return _read_json_file(path or _get_runtime_status_path())
-# Max age of a persisted ``gateway_state.json`` snapshot before its liveness
-# claim is treated as suspect. A healthy gateway rewrites the file (advancing
-# ``updated_at``) far more often than this; a record older than the TTL whose
-# PID is also dead almost certainly outlived an ungracefully-killed writer
-# (taskkill /F, OOM, power loss) that never ran its shutdown handler.
+# Max age of a ``gateway_state.json`` snapshot before its liveness claim is
+# suspect: an older record with a dead PID outlived an ungracefully-killed
+# writer (taskkill /F, OOM, power loss) that never ran its shutdown handler.
_RUNTIME_STATUS_STALE_TTL_S = 120
@@ -1312,73 +1118,42 @@ def runtime_status_is_stale(
record: Optional[dict[str, Any]],
ttl_s: int = _RUNTIME_STATUS_STALE_TTL_S,
) -> bool:
- """Return True when the runtime-status snapshot is older than ``ttl_s``.
-
- Delegates to the existing :func:`_marker_is_stale` on the record's
- ``updated_at`` timestamp. A missing or unparseable timestamp is treated as
- stale (the freshness signal is absent, so it cannot vouch for the record).
- """
+ """True when the snapshot's ``updated_at`` is older than ``ttl_s`` (missing/unparseable => stale)."""
if not isinstance(record, dict):
return True
return _marker_is_stale(record.get("updated_at") or "", ttl_s)
def runtime_status_pid_is_live(record: Optional[dict[str, Any]]) -> bool:
- """Return True when the PID recorded in the snapshot is still alive.
-
- Uses the existing no-kill :func:`_pid_exists` probe and the same
- ``start_time`` PID-reuse guard as :func:`get_runtime_status_running_pid`:
- when both the recorded and live start-times are known they must match, so a
- recycled PID (same number, different process) is not mistaken for the
- original. Degrades to ``False`` when the record has no usable PID.
- """
+ """True when the snapshot's PID is alive and passes the start-time PID-reuse guard."""
pid = _pid_from_record(record)
if pid is None or not _pid_exists(pid):
return False
- recorded_start = (record or {}).get("start_time")
- current_start = _get_process_start_time(pid)
- return not (recorded_start is not None and current_start is not None and current_start != recorded_start)
+ return not _start_time_conflicts(record, pid)
def parse_active_agents(raw: Any) -> int:
- """Coerce a persisted ``active_agents`` value to a clamped non-negative int.
-
- The shared coercion for the in-flight gateway-turn count. Used on the WRITE
- side (``write_runtime_status``) and by both HTTP read surfaces
- (``/api/status`` and ``/health/detailed``) so the count is clamped to a
- single contract — never negative, never raising on a manually-edited or
- otherwise non-numeric value (degrades to ``0``).
- """
+ """Coerce ``active_agents`` to a non-negative int (shared by the writer and both HTTP readers)."""
try:
return max(0, int(raw))
except (TypeError, ValueError):
return 0
-# States in which the gateway is alive and could be asked to drain. Anything
-# else (draining already, stopping, stopped, startup_failed, None) is NOT a
-# valid begin-drain target.
+# Only a live ``running`` gateway is a valid begin-drain target.
_DRAINABLE_GATEWAY_STATES = frozenset({"running"})
def derive_gateway_busy(
*, gateway_running: bool, gateway_state: Any, active_agents: Any
) -> bool:
- """Whether the gateway is actively processing in-flight turns.
+ """Busy iff live, in ``running`` state, and ``active_agents > 0`` (the contract NAS gates on).
- The contract NAS gates lifecycle actions on. Busy iff the gateway is live
- (``gateway_running``), in the ``running`` state, AND at least one agent is
- mid-turn (``active_agents > 0``). Degrades to ``False`` whenever liveness
- is unknown, the state is anything but ``running``, or the count is
- absent/unparseable — i.e. a down or file-absent gateway reads "not busy",
- never a spurious "busy".
-
- NOTE: liveness keys off ``gateway_running`` (a live PID / health probe),
- NEVER ``updated_at`` — a healthy idle gateway never advances that timestamp.
+ Degrades to False on unknown liveness / other state / unparseable count.
+ Liveness keys off ``gateway_running``, NEVER ``updated_at`` -- a healthy
+ idle gateway never advances that timestamp.
"""
- if not gateway_running:
- return False
- if gateway_state not in _DRAINABLE_GATEWAY_STATES:
+ if not gateway_running or gateway_state not in _DRAINABLE_GATEWAY_STATES:
return False
try:
return int(active_agents) > 0
@@ -1387,14 +1162,7 @@ def derive_gateway_busy(
def derive_gateway_drainable(*, gateway_running: bool, gateway_state: Any) -> bool:
- """Whether the gateway can accept a begin-drain request right now.
-
- True iff the gateway is live and in the ``running`` state — i.e. not already
- draining/stopping/stopped and not in a failed-start state. This is
- independent of ``active_agents``: an idle running gateway is drainable (the
- drain just completes immediately). Degrades to ``False`` for a down or
- non-running gateway.
- """
+ """Drainable iff live and ``running`` (independent of ``active_agents``; an idle drain completes at once)."""
return bool(gateway_running) and gateway_state in _DRAINABLE_GATEWAY_STATES
@@ -1402,14 +1170,10 @@ def derive_gateway_drainable(*, gateway_running: bool, gateway_state: Any) -> bo
class GatewayLiveness:
"""Resolved gateway liveness for one dashboard surface.
- ``source`` records which rung of the ladder answered, purely for logging
- and tests — never branch product behavior on it.
-
- ``probe_error`` is True when a rung raised instead of answering. Callers
- that must distinguish "the gateway is down" from "we could not tell"
- need it: the dashboard renders a down badge either way, but the kanban
- dispatcher warning deliberately fails OPEN on an unreadable probe so it
- never cries wolf at a user whose gateway is fine.
+ ``source``: which ladder rung answered (logging/tests only -- never branch
+ product behavior on it). ``probe_error``: a rung raised instead of
+ answering; lets fail-open callers (kanban dispatcher warning) tell "down"
+ from "could not tell".
"""
running: bool
@@ -1431,38 +1195,16 @@ def resolve_gateway_liveness(
) -> GatewayLiveness:
"""Single source of truth for "is the gateway up?" across dashboard surfaces.
- Before this existed, ``/api/status`` and ``/api/messaging/platforms``
- each open-coded their own ladder and disagreed on the same page load —
- the sidebar read "running" while the Channels page rendered "The gateway
- is not running." Three deployments hit it: a cross-container gateway
- (only ``/api/status`` ran the HTTP health probe), a profile-scoped
- dashboard (only ``/api/status`` passed the profile's paths, so messaging
- borrowed another profile's runtime state — issue #71211), and a
- launch-service-managed gateway with no PID file (only some callers used
- the runtime-status fallback).
-
- The ladder, most to least authoritative:
-
- 1. **PID file + runtime lock** — scoped to ``profile_dir`` when given.
- Cached by default (``use_cache``); high-frequency polling must not
- churn file descriptors re-flocking ``gateway.lock`` on every request.
- 2. **HTTP health probe** — supplied by the caller (the dashboard owns the
- deprecated ``GATEWAY_HEALTH_URL`` config). Covers the gateway running
- in another container where no local PID is visible.
- 3. **Runtime status PID** — validated against the live process table with
- ``expected_home`` so a recycled PID belonging to a *different*
- profile's gateway is never reported as this one's.
-
- Rung 3 only ever runs against a LOCAL state record: the probe body's PID
- belongs to another host, and ``os.kill``-ing a remote PID is both wrong
- and trips the test live-system guard. Pass ``runtime`` when the caller
- has already read the state file so it isn't read twice per request.
-
- ``pid_probe`` / ``runtime_reader`` / ``runtime_pid_probe`` let a caller
- inject its own module-level references to these helpers. The dashboard
- passes its ``hermes_cli.web_server`` bindings so the long-standing
- monkeypatch seam in the test-suite keeps working; production callers
- leave them ``None`` and get this module's implementations.
+ Ladder, most to least authoritative:
+ 1. PID file + runtime lock (scoped to ``profile_dir``; cached by default so
+ high-frequency polling does not re-flock ``gateway.lock`` per request).
+ 2. Caller-supplied HTTP health probe (covers a gateway in another container).
+ 3. Runtime status PID, validated against the live process table with
+ ``expected_home`` so a recycled PID of a different profile never counts.
+ Rung 3 only runs against the LOCAL state record -- the probe body's PID
+ belongs to another host. Pass ``runtime`` if the state file is already read.
+ ``pid_probe``/``runtime_reader``/``runtime_pid_probe`` let the dashboard
+ inject its ``hermes_cli.web_server`` bindings (test monkeypatch seam).
"""
_pid_probe = pid_probe or (
get_running_pid_cached if use_cache else get_running_pid
@@ -1473,14 +1215,11 @@ def resolve_gateway_liveness(
pid_path = (profile_dir / "gateway.pid") if profile_dir is not None else None
probe_error = False
try:
- # Plain zero-arg call when unscoped: several callers monkeypatch these
- # probes with zero-arg lambdas, and /api/status's cache signature is
- # keyed on the exact call shape.
+ # Zero-arg call when unscoped: callers monkeypatch with zero-arg lambdas
+ # and /api/status's cache signature is keyed on the call shape.
pid = _pid_probe(pid_path) if pid_path is not None else _pid_probe()
except Exception:
- # A probe failure (permissions, exotic /proc, Windows quirks) must
- # degrade to the next rung, never 500 a status endpoint. Recorded in
- # probe_error so fail-open callers can tell "down" from "unknown".
+ # Degrade to the next rung; never 500 a status endpoint.
pid = None
probe_error = True
if pid is not None:
@@ -1544,20 +1283,13 @@ def get_runtime_status_running_pid(
*,
expected_home: Optional[Path] = None,
) -> Optional[int]:
- """Return a live gateway PID from the runtime status record, if valid.
-
- ``get_running_pid()`` is the primary liveness source because it verifies the
- runtime lock and PID file. Launch-service managers can still leave us with
- a live process and a fresh ``gateway_state.json`` but no ``gateway.pid``; use
- this as a conservative fallback by checking both the persisted state and the
- OS process identity.
-
- ``expected_home`` scopes the OS-identity check to a specific profile's
- HERMES_HOME. Pass it when validating *another* profile's state file (the
- dashboard enumerating every profile): a stale record whose PID the OS has
- recycled onto a different profile's live gateway must not be reported
- running for the dead profile. Omit it (the default) for the active
- profile, where any live gateway command line is acceptable.
+ """Live gateway PID from the runtime status record, or None.
+
+ Conservative fallback to ``get_running_pid()`` for launch-service-managed
+ gateways that have a fresh ``gateway_state.json`` but no ``gateway.pid``.
+ ``expected_home`` scopes the OS-identity check to another profile's home
+ (dashboard enumeration) so a PID recycled onto a different profile's
+ gateway is not reported running for the dead one.
"""
payload = runtime if runtime is not None else read_runtime_status()
if not isinstance(payload, dict):
@@ -1566,22 +1298,11 @@ def get_runtime_status_running_pid(
return None
pid = _pid_from_record(payload)
- if pid is None or not _pid_exists(pid):
- return None
-
- recorded_start = payload.get("start_time")
- current_start = _get_process_start_time(pid)
- if (
- recorded_start is not None
- and current_start is not None
- and current_start != recorded_start
- ):
+ if pid is None or not _pid_exists(pid) or _start_time_conflicts(payload, pid):
return None
- # When no explicit expected_home is given (active profile context),
- # verify the persisted record's hermes_home matches the current process.
- # This prevents the default-profile gateway from assuming another
- # profile's identity via a stale runtime status record (#74872).
+ # Active-profile context: the record's hermes_home must match this process
+ # so a stale record cannot lend another profile's identity.
if expected_home is None and not _pid_record_belongs_to_current_profile(payload):
return None
@@ -1591,24 +1312,18 @@ def get_runtime_status_running_pid(
def remove_pid_file() -> None:
- """Remove the gateway PID file, but only if it belongs to this process.
+ """Remove the PID file only if it belongs to this process.
- During --replace handoffs, the old process's atexit handler can fire AFTER
- the new process has written its own PID file. Blindly removing the file
- would delete the new process's record, leaving the gateway running with no
- PID file (invisible to ``get_running_pid()``).
+ During --replace the old process's atexit can fire AFTER the new process
+ wrote its own record; blind removal would leave the gateway invisible.
"""
try:
path = _get_pid_path()
record = _read_json_file(path)
if record is not None:
- try:
- file_pid = int(record["pid"])
- except (KeyError, TypeError, ValueError):
- file_pid = None
+ file_pid = _pid_from_record(record)
if file_pid is not None and file_pid != os.getpid():
- # PID file belongs to a different process — leave it alone.
- return
+ return # Belongs to a different process — leave it alone.
path.unlink(missing_ok=True)
_clear_running_pid_cache()
except Exception:
@@ -1616,11 +1331,7 @@ def remove_pid_file() -> None:
def acquire_scoped_lock(scope: str, identity: str, metadata: Optional[dict[str, Any]] = None) -> tuple[bool, Optional[dict[str, Any]]]:
- """Acquire a machine-local lock keyed by scope + identity.
-
- Used to prevent multiple local gateways from using the same external identity
- at once (e.g. the same Telegram bot token across different HERMES_HOME dirs).
- """
+ """Acquire a machine-local lock keyed by scope + identity (e.g. one Telegram token across homes)."""
lock_path = _get_scope_lock_path(scope, identity)
lock_path.parent.mkdir(parents=True, exist_ok=True)
record = {
@@ -1630,38 +1341,24 @@ def acquire_scoped_lock(scope: str, identity: str, metadata: Optional[dict[str,
"metadata": metadata or {},
"updated_at": _utc_now_iso(),
}
- # Human-readable profile label for cross-profile conflict diagnostics
- # (OOF-3): "Telegram bot token already in use (PID 559)" gives an
- # operator no way to tell WHICH profile owns the credential. Stamped
- # only on scoped-lock records (they're machine-global; PID/runtime
- # status files are per-home and don't need it). Omitted when no label
- # is inferable; readers fall back to deriving it from hermes_home.
+ # Profile label for cross-profile conflict diagnostics ("token already in
+ # use (PID 559)" alone does not say WHICH profile). Omitted when not
+ # inferable; readers fall back to hermes_home.
profile = _profile_label_for_home(_get_process_hermes_home())
if profile:
record["profile"] = profile
existing = _read_json_file(lock_path)
if existing is None and lock_path.exists():
- # Lock file exists but is empty or contains invalid JSON — treat as
- # stale. This happens when a previous process was killed between
- # O_CREAT|O_EXCL and the subsequent json.dump() (e.g. DNS failure
- # during rapid Slack reconnect retries).
- with contextlib.suppress(OSError):
- lock_path.unlink(missing_ok=True)
+ # Empty/invalid JSON: previous process died between O_EXCL create and
+ # json.dump(). Treat as stale.
+ _unlink_quietly(lock_path)
if existing:
- try:
- existing_pid = int(existing["pid"])
- except (KeyError, TypeError, ValueError):
- existing_pid = None
-
- # Same live PID as this process: always self-reacquire.
- # ``start_time`` is a PID-reuse guard for *other* PIDs; it cannot
- # distinguish two processes that share the caller's own PID (impossible
- # while we are alive). Requiring start_time equality here falsely
- # rejects reconnects when the on-disk record has ``start_time: null``
- # (older writers / psutil failure at first write) while the freshly
- # built record has a real value — the gateway then reports itself as
- # the foreign squatter of its own token (#81468).
+ existing_pid = _pid_from_record(existing)
+
+ # Our own PID: always self-reacquire. start_time guards reuse of OTHER
+ # PIDs; requiring equality here rejects reconnects when the on-disk
+ # record has start_time null (older writers / psutil failure).
if existing_pid == os.getpid():
_write_json_file(lock_path, record)
return True, existing
@@ -1678,73 +1375,49 @@ def acquire_scoped_lock(scope: str, identity: str, metadata: Optional[dict[str,
and current_start != existing.get("start_time")
):
stale = True
- # When start_time comparison is unavailable on either side
- # (macOS / Windows have no /proc, so the lock record's
- # start_time may be None; psutil may also fail to read
- # create_time for recycled PIDs), fall back to checking the
- # live process command line. When cmdline is also unreadable
- # (Windows has no ps), consult the lock record's own argv —
- # the gateway writes it at startup and it's the only identity
- # signal on platforms without ps. Both oracles must indicate
- # "not a gateway" to mark stale.
- if (
- not stale
- and (existing.get("start_time") is None or current_start is None)
- and not _looks_like_gateway_process(existing_pid)
- ):
- live_cmdline = _read_process_cmdline(existing_pid)
- if live_cmdline is not None or not _record_looks_like_gateway(existing):
- stale = True
- # Secondary defence against boot-time PID+start_time collisions:
- # systemd spawns core services deterministically, so an unrelated
- # process (e.g. cron) can land on the exact same PID and jiffy
- # count as a previous gateway. If both start_times are known and
- # match but the live process is not a gateway, and we can confirm
- # that by reading its cmdline, the lock is stale.
+ # Live process is not a gateway: stale when its cmdline is
+ # readable and says so (also catches boot-time PID+start_time
+ # collisions -- systemd spawns deterministically, so an unrelated
+ # service can land on the same PID and jiffy count). When the
+ # cmdline is unreadable (Windows has no ps) AND start_time is
+ # unavailable on either side (no /proc, psutil failure), consult
+ # the lock record's own argv -- the only identity signal there.
if (
not stale
- and existing.get("start_time") is not None
- and current_start is not None
and not _looks_like_gateway_process(existing_pid)
+ and (
+ _read_process_cmdline(existing_pid) is not None
+ or (
+ (existing.get("start_time") is None or current_start is None)
+ and not _record_looks_like_gateway(existing)
+ )
+ )
):
- live_cmdline = _read_process_cmdline(existing_pid)
- if live_cmdline is not None:
- stale = True
- # Check if process is stopped (Ctrl+Z / SIGTSTP) — stopped
- # processes still appear alive to _pid_exists but are not
- # actually running. Treat them as stale so --replace works.
+ stale = True
+ # Stopped processes (Ctrl+Z / SIGTSTP) look alive to _pid_exists
+ # but are not running; treat as stale so --replace works.
if not stale:
try:
_proc_status = Path(f"/proc/{existing_pid}/status")
if _proc_status.exists():
for _line in _proc_status.read_text(encoding="utf-8").splitlines():
if _line.startswith("State:"):
- _state = _line.split()[1]
- if _state in {"T", "t"}: # stopped or tracing stop
+ if _line.split()[1] in {"T", "t"}: # stopped / tracing stop
stale = True
break
except (OSError, PermissionError):
pass
if stale:
- # Remove the stale lock ATOMICALLY by renaming it to a tombstone
- # instead of unlinking. With unlink()+O_EXCL, two racing starters
- # could both observe "removed" (the second unlink() silently
- # deleting the first racer's freshly-created lock) and both win.
- # os.replace() is atomic: exactly one racer claims the stale
- # file; the loser gets FileNotFoundError and falls through to
- # the O_EXCL create below, where at most one process succeeds.
+ # Rename to a tombstone instead of unlink(): with unlink()+O_EXCL two
+ # racing starters could both win (the second unlink deleting the
+ # first racer's fresh lock). os.replace() lets exactly one claim it.
tombstone = lock_path.with_name(lock_path.name + ".stale")
try:
os.replace(lock_path, tombstone)
- except FileNotFoundError:
- # Another racer already claimed the stale lock (and may have
- # created a fresh one) — let O_EXCL below decide the winner.
- pass
except OSError:
- pass
+ pass # Another racer claimed it -- O_EXCL below decides the winner.
else:
- with contextlib.suppress(OSError):
- tombstone.unlink(missing_ok=True)
+ _unlink_quietly(tombstone)
else:
return False, existing
@@ -1756,8 +1429,7 @@ def acquire_scoped_lock(scope: str, identity: str, metadata: Optional[dict[str,
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(record, handle)
except Exception:
- with contextlib.suppress(OSError):
- lock_path.unlink(missing_ok=True)
+ _unlink_quietly(lock_path)
raise
return True, None
@@ -1770,12 +1442,9 @@ def release_scoped_lock(scope: str, identity: str) -> None:
return
if existing.get("pid") != os.getpid():
return
- # Same PID as the live process means we own the lock. Do not require
- # start_time equality: on-disk null vs a live fingerprint (macOS/psutil
- # timing) would otherwise leave the lock stuck across Discord/Telegram
- # reconnects (#81468). start_time only guards PID reuse for *other* PIDs.
- with contextlib.suppress(OSError):
- lock_path.unlink(missing_ok=True)
+ # Own PID => we own the lock. No start_time equality: on-disk null vs a live
+ # fingerprint would leave the lock stuck across reconnects.
+ _unlink_quietly(lock_path)
def release_all_scoped_locks(
@@ -1783,18 +1452,10 @@ def release_all_scoped_locks(
owner_pid: Optional[int] = None,
owner_start_time: Optional[int] = None,
) -> int:
- """Remove scoped lock files in the lock directory.
-
- Called during --replace to clean up stale locks left by stopped/killed
- gateway processes that did not release their locks gracefully. When an
- ``owner_pid`` is provided, only lock records belonging to that gateway
- process are removed. ``owner_start_time`` further narrows the match to
- protect against PID reuse.
+ """Remove scoped lock files (--replace cleanup); returns the count removed.
- When no owner is provided, preserves the legacy behavior and removes every
- scoped lock file in the directory.
-
- Returns the number of lock files removed.
+ With ``owner_pid`` only that gateway's records go (``owner_start_time``
+ narrows against PID reuse); with no owner every lock file is removed.
"""
lock_dir = _get_lock_dir()
removed = 0
@@ -1804,11 +1465,7 @@ def release_all_scoped_locks(
record = _read_json_file(lock_file)
if not isinstance(record, dict):
continue
- try:
- record_pid = int(record.get("pid"))
- except (TypeError, ValueError):
- continue
- if record_pid != owner_pid:
+ if _pid_from_record(record) != owner_pid:
continue
if (
owner_start_time is not None
@@ -1825,22 +1482,13 @@ def release_all_scoped_locks(
# ── --replace takeover marker ─────────────────────────────────────────
#
-# When a new gateway starts with ``--replace``, it SIGTERMs the existing
-# gateway so it can take over the bot token. PR #5646 made SIGTERM exit
-# the gateway with code 1 so ``Restart=on-failure`` can revive it after
-# unexpected kills — but that also means a --replace takeover target
-# exits 1, which tricks systemd into reviving it 30 seconds later,
-# starting a flap loop against the replacer when both services are
-# enabled in the user's systemd (e.g. ``hermes.service`` + ``hermes-
-# gateway.service``).
-#
-# The takeover marker breaks the loop: the replacer writes a short-lived
-# file naming the target PID + start_time BEFORE sending SIGTERM.
-# The target's shutdown handler reads the marker and, if it names
-# this process, treats the SIGTERM as a planned takeover and exits 0.
-# The marker is unlinked after the target has consumed it, so a stale
-# marker left by a crashed replacer can grief at most one future
-# shutdown on the same PID — and only within _TAKEOVER_MARKER_TTL_S.
+# SIGTERM exits the gateway with code 1 so Restart=on-failure revives it after
+# unexpected kills -- which would also revive a --replace target and start a
+# flap loop against the replacer. The replacer therefore writes a short-lived
+# marker naming the target PID + start_time BEFORE SIGTERM; the target's
+# shutdown handler treats a matching marker as a planned takeover and exits 0.
+# The marker is unlinked once consumed, so a stale one can grief at most one
+# future shutdown on the same PID, within _TAKEOVER_MARKER_TTL_S.
_TAKEOVER_MARKER_FILENAME = ".gateway-takeover.json"
_TAKEOVER_MARKER_TTL_S = 60 # Marker older than this is treated as stale
@@ -1849,60 +1497,75 @@ _PLANNED_STOP_MARKER_TTL_S = 60
def _get_takeover_marker_path(hermes_home: Optional[Path] = None) -> Path:
- """Return the path to the --replace takeover marker file.
-
- ``hermes_home`` is supplied only for a verified cross-home handoff. The
- target process always consumes the marker from its own process-level home.
- """
+ """Takeover marker path; ``hermes_home`` is given only for a verified cross-home handoff."""
home = hermes_home or _get_process_hermes_home()
return _canonical_hermes_home(home) / _TAKEOVER_MARKER_FILENAME
def _get_planned_stop_marker_path() -> Path:
"""Return the path to the intentional gateway stop marker file."""
- home = _get_process_hermes_home()
- return home / _PLANNED_STOP_MARKER_FILENAME
+ return _get_process_hermes_home() / _PLANNED_STOP_MARKER_FILENAME
def _marker_is_stale(written_at: str, ttl_s: int) -> bool:
try:
- written_dt = datetime.fromisoformat(written_at)
- age = (datetime.now(timezone.utc) - written_dt).total_seconds()
- return age > ttl_s
+ return (datetime.now(timezone.utc) - datetime.fromisoformat(written_at)).total_seconds() > ttl_s
except (TypeError, ValueError):
return True
-def _consume_pid_marker_for_self(
- path: Path,
- *,
- pid_field: str,
- start_time_field: str,
- ttl_s: int,
-) -> bool:
+def _read_live_pid_marker(path: Path, ttl_s: int) -> Optional[tuple[dict[str, Any], int, Any]]:
+ """Return ``(record, target_pid, target_start_time)`` for a usable marker.
+
+ Malformed or expired markers can never match anyone, so they are unlinked
+ here (a stale file left by a previous instance must not wedge a new one).
+ """
record = _read_json_file(path)
if not record:
- return False
-
+ return None
try:
- target_pid = int(record[pid_field])
- target_start_time = record.get(start_time_field)
+ target_pid = int(record["target_pid"])
+ target_start_time = record.get("target_start_time")
written_at = record.get("written_at") or ""
except (KeyError, TypeError, ValueError):
- with contextlib.suppress(OSError):
- path.unlink(missing_ok=True)
+ _unlink_quietly(path)
+ return None
+ if _marker_is_stale(written_at, ttl_s):
+ _unlink_quietly(path)
+ return None
+ return record, target_pid, target_start_time
+
+
+def _pid_marker_names_self(target_pid: int, target_start_time: Any) -> bool:
+ """PID match with an optional start-time PID-reuse guard.
+
+ ``_get_process_start_time`` returns None on platforms without /proc (macOS,
+ native Windows -- where the planned-stop watcher matters most). Requiring a
+ non-None match there would make every consume return False and misclassify
+ a legitimate ``hermes gateway stop`` as an unexpected exit (revived by the
+ service manager). So: when both start times are known they must match; when
+ either is unknown, PID equality alone decides (bounded by the marker TTL).
+ Shared by the watcher's non-destructive probe and the authoritative consume
+ so they agree on every platform.
+ """
+ if target_pid != os.getpid():
return False
+ our_start_time = _get_process_start_time(target_pid)
+ if target_start_time is not None and our_start_time is not None:
+ return target_start_time == our_start_time
+ return True
- if _marker_is_stale(written_at, ttl_s):
- with contextlib.suppress(OSError):
- path.unlink(missing_ok=True)
+
+def _consume_pid_marker_for_self(path: Path, *, ttl_s: int) -> bool:
+ parsed = _read_live_pid_marker(path, ttl_s)
+ if parsed is None:
return False
+ record, target_pid, target_start_time = parsed
- # Cross-profile guard (#29092): new markers explicitly name the verified
- # TARGET home. That permits a deliberate cross-HERMES_HOME --replace while
- # ensuring a marker accidentally written into another profile's directory
- # is ignored. Legacy markers have no target field, so retain the original
- # same-replacer-home rule for backwards compatibility.
+ # Cross-profile guard: new markers name the verified TARGET home, which
+ # permits a deliberate cross-HERMES_HOME --replace while ignoring a marker
+ # accidentally written into another profile's directory. Legacy markers
+ # have no target field, so keep the original same-replacer-home rule.
our_home = _get_process_hermes_home()
target_home = record.get("target_hermes_home")
if target_home is not None:
@@ -1917,30 +1580,8 @@ def _consume_pid_marker_for_self(
):
return False
- our_pid = os.getpid()
- our_start_time = _get_process_start_time(our_pid)
- # Start-time is a PID-reuse guard. It is only meaningful when both
- # sides actually have it: ``_get_process_start_time`` returns None on
- # platforms without ``/proc`` (macOS, native Windows — the very
- # platform the planned-stop watcher exists for). Requiring a non-None
- # match there would make every consume return False, so a legitimate
- # ``hermes gateway stop`` on Windows would be misclassified as an
- # unexpected ``UNKNOWN`` exit (exit 1) and revived by the service
- # manager. So: when both start_times are known they must match; when
- # either is unknown, fall back to PID equality alone (bounded by the
- # marker's short TTL). This mirrors ``planned_stop_marker_targets_self``
- # so the watcher's non-destructive probe and this authoritative
- # consume agree on every platform (issue #34597).
- if target_pid != our_pid:
- matches = False
- elif target_start_time is not None and our_start_time is not None:
- matches = target_start_time == our_start_time
- else:
- matches = True
-
- with contextlib.suppress(OSError):
- path.unlink(missing_ok=True)
-
+ matches = _pid_marker_names_self(target_pid, target_start_time)
+ _unlink_quietly(path)
return matches
@@ -1950,21 +1591,13 @@ def write_takeover_marker(
target_home: Optional[Path] = None,
target_start_time: Any = _UNSET,
) -> bool:
- """Record that ``target_pid`` is being replaced by the current process.
-
- Captures the target's ``start_time`` so that PID reuse after the
- target exits cannot later match the marker. Also records the
- replacer's PID and a UTC timestamp for TTL-based staleness checks.
+ """Record that ``target_pid`` is being replaced by this process; True on success.
- A verified scoped-lock handoff supplies ``target_home`` and the already
- validated ``target_start_time`` so the marker is written into the target
- gateway's HERMES_HOME rather than the replacer's. Same-home callers omit
- both arguments and preserve the historical behavior.
-
- Returns True on successful write, False on any failure. Historical
- same-home callers may treat the marker as best effort. Cross-home callers
- must fail closed because the target's supervisor could otherwise revive it
- without recognizing the handoff.
+ Captures the target's ``start_time`` (PID-reuse guard) and a timestamp for
+ TTL checks. A verified cross-home handoff passes ``target_home`` and the
+ validated ``target_start_time`` so the marker lands in the target's home;
+ such callers must fail closed on False (the target's supervisor could
+ otherwise revive it).
"""
try:
marker_home = _canonical_hermes_home(
@@ -1989,50 +1622,32 @@ def write_takeover_marker(
def consume_takeover_marker_for_self() -> bool:
- """Check & unlink the takeover marker if it names the current process.
-
- Returns True only when a valid (non-stale) marker names this PID +
- start_time. A returning True indicates the current SIGTERM is a
- planned --replace takeover; the caller should exit 0 instead of
- signalling ``_signal_initiated_shutdown``.
+ """Consume the takeover marker; True means this SIGTERM is a planned takeover (exit 0).
- Always unlinks the marker on match (and on detected staleness) so
- subsequent unrelated signals don't re-trigger.
+ Always unlinks on match or staleness so later unrelated signals don't re-trigger.
"""
- return _consume_pid_marker_for_self(
- _get_takeover_marker_path(),
- pid_field="target_pid",
- start_time_field="target_start_time",
- ttl_s=_TAKEOVER_MARKER_TTL_S,
- )
+ return _consume_pid_marker_for_self(_get_takeover_marker_path(), ttl_s=_TAKEOVER_MARKER_TTL_S)
def clear_takeover_marker(target_home: Optional[Path] = None) -> None:
"""Remove the takeover marker unconditionally. Safe to call repeatedly."""
- with contextlib.suppress(OSError):
- _get_takeover_marker_path(target_home).unlink(missing_ok=True)
+ _unlink_quietly(_get_takeover_marker_path(target_home))
def _validated_scoped_lock_gateway_owner(
record: dict[str, Any],
) -> Optional[tuple[int, int, Path]]:
- """Resolve a live scoped-lock owner to a verified gateway identity.
-
- A machine-global scoped-lock file is only a claim; it is not sufficient
- authority to terminate a process or choose a marker destination. Require
- the lock record, the target HERMES_HOME's gateway PID record, and the live
- OS process to agree on PID, start-time fingerprint, gateway identity, and
- process home. Missing legacy metadata fails closed and leaves the normal
- retryable lock-conflict path in charge.
+ """Resolve a live scoped-lock owner to a verified ``(pid, start_time, home)``.
+
+ A lock file is only a claim: the record, the target home's PID record, and
+ the live process must agree on PID, start-time, gateway identity, and home.
+ Missing legacy metadata fails closed (normal retryable conflict path).
"""
if not isinstance(record, dict) or not _record_looks_like_gateway(record):
return None
- try:
- owner_pid = int(record["pid"])
- except (KeyError, TypeError, ValueError):
- return None
- if owner_pid <= 0 or owner_pid == os.getpid():
+ owner_pid = _pid_from_record(record)
+ if owner_pid is None or owner_pid <= 0 or owner_pid == os.getpid():
return None
owner_start_time = record.get("start_time")
@@ -2061,11 +1676,7 @@ def _validated_scoped_lock_gateway_owner(
pid_record = _read_json_file(target_home / "gateway.pid")
if not isinstance(pid_record, dict) or not _record_looks_like_gateway(pid_record):
return None
- try:
- pid_record_pid = int(pid_record["pid"])
- except (KeyError, TypeError, ValueError):
- return None
- if pid_record_pid != owner_pid or pid_record.get("start_time") != owner_start_time:
+ if _pid_from_record(pid_record) != owner_pid or pid_record.get("start_time") != owner_start_time:
return None
pid_record_home = pid_record.get("hermes_home")
@@ -2085,9 +1696,7 @@ def _scoped_lock_owner_state(owner_pid: int, owner_start_time: int) -> str:
if live_start_time is None:
return "unknown"
if live_start_time != owner_start_time:
- # The original owner exited and the OS recycled its PID. Never signal
- # the replacement process.
- return "exited"
+ return "exited" # PID recycled; never signal the replacement process.
return "same"
@@ -2110,14 +1719,10 @@ def _wait_for_scoped_lock_owner_exit(
def _snapshot_gateway_children(pid: int) -> list:
- """Best-effort snapshot of ``pid``'s live descendants (POSIX only).
-
- Must be taken while the old gateway is still alive: once the parent
- exits, its children are reparented (to init or a subreaper) and can no
- longer be discovered by a parent walk. Returns ``[]`` on Windows —
- ``terminate_pid(force=True)`` there already tree-kills via
- ``taskkill /T`` — and on any error (missing psutil, process already
- gone, access denied). Never raises.
+ """Best-effort snapshot of ``pid``'s live descendants (POSIX only; never raises).
+
+ Take it while the parent is alive -- once it exits the children are
+ reparented and undiscoverable. ``[]`` on Windows (taskkill /T tree-kills).
"""
if _IS_WINDOWS:
return []
@@ -2133,22 +1738,13 @@ def _snapshot_gateway_children(pid: int) -> list:
def reap_gateway_children(children: list, *, parent_pid: int, timeout: float = 5.0) -> int:
- """Best-effort reap of a dead gateway's orphaned descendants (POSIX).
-
- Mirrors the Windows ``taskkill /T`` tree-kill for the POSIX ``--replace``
- paths: adapter subprocesses that survive their parent keep holding scoped
- token locks and block the replacement gateway. Call only AFTER the main
- gateway PID is confirmed dead, with a ``children`` snapshot taken via
- :func:`_snapshot_gateway_children` while it was still alive.
-
- Safety properties:
- - ``psutil.Process.is_running()`` is identity-aware (PID + create time),
- so a recycled child PID is never signalled.
- - A child whose current ppid still equals ``parent_pid`` is skipped: that
- means the parent is in fact alive (caller raced or was mocked) and the
- child is not an orphan.
- - SIGTERM first, bounded wait, SIGKILL only for survivors.
- - Never raises; returns the number of children signalled.
+ """Best-effort reap of a dead gateway's orphaned descendants (POSIX); returns count signalled.
+
+ Surviving adapter subprocesses keep holding token locks. Call only AFTER the
+ parent is confirmed dead with a snapshot from :func:`_snapshot_gateway_children`.
+ ``is_running()`` is identity-aware so a recycled child PID is never
+ signalled; a child whose ppid still equals ``parent_pid`` is skipped (parent
+ alive => not an orphan). SIGTERM, bounded wait, SIGKILL survivors. Never raises.
"""
if _IS_WINDOWS or not children:
return 0
@@ -2164,7 +1760,6 @@ def reap_gateway_children(children: list, *, parent_pid: int, timeout: float = 5
if child.status() == psutil.STATUS_ZOMBIE:
continue
if child.ppid() == parent_pid:
- # Parent still alive — this is not an orphan; leave it.
logger.debug(
"Skipping child PID %d of old gateway %d: parent "
"still appears alive",
@@ -2219,25 +1814,17 @@ def take_over_scoped_lock_holder(
) -> Optional[int]:
"""Terminate one verified scoped-lock holder for explicit ``--replace``.
- Returns the original owner PID only after that exact PID/start-time identity
- has exited (or ``terminate_pid`` reports it already gone). Validation or
- marker-write failure returns ``None`` without signalling anything. This is
- deliberately stricter than the same-home PID-file replacement path: a
- cross-home handoff must place a consumable marker in the target's home or a
- service supervisor could revive the target and start a flap loop.
-
- On POSIX, after the owner is confirmed dead, its previously snapshotted
- child processes are reaped best-effort (see :func:`reap_gateway_children`)
- so orphaned adapter subprocesses cannot keep holding token locks.
+ Returns the owner PID only after that exact PID/start-time identity exited;
+ validation or marker-write failure returns None without signalling. Stricter
+ than same-home replacement: a cross-home handoff must place a consumable
+ marker in the target's home or its supervisor could revive it (flap loop).
+ On POSIX the owner's snapshotted children are then reaped best-effort.
"""
owner = _validated_scoped_lock_gateway_owner(record)
if owner is None:
return None
owner_pid, owner_start_time, target_home = owner
-
- # Snapshot descendants while the owner is still alive — after it exits
- # they are reparented and undiscoverable (POSIX; [] on Windows where
- # taskkill /T already tree-kills).
+ # Snapshot while the owner is alive; afterwards children are reparented.
owner_children = _snapshot_gateway_children(owner_pid)
replaced = _terminate_scoped_lock_owner_once(
@@ -2312,17 +1899,15 @@ def _terminate_scoped_lock_owner_once(
)
return owner_pid if exited else None
finally:
- # The target normally consumes its marker from the signal handler.
- # Clean up any remainder after an already-gone/forced/failed handoff.
+ # The target normally consumes the marker; clean up any remainder.
clear_takeover_marker(target_home)
def write_planned_stop_marker(target_pid: int) -> bool:
"""Record that ``target_pid`` is being stopped intentionally.
- The gateway exits non-zero for unexpected SIGTERM so service managers can
- revive it. Service stop commands send the same SIGTERM, so the CLI writes
- this short-lived marker first to let the target process exit cleanly.
+ Unexpected SIGTERM exits non-zero so service managers revive the gateway;
+ the CLI writes this marker first so a deliberate stop exits cleanly.
"""
try:
target_start_time = _get_process_start_time(target_pid)
@@ -2340,76 +1925,28 @@ def write_planned_stop_marker(target_pid: int) -> bool:
def consume_planned_stop_marker_for_self() -> bool:
"""Return True when the current process is being intentionally stopped."""
- return _consume_pid_marker_for_self(
- _get_planned_stop_marker_path(),
- pid_field="target_pid",
- start_time_field="target_start_time",
- ttl_s=_PLANNED_STOP_MARKER_TTL_S,
- )
+ return _consume_pid_marker_for_self(_get_planned_stop_marker_path(), ttl_s=_PLANNED_STOP_MARKER_TTL_S)
def planned_stop_marker_targets_self() -> bool:
- """Return True only when a live planned-stop marker names the current process.
-
- This is a **non-destructive** probe used by the watcher thread
- (``gateway/run.py:_run_planned_stop_watcher``) to decide whether to
- trigger shutdown. Unlike :func:`consume_planned_stop_marker_for_self`,
- it never unlinks a marker that matches us — the shutdown handler does
- the authoritative consume on its own thread.
-
- It *does* clean up markers that can never apply to this process:
- malformed markers and markers older than the TTL are unlinked so a
- stale file left behind by a previous gateway instance cannot wedge
- the new one. Markers naming a different PID/start_time are left in
- place (they may still be consumed legitimately by the process they
- name) but report False here.
-
- Returns False (without raising) on any read/parse error.
- """
- path = _get_planned_stop_marker_path()
- record = _read_json_file(path)
- if not record:
- return False
-
- try:
- target_pid = int(record["target_pid"])
- target_start_time = record.get("target_start_time")
- written_at = record.get("written_at") or ""
- except (KeyError, TypeError, ValueError):
- # Malformed marker can never match anyone — drop it.
- with contextlib.suppress(OSError):
- path.unlink(missing_ok=True)
- return False
-
- if _marker_is_stale(written_at, _PLANNED_STOP_MARKER_TTL_S):
- # A marker this old is past its useful life regardless of target —
- # clean it up so it cannot crash-loop a freshly booted gateway.
- with contextlib.suppress(OSError):
- path.unlink(missing_ok=True)
- return False
+ """Non-destructive probe: True when a live planned-stop marker names this process.
- our_pid = os.getpid()
- if target_pid != our_pid:
+ Used by the watcher thread (``gateway/run.py:_run_planned_stop_watcher``).
+ Unlike :func:`consume_planned_stop_marker_for_self` it never unlinks a
+ matching marker -- the shutdown handler does the authoritative consume.
+ Malformed/expired markers are still cleaned up; markers naming another
+ PID are left for that process and report False here.
+ """
+ parsed = _read_live_pid_marker(_get_planned_stop_marker_path(), _PLANNED_STOP_MARKER_TTL_S)
+ if parsed is None:
return False
-
- # Start-time is a PID-reuse guard. It is only meaningful when both
- # sides actually have it: ``_get_process_start_time`` returns None on
- # platforms without ``/proc`` (macOS, native Windows — the very
- # platform this watcher exists for). Requiring a non-None match there
- # would make the watcher never fire and re-break the #33778 Windows
- # session-resume path. So: when both start_times are known they must
- # match; when either is unknown, fall back to PID equality alone
- # (the marker is short-lived under a 60s TTL, bounding reuse risk).
- our_start_time = _get_process_start_time(our_pid)
- if target_start_time is not None and our_start_time is not None:
- return target_start_time == our_start_time
- return True
+ _, target_pid, target_start_time = parsed
+ return _pid_marker_names_self(target_pid, target_start_time)
def clear_planned_stop_marker() -> None:
"""Remove the planned-stop marker unconditionally."""
- with contextlib.suppress(OSError):
- _get_planned_stop_marker_path().unlink(missing_ok=True)
+ _unlink_quietly(_get_planned_stop_marker_path())
def get_running_pid(
@@ -2417,49 +1954,26 @@ def get_running_pid(
*,
cleanup_stale: bool = True,
) -> Optional[int]:
- """Return the PID of a running gateway instance, or ``None``.
-
- Checks the PID file and verifies the process is actually alive.
- Cleans up stale PID files automatically.
- """
+ """PID of a running gateway (lock + PID file verified against the live process), or None."""
resolved_pid_path = pid_path or _get_pid_path()
resolved_lock_path = _get_gateway_lock_path(resolved_pid_path)
- lock_active = is_gateway_runtime_lock_active(resolved_lock_path)
- if not lock_active:
- if pid_path is None:
- runtime_pid = get_runtime_status_running_pid()
- if runtime_pid is not None:
- return runtime_pid
+ if is_gateway_runtime_lock_active(resolved_lock_path):
+ for record in (_read_pid_record(resolved_pid_path), _read_gateway_lock_record(resolved_lock_path)):
+ pid = _pid_from_record(record)
+ if pid is None or not _pid_exists(pid) or _start_time_conflicts(record, pid):
+ continue
+ if not _pid_record_belongs_to_current_profile(record):
+ continue
+ if _record_matches_live_gateway_pid(record, pid):
+ return pid
_cleanup_invalid_pid_path(resolved_pid_path, cleanup_stale=cleanup_stale)
- return None
-
- primary_record = _read_pid_record(resolved_pid_path)
- fallback_record = _read_gateway_lock_record(resolved_lock_path)
-
- for record in (primary_record, fallback_record):
- pid = _pid_from_record(record)
- if pid is None:
- continue
-
- if not _pid_exists(pid):
- continue
-
- recorded_start = record.get("start_time")
- current_start = _get_process_start_time(pid)
- if recorded_start is not None and current_start is not None and current_start != recorded_start:
- continue
-
- if not _pid_record_belongs_to_current_profile(record):
- continue
-
- if _record_matches_live_gateway_pid(record, pid):
- return pid
-
- _cleanup_invalid_pid_path(resolved_pid_path, cleanup_stale=cleanup_stale)
+ return get_runtime_status_running_pid() if pid_path is None else None
+ # Lock inactive: the runtime-status fallback runs BEFORE cleanup here.
if pid_path is None:
runtime_pid = get_runtime_status_running_pid()
if runtime_pid is not None:
return runtime_pid
+ _cleanup_invalid_pid_path(resolved_pid_path, cleanup_stale=cleanup_stale)
return None
@@ -2469,15 +1983,10 @@ def get_running_pid_identity_strict(pid_path: Path) -> Optional[tuple[int, float
resolved_lock_path = _get_gateway_lock_path(resolved_pid_path)
pid_exists = _strict_path_exists(resolved_pid_path, "gateway PID")
lock_exists = _strict_path_exists(resolved_lock_path, "gateway lock")
- if not pid_exists and not lock_exists:
- return None
if not lock_exists:
- # No runtime lock can be owned. A stale PID file is not a live gateway.
- return None
+ return None # A stale PID file without a lock is not a live gateway.
if not _is_gateway_runtime_lock_active_strict(resolved_lock_path):
- # The lock probe is authoritative for absence. Stale or malformed files
- # may remain after a crash, but no process currently owns this runtime.
- return None
+ return None # Lock probe is authoritative for absence.
if not pid_exists:
raise RuntimeError("active gateway lock has no PID metadata")
pid_record = _read_pid_record(resolved_pid_path)
@@ -2502,9 +2011,8 @@ def get_running_pid_identity_strict(pid_path: Path) -> Optional[tuple[int, float
raise RuntimeError("gateway process identity changed")
if not all(_record_matches_live_gateway_pid(record, pid) for record in (pid_record, lock_record)):
raise RuntimeError("runtime metadata does not identify a live gateway")
- # Windows persists a centisecond fingerprint; SCM ownership checks need the
- # exact psutil epoch timestamp. Re-read it only after the persisted identity
- # has been validated, and prove it still rounds to that same fingerprint.
+ # Windows persists a centisecond fingerprint; SCM checks need the exact psutil
+ # epoch. Re-read only after validation and prove it rounds to the same value.
if _IS_WINDOWS:
try:
import psutil # type: ignore
@@ -2524,14 +2032,10 @@ def get_running_pid_cached(
cleanup_stale: bool = True,
ttl_seconds: float = _GATEWAY_RUNNING_PID_CACHE_TTL_SECONDS,
) -> Optional[int]:
- """Cached read-side wrapper for dashboard/status polling.
-
- ``get_running_pid()`` probes the runtime lock by briefly opening and locking
- ``gateway.lock``. That is the right authoritative check for control paths,
- but high-frequency read-only HTTP polling can call it hundreds of times per
- minute. Cache for a short window and invalidate on PID/lock/runtime-status
- file changes so status endpoints do not churn file descriptors while still
- noticing gateway start/stop transitions quickly.
+ """Cached ``get_running_pid()`` for high-frequency dashboard polling.
+
+ Short TTL, invalidated on PID/lock/runtime-status file changes, so status
+ endpoints do not re-flock ``gateway.lock`` hundreds of times a minute.
"""
if ttl_seconds <= 0:
return get_running_pid(pid_path, cleanup_stale=cleanup_stale)
diff --git a/gateway/stream_consumer.py b/gateway/stream_consumer.py
index 07ed8f65b78..3e0c8a9df01 100644
--- a/gateway/stream_consumer.py
+++ b/gateway/stream_consumer.py
@@ -1,14 +1,9 @@
"""Gateway streaming consumer — bridges sync agent callbacks to async platform delivery.
-The agent fires stream_delta_callback(text) synchronously from its worker thread.
-GatewayStreamConsumer:
- 1. Receives deltas via on_delta() (thread-safe, sync)
- 2. Queues them to an asyncio task via queue.Queue
- 3. The async run() task buffers, rate-limits, and progressively edits
- a single message on the target platform
-
-Design: Uses the edit transport (send initial message, then editMessageText).
-This is universally supported across Telegram, Discord, and Slack.
+The agent fires stream_delta_callback(text) synchronously from its worker thread;
+on_delta() queues it (queue.Queue) and the async run() task buffers, rate-limits,
+and progressively edits a single platform message (send, then editMessageText —
+supported everywhere; draft/native transports are optional per adapter).
Credit: jobless0x (#774, #1312), OutThisLife (#798), clicksingh (#697).
"""
@@ -42,62 +37,36 @@ import contextlib
logger = logging.getLogger("gateway.stream_consumer")
-# Sentinel to signal the stream is complete
-_DONE = object()
-_NEW_SEGMENT = object()
-_COMMENTARY = object()
-# Sentinel for tool-progress lines injected into the native stream bubble.
-# Enqueued as ``(_TOOL_PROGRESS, line_text)`` by ``on_tool_progress()``.
-_TOOL_PROGRESS = object()
-# Authoritative turn-final payload, enqueued by ``finish(final_text=...)``
-# just before ``_DONE``. Carries the completed ``final_response`` —
-# including post-stream augmentation (file-mutation verifier footer,
-# turn-completion explainer) — so the finalize/seal delivers the TRUE final
-# and the recorded payload reconciles (#71643 / live finding #11: the
-# footer-bearing final previously arrived only via a separate plain send).
+# Queue sentinels (see run() for handling).
+_DONE = object() # stream complete
+_NEW_SEGMENT = object() # finalize current message, start a fresh one
+_COMMENTARY = object() # (_COMMENTARY, text): completed interim commentary
+_TOOL_PROGRESS = object() # (_TOOL_PROGRESS, line): overlay line for the native bubble
+# (_FINAL_TEXT, text): authoritative completed final_response (incl. post-stream
+# augmentation such as verifier footers) enqueued just before _DONE, so the
+# finalize/seal delivers the TRUE final and the recorded payload reconciles.
_FINAL_TEXT = object()
-
-# Queue marker for a synchronous flush barrier. Enqueued as
-# ``(_FLUSH, threading.Event)``; the drain loop finalizes and delivers any
-# buffered segment, then sets the event. A caller on the agent worker thread
-# uses this (via ``flush_pending_sync``) to block until everything queued
-# BEFORE the marker has actually landed on the platform — needed before
-# sending a blocking interactive prompt (clarify poll) so the prompt is the
-# last thing on screen, not racing ahead of buffered prose.
+# (_FLUSH, threading.Event): barrier — drain loop finalizes/delivers anything
+# buffered, then sets the event. Used by flush_pending_sync() before a blocking
+# interactive prompt so the prompt lands below buffered prose, not above it.
_FLUSH = object()
-
-# Sentinel to signal an interaction boundary (approval prompt OR clarify
-# decision prompt) — finalize the current stream, disable native streaming,
-# and let post-interaction output go via send().
+# Interaction boundary (approval OR clarify prompt): finalize the current
+# stream; post-prompt output goes via send() or a re-opened stream.
_APPROVAL_BOUNDARY = object()
-
-# Sentinel to request an EAGER native re-seed after a clarify-reopen boundary.
-# Posted the moment the user answers a clarify (before the LLM produces any
-# post-answer delta), so the WeCom typing bubble reappears immediately instead
-# of waiting for the first token. On WeCom, typing is driven by the stream
-# seed frame (send_typing is a no-op), and the reopen path otherwise re-seeds
-# lazily on the first delta — measured 48s of dead air in one turn. Handled
-# serially in run(); see request_reopen_seed() and the run-loop handler.
+# EAGER native re-seed right after a clarify answer, before the first post-answer
+# delta. On WeCom typing is driven by the seed frame (send_typing is a no-op)
+# and lazy re-seed on first delta measured 48s of dead air.
_REOPEN_SEED = object()
-# Default finalize text shown at an interaction boundary when no content has
-# accumulated yet. Callers may override per-boundary (e.g. clarify passes its
-# own) via close_for_approval_prompt(placeholder=...).
+# Boundary finalize text when nothing has accumulated yet; overridable per
+# boundary via close_for_approval_prompt(placeholder=...).
_DEFAULT_BOUNDARY_PLACEHOLDER = "⏸ 等待审批中..."
def escape_code_fences_for_display(text: str) -> str:
- """Escape triple-backtick markers so text can be safely wrapped
- inside an outer ``` code block without breaking the fence.
-
- When reasoning content contains ``` (e.g. the model quotes code
- in its thinking), wrapping it in an outer ``` for display causes
- the inner fence to break the outer block. Solution: replace each
- `` ``` `` with `` \\`\\`\\` `` before wrapping.
+ """Replace each ``` with \\`\\`\\` so text can be wrapped in an outer ``` block.
- Returns:
- The input text with each `` ``` `` replaced by `` \\`\\`\\` ``,
- or the input unchanged if no triple-backticks are present.
+ Reasoning content that quotes code would otherwise break the outer fence.
"""
if not isinstance(text, str) or "```" not in text:
return text
@@ -105,47 +74,23 @@ def escape_code_fences_for_display(text: str) -> str:
def ensure_closed_code_fences(text: str) -> str:
- """Append a closing `` ``` `` fence and/or `` ` `` if the text has
- orphaned code-block or inline-code markers.
-
- When model output is truncated mid-code-block (e.g. by token limits
- or a finish_reason="length"), the resulting message has an unclosed
- code fence. On Discord, Slack, and other platforms this causes
- everything after the orphaned fence to render as a single code block.
- The same problem applies to inline-code spans closed by a single
- backtick: an orphaned `` ` `` makes the remainder of the message
- render as inline code.
-
- Triple-backtick: count `` ``` `` occurrences. If odd, append a
- closing fence on its own line. This is safe because nested
- triple-backtick fences (e.g. a literal `` ``` `` inside a code block)
- are exceedingly rare in model output and, when they do appear, the
- extra closing fence just creates a brief empty code block at the end
- of the message — far less harmful than the entire message being one
- giant code block.
-
- Single backtick: after balancing triple-backtick fences, strip all
- complete `` ```…``` `` regions and count remaining standalone `` ` ``.
- If odd, append a closing inline-code backtick. Same trade-off: a
- stray closing backtick may produce a brief empty inline-code span,
- which is far less harmful than the rest of the message being rendered
- as inline code.
-
- Returns:
- The input text with closing markers appended if needed, or the
- input text unchanged.
+ """Append a closing ``` and/or ` if the text has orphaned code markers.
+
+ Output truncated mid-code-block (token limit, finish_reason="length") would
+ otherwise render everything after the orphan as one code block / inline
+ span. Trade-off: a spurious close creates a brief empty span at the end,
+ far less harmful than the alternative. Odd ``` count → append a fence on
+ its own line; then, with complete ```…``` regions stripped, odd ` count →
+ append a backtick.
"""
if not isinstance(text, str) or not text:
return text
- # Step 1: fix triple-backtick code-block fences (existing logic)
if text.count("```") % 2 == 1:
text = text.rstrip("\n") + "\n```"
- # Step 2: fix single-backtick inline-code spans
- # Remove complete ```…``` regions so their internal backticks don't
- # pollute the standalone count. Also remove any trailing unclosed
- # ``` that leaks through (defence in depth).
+ # Strip complete fenced regions (and any trailing unclosed ``` that leaks
+ # through) so their internal backticks don't pollute the standalone count.
import re
without_fences = re.sub(r"```.*?```", "", text, flags=re.DOTALL)
without_fences = re.sub(r"```[^`]*$", "", without_fences)
@@ -163,25 +108,16 @@ class StreamConsumerConfig:
buffer_threshold: int = _DEFAULT_STREAMING_BUFFER_THRESHOLD
cursor: str = _DEFAULT_STREAMING_CURSOR
buffer_only: bool = False
- # When >0, the final edit for a streamed response is delivered as a
- # fresh message if the original preview has been visible for at least
- # this many seconds. This makes the platform's visible timestamp
- # reflect completion time instead of first-token time for long-running
- # responses (e.g. reasoning models that stream slowly). Ported from
- # openclaw/openclaw#72038. Default 0 = always edit in place (legacy
- # behavior). The gateway enables this selectively per-platform.
+ # When >0, deliver the final as a fresh message if the preview has been
+ # visible at least this long, so the visible timestamp reflects completion
+ # rather than first token. 0 = always edit in place. Enabled per-platform.
fresh_final_after_seconds: float = 0.0
- # Streaming transport selection:
- # "auto" — prefer native draft streaming (e.g. Telegram sendMessageDraft)
- # when the adapter + chat supports it; fall back to edit.
- # "draft" — explicitly request native draft streaming; fall back to
- # edit when unsupported.
- # "edit" — progressive editMessageText (legacy/default behavior).
- # "off" — handled by the gateway before the consumer is even built.
+ # "auto"/"draft": native draft streaming when adapter+chat support it, else
+ # edit. "edit": progressive editMessageText. "off": handled by the gateway
+ # before the consumer is built.
transport: str = "edit"
- # Hint for the consumer about the originating chat type (e.g. "dm",
- # "group", "supergroup", "forum"). Used to gate native draft streaming,
- # which is platform-specific (Telegram drafts are DM-only).
+ # Originating chat type ("dm", "group", ...); gates draft streaming, which
+ # is platform-specific (Telegram drafts are DM-only).
chat_type: str = ""
@@ -191,20 +127,17 @@ class GatewayStreamConsumer:
Usage::
consumer = GatewayStreamConsumer(adapter, chat_id, config, metadata=metadata)
- # Pass consumer.on_delta as stream_delta_callback to AIAgent
agent = AIAgent(..., stream_delta_callback=consumer.on_delta)
- # Start the consumer as an asyncio task
task = asyncio.create_task(consumer.run())
# ... run agent in thread pool ...
consumer.finish() # signal completion
await task # wait for final edit
"""
- # After this many consecutive flood-control failures, permanently disable
- # progressive edits for the remainder of the stream.
+ # Consecutive flood-control failures before progressive edits are disabled
+ # for the rest of the stream.
_MAX_FLOOD_STRIKES = 3
- # Reasoning/thinking tags that models emit inline in content.
# Must stay in sync with cli.py _OPEN_TAGS/_CLOSE_TAGS and
# run_agent.py _strip_think_blocks() tag variants.
_OPEN_THINK_TAGS = (
@@ -216,22 +149,14 @@ class GatewayStreamConsumer:
"</THINKING>", "</thinking>", "</thought>",
)
- # Class-wide monotonic counter for native-streaming draft ids. Telegram
- # animates a draft when the same draft_id is reused across consecutive
- # calls in the same chat, so we need a fresh non-zero id per response.
- #
- # Seeded from a RANDOM process nonce, not zero and not the clock (PR
- # 85796 review, B3 + r2 follow-up): draft_id is the wire identity for
- # the relay connector's per-(channel, draft_id) sealed-stream
- # tombstones, which outlive this process. Relay gateways are
- # disposable by design (scale-to-zero), so a counter restarting at 1
- # replays ids the connector already sealed — it then answers frames
- # from the NEW turn out of the OLD tombstone (zero platform calls,
- # old message identity) and the user's reply is silently dropped.
- # An epoch-ms seed (the first fix) still collides on same-millisecond
- # starts, forks, and clock steps; 49 random bits make collision
- # probability negligible while keeping ids + realistic turn counts
- # comfortably inside the connector's JS number range (2^53).
+ # Class-wide monotonic counter for draft ids (Telegram animates a draft only
+ # when the same non-zero draft_id is reused within a response). Seeded from
+ # a RANDOM nonce, not 0 or the clock: draft_id is the wire identity for the
+ # relay connector's per-(channel, draft_id) sealed-stream tombstones, which
+ # outlive this (scale-to-zero) process — a replayed id is answered out of
+ # the OLD tombstone and the reply is silently dropped. Epoch-ms seeds still
+ # collide on same-ms starts/forks/clock steps; 49 bits keeps ids + turn
+ # counts inside the connector's JS number range (2^53).
_draft_id_counter: int = secrets.randbits(49)
def __init__(
@@ -249,199 +174,138 @@ class GatewayStreamConsumer:
self.chat_id = chat_id
self.cfg = config or StreamConsumerConfig()
self.metadata = metadata
- # Fired whenever a fresh content bubble is created on the platform
- # (first-send of a new message, commentary, overflow chunk, or
- # fallback continuation). The gateway uses this to linearize the
- # tool-progress bubble: when content resumes after a tool batch,
- # the next tool.started should open a NEW progress bubble below
- # the content, not edit the old bubble above it.
- # Called with no arguments. Exceptions are swallowed.
+ # No-arg callback fired whenever a fresh content bubble is created
+ # (first send, commentary, overflow chunk, fallback continuation); the
+ # gateway uses it to open the next tool-progress bubble BELOW resumed
+ # content instead of editing the old one above. Exceptions swallowed.
self._on_new_message = on_new_message
- # Fired once when the stream transitions into its finalization path.
- # Gateway callers use this to pause typing refreshes before a slow
- # final rich-text edit (Telegram MarkdownV2 finalize, etc.).
+ # Fired once on entering the finalization path so the gateway can pause
+ # typing refreshes before a slow rich-text final edit.
self._on_before_finalize = on_before_finalize
self._initial_reply_to_id = initial_reply_to_id
- # Per-turn identifier: uniquely identifies this consumer's stream turn.
- # Passed to adapter.send_stream_frame() to prevent concurrent consumers
- # from interfering with each other (e.g., /background, parallel subagents).
- # Mirrors official wecom-openclaw-plugin's per-message streamId generation.
+ # Per-turn id passed to adapter.send_stream_frame() so concurrent
+ # consumers (/background, parallel subagents) don't interfere.
import uuid
self._turn_id = str(uuid.uuid4())
self._queue: queue.Queue = queue.Queue()
self._accumulated = ""
- # Full segment text mirror of ``_accumulated`` that is NOT truncated
- # when overflow splits seal head chunks. Used to record a reconciliable
- # turn-final payload for multi-message deliveries (#78541).
+ # Mirror of ``_accumulated`` NOT truncated when overflow splits seal
+ # head chunks; records a reconcilable turn-final payload for splits.
self._stream_ledger = ""
self._message_id: Optional[str] = None
- # Wall-clock timestamp (time.monotonic) when ``_message_id`` was
- # first assigned from a successful first-send. Used by the
- # fresh-final logic to detect long-lived previews whose edit
- # timestamps would be stale by completion time. Ported from
- # openclaw/openclaw#72038.
+ # time.monotonic() when ``_message_id`` was first assigned; fresh-final
+ # logic uses it to detect long-lived previews.
self._message_created_ts: Optional[float] = None
- # Every real preview message id the consumer has put on screen during
- # this response (first send + any continuation messages from oversized
- # edits/sends). The fresh-final path deletes all of them when it
- # re-delivers the completed answer as a single (rich) message, so a
- # reply that was split across the platform's edit limit while streaming
- # doesn't leave stale fragments above the final message.
+ # Every real preview message id put on screen this response (first send
+ # + continuation messages). Fresh-final deletes them all so a reply
+ # split at the edit limit leaves no stale fragments above the final.
self._preview_message_ids: "set[str]" = set()
- # IDs from only the active text segment. A tool boundary preserves
- # the run-wide set for fresh-final bookkeeping, but a failure recovery
- # must never delete an earlier finalized preamble/commentary message.
+ # IDs from only the active text segment: failure recovery must never
+ # delete an earlier finalized preamble/commentary message.
self._segment_preview_message_ids: "set[str]" = set()
self._already_sent = False
self._edit_supported = True # Disabled when progressive edits are no longer usable
self._last_edit_time = 0.0
self._last_sent_text = "" # Track last-sent text to skip redundant edits
- # True when the most recent _send_or_edit split-and-delivered across
- # continuation messages (the adapter adopted a new message id).
+ # True when the most recent _send_or_edit split across continuation
+ # messages (the adapter adopted a new message id).
self._last_edit_overflowed = False
self._fallback_final_send = False
self._fallback_prefix = ""
- # True when fallback is sending only the missing tail after a partial
- # Telegram overflow delivery. In that case the already-visible prefix
- # is intentional content, not a stale preview to delete.
+ # True when fallback sends only the missing tail after a partial
+ # overflow delivery: the visible prefix is content, not a stale preview.
self._fallback_preserve_partial_messages = False
- # Keep fallback recovery responsive. Telegram's adapter already bounds
- # edit retries at five seconds; a final-delivery fallback must not hold
- # the stream task through a longer flood cooldown before retrying.
+ # Telegram bounds edit retries at 5s; a final-delivery fallback must not
+ # hold the stream task through a longer flood cooldown.
self._max_fallback_flood_retry_seconds = 5.0
self._flood_strikes = 0 # Consecutive flood-control edit failures
self._current_edit_interval = self.cfg.edit_interval # Adaptive backoff
self._final_response_sent = False
- # Set when the final response content was sent to the user via
- # streaming, even if the final edit (cursor removal etc.)
- # subsequently failed.
+ # Final content reached the user even if the cosmetic final edit
+ # (cursor removal) then failed.
self._final_content_delivered = False
# Exact cleaned payload of the turn-final delivery that set the flags
- # above. The gateway compares this against the completed
- # ``final_response`` before trusting the flags: a *successful* finalize
- # edit that carried only a stale preview snapshot must not suppress the
- # complete send (#71643). ``None`` means "no record" — legacy trust,
- # so paths that predate the record keep their behavior.
+ # above. The gateway compares it against the completed final_response
+ # before trusting the flags (a successful finalize edit may carry only a
+ # stale preview snapshot). ``None`` = no record → legacy trust.
self._delivered_final_text: Optional[str] = None
- # True when the current turn's answer was delivered across multiple
- # sealed messages (overflow split / adapter continuation adoption).
- # When a payload was recorded (via ``_stream_ledger`` /
- # ``_record_turn_final_payload``), ``delivered_final_matches`` can still
- # reconcile. Payload-less split delivery must NOT inherit legacy trust
- # (#78541) — that combination was swallowing complete Telegram group
- # replies after an early/partial multi-message delivery.
+ # Answer delivered across multiple sealed messages (overflow split /
+ # continuation adoption). With a recorded payload, delivered_final_matches
+ # can still reconcile; payload-less split delivery must NOT inherit
+ # legacy trust (it swallowed complete replies after partial splits).
self._turn_split_delivery = False
- # True when a full-final send timed out in a way that MAY have reached
- # the platform (``_send_empty_fallback_final`` → "ambiguous"). The
- # only case where a payload-less delivery flag keeps legacy trust in
- # ``delivered_final_matches`` (#95382 tightening) — re-sending there
- # risks a duplicate rather than recovering a loss.
+ # A full-final send timed out in a way that MAY have reached the
+ # platform — the only payload-less case that keeps legacy trust, since
+ # re-sending risks a duplicate rather than recovering a loss.
self._delivery_ambiguous = False
self._delivered_commentary_texts: list[str] = []
- # Retains the finalized visible text of each streaming segment so
- # ``has_delivered_text`` can still match after ``_reset_segment_state``
- # clears ``_last_sent_text``. Without this, a segment break (triggered
- # by ``on_segment_break`` or ``on_commentary``) erases the only record
- # of what was delivered, and the gateway's final-send suppression
- # can't recognize an already-delivered response. (#65919 review)
+ # Finalized visible text of each segment, so has_delivered_text still
+ # matches after _reset_segment_state clears _last_sent_text.
self._delivered_segment_texts: list[str] = []
- # Cache adapter lifecycle capability: only platforms that need an
- # explicit finalize call (e.g. DingTalk AI Cards) force us to make
- # a redundant final edit. Everyone else keeps the fast path.
- # Use ``is True`` (not ``bool(...)``) so MagicMock attribute access
- # in tests doesn't incorrectly enable this path.
+ # Only platforms needing an explicit finalize call (e.g. DingTalk AI
+ # Cards) force a redundant final edit. ``is True`` keeps MagicMock
+ # adapters in tests from enabling this path.
self._adapter_requires_finalize: bool = (
getattr(adapter, "REQUIRES_EDIT_FINALIZE", False) is True
)
- # Session staleness guard — when set to False (e.g. after /new or
- # /stop), the run() loop will abandon the stream early instead of
- # continuing to edit and deliver stale deltas.
+ # Returns False after /new or /stop; run() then abandons the stream
+ # instead of delivering stale deltas.
self._run_still_current = run_still_current or (lambda: True)
# Think-block filter state (mirrors CLI's _stream_delta tag suppression)
self._in_think_block = False
self._think_buffer = ""
- # Native draft-streaming state. Resolved at the start of run() based
- # on cfg.transport, cfg.chat_type, and the adapter's
- # supports_draft_streaming() probe. When True, the consumer emits
- # animated draft frames via adapter.send_draft instead of progressive
- # edits via adapter.edit_message. The final answer still goes
- # through the normal first-send path so the user gets a real message
- # in their chat history (drafts have no message_id).
+ # Draft streaming: resolved at the start of run(). Animated frames go
+ # via adapter.send_draft instead of edits; the final answer still uses
+ # the normal first-send path (drafts have no message_id).
self._use_draft_streaming = False
self._draft_id: Optional[int] = None
- # Cumulative draft-frame failure count for this consumer. After the
- # first failure we permanently disable drafts for the remainder of
- # this response and route through edit-based for graceful degradation.
+ # First draft failure permanently disables drafts for this response.
self._draft_failures = 0
self._before_finalize_notified = False
- # Native streaming transport (e.g. WeCom msgtype: "stream"). Unlike
- # drafts, native streaming is the *only* delivery channel for the
- # turn — first frame, mid-stream updates, and the final answer all
- # flow through ``adapter.send_stream_frame()`` and the adapter
- # manages the stream lifecycle (init → cumulative updates →
- # finish=true). Resolved at the start of run() and disabled on
- # any failure so the consumer falls back to edit/send.
+ # Native streaming (e.g. WeCom msgtype "stream"): the ONLY delivery
+ # channel for the turn — seed, cumulative updates, and finish=true all
+ # go through adapter.send_stream_frame(). Resolved at the start of
+ # run(); disabled on any failure so the consumer falls back to edit/send.
self._use_native_streaming = False
- # Tracks whether the native stream bubble has been opened (seed frame sent).
- # Used in fallback logic to decide if we need to finalize the stream before
- # falling back to send(). Set to True after seed frame succeeds, even though
- # seed has zero visible content.
+ # Seed frame sent (even though it has zero visible content); fallback
+ # logic uses it to decide whether the stream must be finalized first.
self._native_stream_opened = False
- # Number of visible characters last successfully pushed to the
- # native stream. Used for "send only when enough new content has
- # accumulated" throttling so we don't spam frames at WeCom's
- # 30 frames/min rate ceiling.
+ # Visible chars last pushed to the native stream; throttles frames
+ # under WeCom's 30 frames/min ceiling.
self._native_last_pushed_len = 0
- # Finalize text used at an interaction boundary (approval/clarify) when
- # no content has accumulated yet. Set by close_for_approval_prompt();
- # defaults to the approval wording for backward compatibility.
+ # Boundary state, set by close_for_approval_prompt(); race-free because
+ # boundaries are processed serially. ``_boundary_reopen``: keep native
+ # streaming enabled so post-prompt output re-opens a fresh stream via
+ # the lazy re-seed (clarify: short waits) instead of degrading to send()
+ # (approval: unbounded waits, stream may go stale).
self._boundary_placeholder = _DEFAULT_BOUNDARY_PLACEHOLDER
- # Human-readable label for the current interaction boundary, used only
- # for log prefixes so a clarify boundary doesn't log as "Approval".
- # Set by close_for_approval_prompt(); race-free because boundaries are
- # processed serially.
self._boundary_reason = "Approval"
- # When True, the interaction boundary finalizes the current stream but
- # KEEPS native streaming enabled so post-prompt output re-opens a fresh
- # native stream (via the lazy re-seed in _send_or_edit) instead of
- # degrading to a one-shot send(). Clarify sets this (short waits, low
- # stream-staleness risk); approval leaves it False (long, unbounded
- # waits — the stream may go stale, so send() is safer). Set by
- # close_for_approval_prompt(); race-free (boundaries are serial).
self._boundary_reopen = False
- # Marks that a boundary asked to reopen the native stream but no
- # post-prompt content has re-seeded it yet. Guards got_done from
- # re-seeding a fresh stream just to emit a lone "✅" placeholder when
- # the agent produced nothing after the prompt.
+ # Boundary asked to reopen but nothing has re-seeded yet; keeps got_done
+ # from opening a stream just to emit a lone "✅" placeholder.
self._awaiting_reopen_after_boundary = False
- # Marks that an EAGER re-seed (via _REOPEN_SEED) already opened a fresh
- # native stream after a clarify answer, BEFORE any post-answer content.
- # Unlike the lazy path, the typing bubble is already on screen, so
- # got_done must actively finalize it (not silently skip) when the agent
- # produces no content — otherwise a blank typing bubble hangs forever.
+ # An EAGER re-seed (_REOPEN_SEED) already opened a fresh bubble before
+ # any content, so got_done must actively finalize it when the agent
+ # produces nothing — otherwise a blank typing bubble hangs forever.
self._reopen_seeded_eagerly = False
- # Tool-progress overlay state (native streaming only).
- # Lines are injected via on_tool_progress() and displayed as a
- # temporary overlay in the stream bubble until real text arrives.
+ # Tool-progress overlay (native streaming only): lines from
+ # on_tool_progress() shown in the bubble until real text arrives.
self._tool_progress_lines: list[str] = []
self._tool_progress_active: bool = False
-
def _stream_is_message(self) -> bool:
"""Whether THIS chat's transport treats the stream as the message.
- Prefers the adapter's per-chat probe (multi-platform relay: one
- adapter fronts N platforms, and the class attribute can only
- reflect the primary identity — review r2, finding 2). Falls back
- to the legacy attribute for adapters without the probe. Both are
- resolved on the CLASS to stay MagicMock-safe (auto-created
- instance attributes are truthy).
+ Prefers the adapter's per-chat probe (a multi-platform relay adapter's
+ class attribute can only reflect its primary identity), falling back to
+ the legacy attribute. Both are resolved on the CLASS to stay
+ MagicMock-safe (auto-created instance attributes are truthy).
"""
probe = getattr(type(self.adapter), "stream_is_message_for_chat", None)
if callable(probe):
@@ -453,35 +317,17 @@ class GatewayStreamConsumer:
@property
def accepts_tool_progress(self) -> bool:
- """Whether this consumer can absorb tool progress into its stream.
-
- True only when native streaming is resolved and active. Callers use
- this to decide the progress routing path (in-stream vs progress_queue).
- """
+ """True only when native streaming is active (gates in-stream tool progress)."""
return self._use_native_streaming
def on_tool_progress(self, line: str) -> None:
- """Inject a tool-progress status line into the native stream bubble.
-
- Thread-safe (called from agent worker thread via queue.Queue). Only
- meaningful when native streaming is active — callers should gate on
- ``accepts_tool_progress``.
-
- The line is displayed as an overlay until the next text delta arrives,
- at which point real content overwrites the tool-progress lines.
- """
+ """Thread-safe: overlay a tool-progress line in the native bubble until the next delta."""
if line:
self._queue.put((_TOOL_PROGRESS, line))
def _compose_frame_content(self) -> str:
- """Compose the current frame content for native streaming.
-
- Strategy B: when both accumulated text and tool-progress lines exist,
- append tool lines below the text separated by a horizontal rule.
- On finalize, only accumulated text is sent (no tool lines).
- """
+ """Native frame content: text, with any tool-progress lines below a rule."""
if self._accumulated and self._tool_progress_lines:
- # Text + active tool status at the bottom
return self._accumulated + "\n\n---\n" + "\n".join(self._tool_progress_lines)
elif self._accumulated:
return self._accumulated
@@ -495,16 +341,12 @@ class GatewayStreamConsumer:
final: bool = False,
expect_edits: bool = False,
) -> dict | None:
- """Return per-send metadata for stream-created messages.
-
- Mattermost treats notify-worthy sends as user-visible final content
- when deciding whether a broken thread root may fall back flat. Preview
- and progress sends keep their original metadata and remain thread-strict.
+ """Per-send metadata for stream-created messages.
- ``expect_edits`` preserves the upstream Telegram streaming contract:
- preview messages that may be edited later must stay on the editable
- legacy send path, while fresh/fallback final sends can still use richer
- final-message delivery.
+ ``final`` sets notify=True (Mattermost treats notify-worthy sends as
+ final content when deciding whether a broken thread root may fall back
+ flat). ``expect_edits`` keeps editable previews on Telegram's legacy
+ send path while final sends may use richer delivery.
"""
meta = dict(self.metadata) if self.metadata else {}
if self._initial_reply_to_id:
@@ -527,13 +369,12 @@ class GatewayStreamConsumer:
@property
def message_id(self) -> str | None:
- """The Discord/chat message ID of the last-sent or edited message."""
+ """Message ID of the last-sent or edited message."""
return self._message_id
@property
def final_content_delivered(self) -> bool:
- """True when the final response content reached the user, even if
- the subsequent cosmetic edit (cursor removal) failed."""
+ """True when the final content reached the user, even if the cosmetic final edit failed."""
return self._final_content_delivered
async def _notify_before_finalize(self) -> None:
@@ -558,15 +399,13 @@ class GatewayStreamConsumer:
finalize: bool = False,
):
"""Edit via the adapter, passing routing metadata when supported."""
+ # Contract: adapters must accept finalize= even when False (test-guarded).
kwargs = {
"chat_id": self.chat_id,
"message_id": message_id,
"content": content,
+ "finalize": finalize,
}
- # Keep the long-standing stream-consumer contract: concrete adapters
- # must accept finalize= even when it is False (guarded by tests).
- kwargs["finalize"] = finalize
-
if self.metadata:
try:
params = inspect.signature(self.adapter.edit_message).parameters
@@ -583,8 +422,7 @@ class GatewayStreamConsumer:
"""Append to the live buffer and the split-stable stream ledger."""
if not text:
return
- # New text delta arriving: clear tool-progress overlay so the next
- # frame shows real content (Strategy B: text overwrites tool lines).
+ # Real text overwrites the tool-progress overlay.
if self._tool_progress_lines:
self._tool_progress_lines.clear()
self._tool_progress_active = False
@@ -594,16 +432,10 @@ class GatewayStreamConsumer:
def _mark_skip_redundant_finalize(self) -> None:
"""Mark the turn final as delivered by a prior mid-stream edit.
- Used by the run loop when the final accumulated content was already
- delivered by the last visible edit and the explicit finalize edit is
- skipped. Records what was actually ACKED on the wire, not what was
- accumulated: a throttled edit-transport stream can reach this state
- with the last acked edit still holding an earlier preview snapshot
- (cursor-suffixed). Recording ``_accumulated`` would let a frozen
- preview reconcile as the delivered final and suppress the corrective
- send, leaving the user a cut-off message. The multi-message split
- path keeps its ledger substitution inside
- ``_record_turn_final_payload``.
+ Records what was ACKED on the wire, not ``_accumulated``: a throttled
+ edit stream can reach this state with the last acked edit still holding
+ an earlier (cursor-suffixed) preview, and recording the accumulator
+ would let that frozen preview suppress the corrective send.
"""
self._final_response_sent = True
self._final_content_delivered = True
@@ -613,19 +445,14 @@ class GatewayStreamConsumer:
self._record_turn_final_payload(acked)
def _record_turn_final_payload(self, text: str) -> None:
- """Record what the user has actually seen as this turn's final answer.
-
- Normalized the same way ``_send_or_edit`` normalizes outgoing text
- (media-directive strip + fence closing) so the gateway can compare it
- against the completed ``final_response`` (#71643).
-
- ``text`` is what the *calling* path just delivered. On a multi-message
- split that is only the trailing chunk — the overflow paths truncate
- ``_accumulated`` once head chunks are sealed — so ``_stream_ledger``
- (the un-truncated segment text) is preferred there and ``text`` is
- ignored. Without that substitution a split turn records a tail-only
- payload, which the gateway reads as a mismatch and re-sends on top of
- an answer the user already received (#78541).
+ """Record what the user actually saw as this turn's final answer.
+
+ Normalized like ``_send_or_edit`` output (media-directive strip + fence
+ closing) so the gateway can compare it to the completed final_response.
+ On a multi-message split ``text`` is only the trailing chunk (overflow
+ truncates ``_accumulated`` as head chunks seal), so the un-truncated
+ ``_stream_ledger`` is recorded instead — else the gateway sees a
+ mismatch and re-sends an answer the user already received.
"""
source = text or ""
if self._turn_split_delivery and self._stream_ledger:
@@ -635,23 +462,15 @@ class GatewayStreamConsumer:
).strip()
def delivered_final_matches(self, final_text: str) -> Optional[bool]:
- """Reconcile the recorded turn-final payload against ``final_text``.
-
- Returns a tri-state verdict for the gateway's suppression decision
- (#71643 — a *successful* finalize edit can still carry only a stale
- preview snapshot, so call success alone must not confirm delivery):
-
- - ``True`` — the recorded turn-final payload (or a previously
- delivered segment/commentary) matches ``final_text``; suppressing
- the normal final send is safe.
- - ``False`` — a turn-final delivery was recorded but its payload
- demonstrably differs from ``final_text``, OR this was a
- payload-less multi-message split delivery (#78541) whose flag
- alone must not suppress the normal final send.
- - ``None`` — no payload comparison is possible on a non-split
- legacy/uncertain path that recorded nothing. The caller keeps
- the pre-existing flag-trusting behavior so ambiguous-timeout
- dedup is not regressed.
+ """Tri-state reconcile of the recorded turn-final payload against ``final_text``.
+
+ A *successful* finalize edit can still carry only a stale preview, so
+ call success alone must not confirm delivery.
+ True: recorded payload (or an earlier segment/commentary) matches —
+ suppressing the normal final send is safe. False: recorded payload
+ differs, or payload-less multi-message split (flag alone must not
+ suppress). None: nothing recorded on a non-split legacy/ambiguous path;
+ caller keeps its flag-trusting behavior.
"""
target = ensure_closed_code_fences(
self._clean_for_display(final_text or "")
@@ -660,32 +479,23 @@ class GatewayStreamConsumer:
return None
if self._delivered_final_text is None:
if self._turn_split_delivery:
- # #78541: refuse legacy trust for payload-less split delivery.
return False
- # #95382 / #98552 class fix: a delivery flag with NO recorded
- # payload must still be judged against the FINAL content, not
- # trusted blindly. Every internal flag-setting site records a
- # payload; a record-less consumer whose visible/streamed text
- # does not contain the completed response has demonstrably NOT
- # delivered it (first-edit prefix, mid-stream truncation) — the
- # flag alone must not suppress the corrective send.
- # ``_already_sent`` gates the visible-text match: draft frames
- # set ``_last_sent_text`` for dedupe but are ephemeral (they
- # deliberately do not set ``_already_sent``), so draft-only
- # visibility must not count as durable delivery.
+ # No recorded payload: judge against the FINAL content rather than
+ # trusting the flag — a consumer whose visible text lacks the
+ # completed response (first-edit prefix, mid-stream truncation) has
+ # demonstrably NOT delivered it. ``_already_sent`` gates the match:
+ # draft frames set ``_last_sent_text`` but are ephemeral and
+ # deliberately don't set ``_already_sent``.
if self._already_sent and self.has_delivered_text(final_text):
return True
- # The one legitimately ambiguous case keeps legacy trust: a
- # timed-out full-final send may have reached the platform
- # (``_send_empty_fallback_final`` → "ambiguous"), so re-sending
- # risks a duplicate. That site marks itself explicitly.
+ # Only a timed-out full-final send that MAY have landed keeps legacy
+ # trust — re-sending risks a duplicate.
if self._delivery_ambiguous:
return None
return False
if self._delivered_final_text.strip() == target:
return True
- # A segment break / commentary may have delivered the final text
- # earlier in the turn under a different record.
+ # A segment break / commentary may have delivered it under another record.
return bool(self.has_delivered_text(final_text))
def has_delivered_text(self, text: str) -> bool:
@@ -711,66 +521,35 @@ class GatewayStreamConsumer:
reason: str = "Approval",
reopen: bool = False,
) -> asyncio.Future:
- """Signal an interaction boundary — finalize stream, then either disable
- native (approval) or keep it for a fresh re-opened stream (clarify).
-
- Used for any mid-stream interaction that must not keep updating the
- current native-stream bubble: a dangerous-command approval prompt or a
- clarify decision prompt. Queues a boundary signal that the consumer
- processes serially: finalize the current stream with accumulated text
- (creating a stable message for pre-prompt content), then handle
- post-prompt output per ``reopen``.
-
- ``placeholder`` is the finalize text used only when there is no
- accumulated content yet (the prompt fired as the agent's first action).
- Defaults to the approval placeholder; clarify passes its own so the
- finalized bubble doesn't read "waiting for approval" for a question.
-
- ``reason`` is a human-readable label ("Approval"/"Clarify") used only
- for the boundary handler's log prefixes so a clarify boundary doesn't
- surface as an "Approval boundary" failure during troubleshooting.
-
- ``reopen`` controls post-prompt delivery. False (approval): disable
- native streaming and buffer post-prompt output into a single reliable
- send() — approval waits are long and unbounded, so the stream may go
- stale. True (clarify): keep native streaming enabled so post-prompt
- output re-opens a fresh native stream via the existing lazy re-seed,
- restoring the typing-bubble experience; if the re-seed later fails the
- consumer degrades to send() automatically.
-
- Returns a (Future, cancelled_flag) tuple. The Future resolves True
- when the boundary has been processed. cancelled_flag is included
- for backward compatibility with callers that set it on timeout;
- the boundary handler no longer reads it (finalize always runs).
-
- For platforms without native streaming this is a no-op (returns
- an immediately-resolved Future).
-
- Called from sync context (agent/approval thread). The boundary
- is processed by the consumer's async run() task, ensuring no
- race conditions with pending deltas or other queue items.
+ """Queue an interaction boundary (approval / clarify prompt) from sync context.
+
+ run() processes it serially: finalize the current native stream with
+ accumulated text (``placeholder`` when nothing accumulated yet), then
+ per ``reopen``: False (approval; long unbounded waits, stream may go
+ stale) disables native streaming and batches post-prompt output into
+ one send(); True (clarify) keeps native enabled so post-prompt output
+ re-opens a fresh stream via the lazy re-seed, degrading to send() if
+ that fails. ``reason`` labels log lines ("Approval"/"Clarify").
+
+ Returns a (Future, cancelled_flag) tuple; the Future resolves True once
+ processed. cancelled_flag is kept for callers that set it on timeout
+ but the handler no longer reads it (finalize always runs). Without
+ native streaming returns a bare, already-resolved Future.
"""
loop = None
with contextlib.suppress(RuntimeError):
loop = asyncio.get_running_loop()
if not self._use_native_streaming:
- # No native stream to close — return resolved future
f = asyncio.Future() if loop else concurrent.futures.Future()
f.set_result(True)
return f
- # Stash the empty-content placeholder, log label, and reopen mode for
- # the serial boundary handler. Boundaries are processed one at a time,
- # so instance attributes are race-free and keep the queue signal shape
- # unchanged.
+ # Instance attributes are race-free: boundaries are processed one at a time.
self._boundary_placeholder = placeholder or _DEFAULT_BOUNDARY_PLACEHOLDER
self._boundary_reason = reason or "Approval"
self._boundary_reopen = bool(reopen)
- # Create a future that run() will resolve after processing.
- # cancelled_flag is retained for backward compatibility with callers
- # (run.py sets it on timeout) but the handler always finalizes regardless.
boundary_future = loop.create_future() if loop else concurrent.futures.Future()
cancelled_flag = {"cancelled": False}
@@ -783,20 +562,13 @@ class GatewayStreamConsumer:
self._queue.put((_COMMENTARY, text))
def flush_pending_sync(self, timeout: float = 5.0) -> bool:
- """Block the calling (agent worker) thread until everything queued
- before this point has been finalized and delivered to the platform.
-
- Enqueues a ``(_FLUSH, Event)`` barrier behind any pending deltas /
- commentary / segment breaks. The async ``run()`` task processes those
- first (FIFO), then handles the barrier — finalizing the current segment
- and setting the event. Returns True if the flush completed within
- ``timeout``, False on timeout (so the caller continues rather than
- hanging if the consumer task is not running / already finished).
-
- This is the ordering barrier used before sending a blocking interactive
- prompt (clarify poll): without it, the poll — sent on a separate,
- agent-thread-blocking path — races ahead of buffered prose that is still
- sitting in this queue, so the question lands ABOVE its own explanation.
+ """Block the agent worker thread until everything queued so far is delivered.
+
+ Enqueues a ``(_FLUSH, Event)`` barrier; run() drains earlier items
+ (FIFO), finalizes the current segment, then sets the event. Returns
+ False on timeout so the caller proceeds even if the consumer task is
+ not running. Used before a blocking interactive prompt (clarify poll)
+ so the question doesn't land ABOVE its own explanation.
"""
evt = threading.Event()
try:
@@ -806,18 +578,12 @@ class GatewayStreamConsumer:
return evt.wait(timeout=max(0.0, float(timeout)))
def request_reopen_seed(self) -> None:
- """Request an EAGER native re-seed after a clarify-reopen boundary.
-
- Called (thread-safe, like on_commentary / close_for_approval_prompt)
- the instant the user answers a clarify — BEFORE the LLM emits any
- post-answer delta. Posts _REOPEN_SEED so run() immediately sends an
- empty seed frame, which is what makes the WeCom typing bubble reappear
- without waiting for the first token (measured 48s of dead air otherwise).
-
- No-op unless we're in the reopen-pending state on a native stream: only
- after a clarify boundary (`_awaiting_reopen_after_boundary`) with native
- still enabled and no stream currently open. This keeps a stray call from
- opening a spurious bubble mid-stream or on the approval path.
+ """Thread-safe: request an EAGER native re-seed after a clarify answer.
+
+ Posts _REOPEN_SEED so run() sends an empty seed frame before the first
+ post-answer delta (WeCom typing bubble reappears immediately). No-op
+ unless reopen-pending on a native stream with no stream open, so a
+ stray call can't open a spurious bubble mid-stream or on approval.
"""
if (
self._use_native_streaming
@@ -840,11 +606,9 @@ class GatewayStreamConsumer:
def _signal_flush(flush_event) -> None:
"""Wake a thread blocked in flush_pending_sync(), swallowing errors.
- Centralised so every loop exit path that consumed a ``_FLUSH`` barrier
- (the normal bottom-of-iteration path AND early ``continue`` paths such
- as the oversized-prose overflow split) reliably sets the event. Missing
- a set is not a deadlock — the caller uses a bounded timeout — but it
- would make the caller stall the full timeout before its blocking send.
+ Every loop path that consumed a ``_FLUSH`` barrier (including early
+ ``continue`` paths) must call this; a missed set isn't a deadlock
+ (bounded wait) but stalls the caller for the full timeout.
"""
if flush_event is None:
return
@@ -854,9 +618,7 @@ class GatewayStreamConsumer:
def _reset_segment_state(self, *, preserve_no_edit: bool = False) -> None:
if preserve_no_edit and self._message_id == "__no_edit__":
return
- # Retain the finalized visible text of the current segment before
- # clearing ``_last_sent_text``, so ``has_delivered_text`` can still
- # match it after a segment break. (#65919 review)
+ # Retain the segment's visible text so has_delivered_text still matches.
if self._last_sent_text:
finalized = self._clean_for_display(self._last_sent_text).strip()
if finalized:
@@ -870,68 +632,41 @@ class GatewayStreamConsumer:
self._fallback_prefix = ""
self._fallback_preserve_partial_messages = False
self._segment_preview_message_ids = set()
- # Tool-progress overlay: clear on segment reset so a new segment
- # starts clean.
self._tool_progress_lines = []
self._tool_progress_active = False
- # #29346: a tool/segment boundary means what we delivered was an interim
- # preamble, not the final answer — clear the flags so a premature setter
- # can't fool the gateway. Safe: got_done returns before any reset, and
- # run.py reads these only after the consumer task exits.
+ # A segment boundary means what we delivered was an interim preamble —
+ # clear the final flags so a premature setter can't fool the gateway.
+ # Safe: got_done returns before any reset; run.py reads these only
+ # after the consumer task exits.
self._final_response_sent = False
self._final_content_delivered = False
self._delivered_final_text = None
self._delivery_ambiguous = False
self._turn_split_delivery = False
- # Native draft streaming: bump the draft_id so the next text segment
- # animates as a fresh preview below the tool-progress bubbles, not
- # over the prior segment's already-finalized draft. This is how
- # we avoid the "inter-tool-call text leak" failure mode openclaw
- # documented in their issue #32535 — each text block becomes its
- # own visible message via the finalize, then a new draft animates
- # for the next one.
- if self._use_draft_streaming:
- # Finding #4 (live canary, Alice): for stream-is-the-message
- # adapters (relay Slack native streaming), a draft_id bump opens
- # a brand-new platform stream per tool boundary — the user saw
- # one frozen message per segment (each stuck with the streaming
- # cursor, never sealed) plus the real final. Those adapters keep
- # ONE stream per turn: tool progress lives in the native task
- # card, and the connector's suffix-delta logic appends each new
- # segment cleanly (prefix mismatch → whole-segment append).
- # Telegram-shaped drafts (clear + separate final) keep the bump.
- if not self._stream_is_message():
- type(self)._draft_id_counter += 1
- self._draft_id = type(self)._draft_id_counter
+ # Telegram-shaped drafts: bump draft_id so the next segment animates as
+ # a fresh preview below the tool-progress bubbles instead of over the
+ # prior finalized draft. Stream-is-the-message adapters (relay Slack)
+ # keep ONE stream per turn — a bump there opened a new platform stream
+ # per tool boundary, leaving one frozen cursor-suffixed message per
+ # segment; the connector's suffix-delta logic appends segments instead.
+ if self._use_draft_streaming and not self._stream_is_message():
+ type(self)._draft_id_counter += 1
+ self._draft_id = type(self)._draft_id_counter
async def _handle_approval_boundary(self, boundary_future, cancelled_flag=None) -> None:
- """Process an approval boundary: finalize stream, disable native for post-approval.
-
- This method is called serially from run() when _APPROVAL_BOUNDARY is dequeued.
-
- Strategy: finalize the current stream with accumulated text (creating a
- stable message for pre-approval content), then disable native streaming
- so post-approval output goes through the reliable send() path.
-
- Why not keep the stream open across approval:
- - WeCom stream finalize ack only confirms server receipt, not client render.
- - Approval waits introduce an idle gap where the stream may become stale
- on the client side (no server-side 846608, but client stops tracking it).
- - If content_delivered=True but the client didn't render, the normal
- final send is suppressed → user sees nothing.
- - Approval is a natural interaction boundary; "pre-approval preamble" +
- "post-approval result" as two messages is acceptable UX.
-
- Post-approval output uses regular send() which is unconditionally reliable.
+ """Serially process an interaction boundary dequeued by run().
+
+ Finalize the current stream with accumulated text (stable message for
+ pre-prompt content), then route post-prompt output per
+ ``_boundary_reopen``. The stream is not kept open across approval
+ because the WeCom finalize ack only confirms server receipt: after a
+ long idle gap the client may stop tracking the stream, and a suppressed
+ final send would then leave the user with nothing.
"""
- # Log label ("Approval"/"Clarify") so a clarify boundary failure doesn't
- # surface as an "Approval boundary" error during troubleshooting.
- _reason = getattr(self, "_boundary_reason", "Approval") or "Approval"
+ _reason = self._boundary_reason or "Approval"
delivery_failed = False
try:
if self._native_stream_opened:
- # Finalize current stream with accumulated content.
- # This converts the typing bubble into a stable message.
finalize_text = self._accumulated or self._boundary_placeholder
finalize_ok = False
try:
@@ -947,9 +682,8 @@ class GatewayStreamConsumer:
logger.warning("%s boundary: finalize failed: %s", _reason, e)
if not finalize_ok:
- # Stream finalize didn't land — the typing bubble may still
- # be showing partial content. Fallback: deliver the pre-prompt
- # text via reliable send() so the user at least sees it.
+ # Typing bubble may still show partial content; deliver
+ # pre-prompt text via send() so the user at least sees it.
logger.warning(
"%s boundary: finalize not confirmed, "
"falling back to send() for pre-prompt text (chat=%s)",
@@ -967,8 +701,6 @@ class GatewayStreamConsumer:
_reason, send_err,
)
if not fallback_ok:
- # Both finalize and fallback failed — pre-prompt text
- # may be lost. Mark boundary as failed so the caller knows.
logger.error(
"%s boundary: both finalize and fallback send failed "
"(chat=%s) — pre-prompt text may not have been delivered",
@@ -982,45 +714,28 @@ class GatewayStreamConsumer:
)
if self._boundary_reopen:
- # Clarify boundary: KEEP native streaming enabled. The current
- # stream was finalized above (pre-prompt content is now a stable
- # bubble); marking it closed makes the next post-prompt delta
- # re-open a fresh native stream via the lazy re-seed in
- # _send_or_edit, restoring the typing-bubble experience. Do NOT
- # set buffer_only — post-prompt output should stream, not batch.
- # If the re-seed later fails, the consumer degrades to send()
- # on its own. _awaiting_reopen_after_boundary guards got_done
- # from re-seeding a stream just to emit a lone "✅" when the
- # agent produced no post-prompt content.
+ # Clarify: keep native enabled; marking the stream closed makes
+ # the next post-prompt delta re-open a fresh one via the lazy
+ # re-seed in _send_or_edit. Do NOT set buffer_only — post-prompt
+ # output should stream. The gap between this INFO and the
+ # "Re-opened native stream" INFO is the typing-reappear latency.
self._native_stream_opened = False
self._native_last_pushed_len = 0
self._awaiting_reopen_after_boundary = True
self._reset_segment_state()
- # INFO (temporary latency probe): boundary finalize is done and
- # the old bubble is closed. From here the consumer waits for
- # the LLM's first post-answer delta before re-seeding the C
- # bubble — so the gap between THIS line and the
- # "Re-opened native stream" INFO below is exactly the
- # "typing slow to reappear after clarify" delay.
logger.info(
"[latency] Clarify boundary finalized, awaiting first "
"post-answer delta to re-seed (chat=%s, turn=%s)",
self.chat_id, self._turn_id,
)
else:
- # Approval boundary: disable native streaming for post-approval
- # output, which goes through regular send() (unconditionally
- # reliable, no client-side stream state dependency). Set
- # buffer_only=True so the consumer accumulates all post-approval
- # text and delivers it in one shot on got_done, avoiding
- # mid-stream flushes that would create multiple messages on
- # non-editable platforms like WeCom.
+ # Approval: post-approval output goes via send(). buffer_only
+ # delivers it in one shot on got_done, avoiding mid-stream
+ # flushes that create multiple messages on non-editable platforms.
self._use_native_streaming = False
self._native_stream_opened = False
self._native_last_pushed_len = 0
self.cfg.buffer_only = True
-
- # Reset segment state so post-approval output starts fresh via send().
self._reset_segment_state()
boundary_ok = not delivery_failed
@@ -1029,12 +744,13 @@ class GatewayStreamConsumer:
logger.warning("%s boundary processing failed: %s", _reason, e)
boundary_ok = False
finally:
- # Resolve future so approval callback knows the result
if boundary_future is not None:
try:
- if isinstance(boundary_future, (asyncio.Future, concurrent.futures.Future)):
- if not boundary_future.done():
- boundary_future.set_result(boundary_ok)
+ if (
+ isinstance(boundary_future, (asyncio.Future, concurrent.futures.Future))
+ and not boundary_future.done()
+ ):
+ boundary_future.set_result(boundary_ok)
except Exception:
pass
@@ -1051,48 +767,35 @@ class GatewayStreamConsumer:
self.on_segment_break()
def finish(self, final_text: Optional[str] = None) -> None:
- """Signal that the stream is complete.
-
- ``final_text``, when provided, is the AUTHORITATIVE completed
- ``final_response`` — including post-stream augmentation the
- accumulator never saw (file-mutation verifier footer,
- turn-completion explainer, plugin transforms). The drain loop
- adopts it as the finalize payload so the sealed/edited message IS
- the true final and no separate corrective send is needed
- (live finding #11). Callers that cannot know the final yet
- (interrupt/error paths) call ``finish()`` bare — legacy behavior.
+ """Signal stream completion.
+
+ ``final_text`` is the AUTHORITATIVE completed final_response (incl.
+ post-stream augmentation the accumulator never saw); the drain loop
+ adopts it as the finalize payload so no corrective send is needed.
+ Interrupt/error paths that can't know the final call ``finish()`` bare.
"""
if final_text is not None:
self._queue.put((_FINAL_TEXT, final_text))
self._queue.put(_DONE)
# ── Think-block filtering ────────────────────────────────────────
- # Models like MiniMax emit inline <think>...</think> blocks in their
- # content. The CLI's _stream_delta suppresses these via a state
- # machine; we do the same here so gateway users never see raw
- # reasoning tags. The agent also strips them from the final
- # response (run_agent.py _strip_think_blocks), but the stream
- # consumer sends intermediate edits before that stripping happens.
+ # Some models emit inline <think>...</think> blocks in content. The agent
+ # strips them from the final response, but intermediate edits go out before
+ # that, so mirror the CLI's _stream_delta state machine here.
def _filter_and_accumulate(self, text: str) -> None:
- """Add a text delta to the accumulated buffer, suppressing think blocks.
+ """Append a delta to the buffer, discarding think blocks.
- Uses a state machine that tracks whether we are inside a
- reasoning/thinking block. Text inside such blocks is silently
- discarded. Partial tags at buffer boundaries are held back in
- ``_think_buffer`` until enough characters arrive to decide.
+ Partial tags at buffer boundaries are held in ``_think_buffer`` until
+ enough characters arrive to decide.
"""
buf = self._think_buffer + text
self._think_buffer = ""
while buf:
- # Case-insensitive matching: models emit mixed-case tag
- # variants (<Think>, <THINKING>, …). Match against a
- # lowercased view of the buffer with lowercased tag names so
- # every case variant is caught with a single canonical form.
+ # Case-insensitive: models emit <Think>, <THINKING>, …
lower_buf = buf.lower()
if self._in_think_block:
- # Look for the earliest closing tag
best_idx = -1
best_len = 0
for tag in self._CLOSE_THINK_TAGS:
@@ -1102,20 +805,17 @@ class GatewayStreamConsumer:
best_len = len(tag)
if best_len:
- # Found closing tag — discard block, process remainder
self._in_think_block = False
buf = buf[best_idx + best_len:]
else:
- # No closing tag yet — hold tail that could be a
- # partial closing tag prefix, discard the rest.
+ # Hold a tail that could be a partial close tag; discard the rest.
max_tag = max(len(t) for t in self._CLOSE_THINK_TAGS)
self._think_buffer = buf[-max_tag:] if len(buf) > max_tag else buf
return
else:
- # Look for earliest opening tag at a block boundary
- # (start of text / preceded by newline + optional whitespace).
- # This prevents false positives when models *mention* tags
- # in prose (e.g. "the <think> tag is used for…").
+ # Earliest opening tag at a block boundary (start of text, or
+ # newline + optional whitespace) — prose that merely *mentions*
+ # a tag must not trigger.
best_idx = -1
best_len = 0
for tag in self._OPEN_THINK_TAGS:
@@ -1150,12 +850,11 @@ class GatewayStreamConsumer:
search_start = idx + 1
if best_len:
- # Emit text before the tag, enter think block
self._append_accumulated(buf[:best_idx])
self._in_think_block = True
buf = buf[best_idx + best_len:]
else:
- # No opening tag — check for a partial tag at the tail
+ # Hold back a partial open tag at the tail.
held_back = 0
for tag in self._OPEN_THINK_TAGS:
tag_lower = tag.lower()
@@ -1166,24 +865,17 @@ class GatewayStreamConsumer:
self._append_accumulated(buf[:-held_back])
self._think_buffer = buf[-held_back:]
else:
- # No (partial) open tag — but the model may have
- # emitted an orphan close tag like </think> on its
- # own (e.g. when a thinking-mode toggle drops the
- # matched open, or when upstream stripping is
- # incomplete). Strip those before accumulating so
- # they never reach the user.
+ # An orphan </think> (thinking-mode toggle dropped the
+ # open, or incomplete upstream stripping) is noise.
self._append_accumulated(self._strip_orphan_close_tags(buf))
return
@classmethod
def _strip_orphan_close_tags(cls, text: str) -> str:
- """Remove any close tags from *text* that have no matching open.
+ """Remove close tags (plus trailing whitespace) that have no matching open.
- Mirrors ``agent/think_scrubber.py::StreamingThinkScrubber.
- _strip_orphan_close_tags`` so the progressive-display filter
- behaves the same as the post-stream final-response scrubber.
- An orphan close tag is always noise — stripped along with any
- trailing whitespace so surrounding prose flows naturally.
+ Mirrors ``agent/think_scrubber.py::StreamingThinkScrubber`` so the
+ progressive display matches the post-stream scrubber.
"""
if "</" not in text:
return text
@@ -1209,47 +901,29 @@ class GatewayStreamConsumer:
return "".join(out)
def _flush_think_buffer(self) -> None:
- """Flush any held-back partial-tag buffer into accumulated text.
-
- Called when the stream ends (got_done) so that partial text that
- was held back waiting for a possible opening tag is not lost.
- """
+ """On stream end, flush text held back waiting for a possible open tag."""
if self._think_buffer and not self._in_think_block:
- # Strip any orphan close tags that may have been held back —
- # see _filter_and_accumulate for context.
self._append_accumulated(self._strip_orphan_close_tags(self._think_buffer))
self._think_buffer = ""
async def run(self) -> None:
"""Async task that drains the queue and edits the platform message."""
- # Platform message length limit — leave room for cursor + formatting.
- # Use the adapter's length function (e.g. utf16_len for Telegram) so
- # overflow detection matches what the platform actually enforces.
- # Both resolve PER-CHAT (max_message_length_for_chat): a relay adapter
- # fronting N platforms has different caps per chat (Discord 2000 vs
- # Telegram 4096); native adapters return their scalar unchanged.
- # Gate on isinstance(BasePlatformAdapter) so test MagicMocks (whose
- # auto-attributes return mock objects, not callables) fall back to len.
+ # Length function and limit resolve PER-CHAT (a relay adapter fronting
+ # N platforms has different caps per chat) using the platform's unit
+ # (e.g. utf16 for Telegram). isinstance gate: MagicMock auto-attributes
+ # aren't callables, so test doubles fall back to len.
_len_fn: "Callable[[str], int]" = (
self.adapter.message_len_fn_for_chat(self.chat_id)
if isinstance(self.adapter, _BasePlatformAdapter)
else len
)
- # Rich-capable adapters (Telegram rich messages) raise this above the
- # legacy per-message limit so a reply that fits one rich send/draft
- # isn't fragmented at 4096 while streaming. See _raw_message_limit.
_raw_limit = self._raw_message_limit()
_safe_limit = max(500, _raw_limit - _len_fn(self.cfg.cursor) - 100)
- # Resolve transport once per run. Native streaming wins over draft
- # because the only adapters that declare it (WeCom) cannot edit
- # messages at all — there is no edit path to fall back to mid-turn.
- # When native is selected we send an empty seed frame immediately so
- # the user sees the platform's "typing" indicator before the LLM
- # produces any tokens; if that seed fails (no req_id, transport
- # error) we disable native and let the consumer take the regular
- # edit path (which will in turn refuse and fall back to fallback
- # send via the gateway, since SUPPORTS_MESSAGE_EDITING=False).
+ # Native streaming wins over draft: adapters that declare it (WeCom)
+ # cannot edit at all. Send an empty seed frame now so the user sees
+ # "typing" before the first token; on seed failure fall back to the
+ # edit path (which the gateway's fallback send then handles).
self._use_native_streaming = self._resolve_native_streaming()
if self._use_native_streaming:
logger.debug(
@@ -1264,7 +938,6 @@ class GatewayStreamConsumer:
turn_id=self._turn_id,
)
if seed_ok:
- # Mark stream as opened so fallback knows to finalize
self._native_stream_opened = True
except Exception:
logger.debug(
@@ -1275,8 +948,7 @@ class GatewayStreamConsumer:
if not seed_ok:
self._use_native_streaming = False
- # Resolve native draft streaming (Telegram drafts) only when native
- # streaming is not in use — they target the same first-frame slot.
+ # Drafts and native streaming target the same first-frame slot.
if self._use_native_streaming:
self._use_draft_streaming = False
else:
@@ -1291,14 +963,11 @@ class GatewayStreamConsumer:
try:
while True:
- # Abandon the stream early if the session has been reset
- # (e.g. /new or /stop). Prevents stale deltas from being
- # delivered after the user has already moved on.
+ # Session reset (/new, /stop): abandon rather than deliver stale deltas.
if not self._run_still_current():
await self._abandon_native_stream()
return
- # Drain all available items from the queue
got_done = False
got_segment_break = False
got_flush = False
@@ -1318,19 +987,10 @@ class GatewayStreamConsumer:
got_segment_break = True
break
if isinstance(item, tuple) and len(item) == 2 and item[0] is _FINAL_TEXT:
- # Authoritative turn-final payload (see finish()).
- # Adopt it as the finalize content so the seal /
- # final edit carries the TRUE final — including
- # post-stream augmentation (verifier footer,
- # completion explainer) the accumulator never saw.
- # Only when this consumer actually streamed
- # something this turn: a no-stream turn keeps the
- # gateway's normal final-send path (adopting here
- # would move delivery ownership for every
- # non-streaming model). Skip on a multi-message
- # split delivery: heads are already sealed on
- # screen, so adopting the full final would repeat
- # them inside the tail (#78541 shape).
+ # Adopt the authoritative final (see finish()) as the
+ # finalize content — only if this consumer streamed
+ # something (a no-stream turn keeps the gateway's
+ # normal final-send ownership).
_streamed_something = bool(
self._accumulated
or self._message_id
@@ -1343,21 +1003,13 @@ class GatewayStreamConsumer:
self._accumulated = item[1]
self._stream_ledger = item[1]
elif _streamed_something and self._turn_split_delivery:
- # Split delivery + authoritative final (review
- # r2, finding 3): wholesale adoption would
- # repeat sealed heads inside the tail (#78541),
- # but REFUSING entirely re-creates the #11
- # duplicate one level up — a post-split footer
- # never enters the ledger, delivered_final_
- # matches reports a mismatch, and the gateway
- # resends the ENTIRE body+footer. When the
- # authoritative final strictly prefix-extends
- # the split ledger, the missing suffix is the
- # only undelivered content: append it to the
- # live tail and the ledger, so the finalize
- # carries it and the recorded payload
- # reconciles. Non-prefix rewrites keep the
- # full-resend fallback (can't patch a rewrite).
+ # Split delivery: wholesale adoption would repeat
+ # sealed heads inside the tail, but refusing
+ # entirely makes the gateway resend the ENTIRE
+ # body+footer. If the final strictly
+ # prefix-extends the ledger, append only the
+ # missing suffix; non-prefix rewrites keep the
+ # full-resend fallback.
_final_raw = item[1]
_ledger = self._stream_ledger
if (
@@ -1381,17 +1033,12 @@ class GatewayStreamConsumer:
commentary_text = item[1]
break
if isinstance(item, tuple) and len(item) == 2 and item[0] is _FLUSH:
- # Flush barrier: finalize the current segment like a
- # tool boundary, then signal the waiting thread once
- # delivery for this iteration has completed (below).
+ # Barrier: finalize like a tool boundary, signal below.
got_flush = True
got_segment_break = True
flush_event = item[1]
break
if isinstance(item, tuple) and len(item) == 2 and item[0] is _TOOL_PROGRESS:
- # Tool-progress overlay: accumulate the status line.
- # Only effective in native-streaming mode (callers
- # gate before enqueue via accepts_tool_progress).
if self._use_native_streaming:
self._tool_progress_lines.append(item[1])
self._tool_progress_active = True
@@ -1400,32 +1047,20 @@ class GatewayStreamConsumer:
except queue.Empty:
break
- # Handle approval boundary: close current stream, reset for new turn.
- # Must happen before got_done/segment_break processing since it
- # produces its own finalize and resets state.
+ # Boundary produces its own finalize and resets state, so it
+ # must run before got_done/segment_break processing.
if got_approval_boundary:
await self._handle_approval_boundary(
approval_boundary_future, approval_boundary_cancelled
)
continue
- # Handle eager re-seed: the user just answered a clarify prompt.
- # Open a fresh native stream NOW (empty seed frame) so the WeCom
- # typing bubble reappears immediately, without waiting for the
- # LLM's first post-answer delta. Only meaningful in the
- # reopen-pending state with native still live and no stream open;
- # request_reopen_seed() already gates on that, and we re-check
- # here because state may have advanced between put and dequeue.
- #
- # TRADE-OFF: this moves the start of WeCom's ~6-minute stream
- # session limit (STREAM_EXPIRED_ERRCODE 846608, counted from the
- # FIRST frame, not renewed by intermediate frames) forward from
- # the first post-answer delta to the user-reply instant — the
- # effective window shrinks by however long the LLM takes to
- # produce its first token. A first token >5min is very rare, and
- # if the stream does expire send_stream_frame returns False and
- # the else branch below degrades to send(), so the answer still
- # lands (only the streaming animation is lost). Acceptable.
+ # Eager re-seed after a clarify answer. Re-check the gate
+ # (state may have advanced between put and dequeue). Trade-off:
+ # WeCom's ~6-minute stream limit (errcode 846608, counted from
+ # the FIRST frame) now starts at the reply instant rather than
+ # the first post-answer delta; if it expires, send_stream_frame
+ # returns False and we degrade to send() — only animation is lost.
if got_reopen_seed:
if (
self._use_native_streaming
@@ -1455,32 +1090,20 @@ class GatewayStreamConsumer:
self._turn_id,
)
else:
- # Seed failed — degrade to a single buffered send()
- # so the post-answer content still lands as one
- # bubble (not per-tick fragments on a non-editable
- # platform). Mirrors the approval-boundary degrade.
+ # Degrade to a single buffered send() (one bubble,
+ # not per-tick fragments), like the approval path.
self._use_native_streaming = False
self._native_stream_opened = False
self._native_last_pushed_len = 0
self.cfg.buffer_only = True
continue
- # Flush any held-back partial-tag buffer on stream end
- # so trailing text that was waiting for a potential open
- # tag is not lost.
if got_done:
self._flush_think_buffer()
- # Intentional-silence suppression. When the agent chose
- # not to reply it emits a bare control marker (NO_REPLY /
- # [SILENT] / …). The gateway's whole-response filter
- # (gateway/run.py) suppresses this on the non-streaming
- # path, but by the time it runs the stream consumer has
- # already edited the raw marker onto the screen. Detect
- # the exact-marker final buffer here and retract any
- # preview instead of finalizing it, so the marker never
- # reaches the chat. Substantive prose that merely mentions
- # a marker is NOT suppressed (see is_intentional_silence_response).
+ # A bare intentional-silence marker (NO_REPLY / [SILENT]):
+ # the gateway's whole-response filter runs too late for a
+ # streamed preview, so retract it here instead of finalizing.
if _is_intentional_silence_response(
self._clean_for_display(self._accumulated)
):
@@ -1497,39 +1120,28 @@ class GatewayStreamConsumer:
)
if not self.cfg.buffer_only:
if self._use_native_streaming:
- # Fire-and-forget: native streaming has no platform
- # edit-rate limit — push every accumulated delta
- # immediately. The only gate is "have we accumulated
- # anything new at all".
+ # No platform edit-rate limit: push every delta immediately.
should_edit = should_edit or bool(self._accumulated) or self._tool_progress_active
else:
should_edit = should_edit or (
(elapsed >= self._current_edit_interval
and self._accumulated)
- # buffer_threshold is intentionally codepoint-based:
- # it's a debounce heuristic ("send updates roughly
- # every N visible characters"), not a platform-limit
- # check. _len_fn is reserved for overflow detection.
+ # buffer_threshold is a codepoint debounce heuristic,
+ # not a platform-limit check (_len_fn is for overflow).
or len(self._accumulated) >= self.cfg.buffer_threshold
)
current_update_visible = False
- # Whether the got_done update below was delivered as a FRESH
- # persistent send through the native-draft transport (drafts
- # have no message id, so the finalize tick is a brand-new
- # send that already carried finalize=True). Distinguishes
- # that case from an EDIT issued while draft streaming is
- # active, which must keep the legacy explicit-finalize pass
- # for REQUIRES_EDIT_FINALIZE adapters.
+ # got_done update went out as a FRESH send via the draft
+ # transport (drafts have no message id) already carrying
+ # finalize=True — unlike an EDIT during draft streaming, which
+ # still needs the explicit finalize pass for
+ # REQUIRES_EDIT_FINALIZE adapters.
draft_final_fresh_send = False
- # Hold back mid-stream edits while the buffer so far could
- # still resolve to an intentional-silence marker. Without
- # this, a partial marker (e.g. "NO_REPLY" streamed as
- # "NO"→"NO_REPLY") would flash onto the screen on an interval
- # tick before got_done can suppress it. Only defers display —
- # got_done above always resolves the buffer (suppress if it's
- # an exact marker, otherwise fall through and flush normally),
- # so genuine prose that merely starts marker-like is never lost.
+ # Defer mid-stream edits while the buffer could still resolve
+ # to a silence marker ("NO"→"NO_REPLY") so it never flashes on
+ # screen; got_done always resolves the buffer, so marker-like
+ # prose is never lost.
if (
should_edit
and not got_done
@@ -1541,30 +1153,21 @@ class GatewayStreamConsumer:
):
should_edit = False
if should_edit and (self._accumulated or (self._use_native_streaming and self._tool_progress_active)):
- # Split overflow: if accumulated text exceeds the platform
- # limit, split into properly sized chunks.
- # Native streaming bypasses this entirely — the adapter's
- # send_stream_frame handles byte-level truncation against
- # the stream protocol's larger limit (e.g. WeCom's 20480
- # bytes vs. MAX_MESSAGE_LENGTH's 4000 codepoints).
+ # Overflow split. Native streaming bypasses this: the
+ # adapter truncates against the stream protocol's own limit.
if (
not self._use_native_streaming
and _len_fn(self._accumulated) > _safe_limit
and self._message_id is None
):
- # No existing message to edit (first message or after a
- # segment break). Seal only the overflowing head chunks
- # as fixed messages, then keep the trailing chunk in
- # _accumulated so the normal send/edit path below makes
- # it the active preview. That lets chunk 2, 3, ... keep
- # updating in-place as later streamed deltas arrive
- # instead of posting every split as an immutable message.
+ # No message to edit yet: seal only the overflowing head
+ # chunks, keep the tail in _accumulated so it becomes the
+ # active preview that later deltas edit in place.
chunks = self._truncate_for_stream(
self._accumulated, _safe_limit, _len_fn,
)
if len(chunks) <= 1:
- # A malformed/legacy adapter result must not leave
- # this overflow branch with an unsplittable payload.
+ # Malformed/legacy adapter result must still be splittable.
chunks = self._split_text_chunks(
self._accumulated, _safe_limit, _len_fn,
)
@@ -1578,9 +1181,7 @@ class GatewayStreamConsumer:
final=got_done,
)
if new_id is None or new_id == reply_to:
- # Failed to deliver a sealed head; keep the
- # full accumulated text intact so the gateway's
- # fallback path can still deliver it completely.
+ # Keep the full text intact for the gateway fallback.
all_heads_delivered = False
chunks_delivered = False
break
@@ -1589,28 +1190,18 @@ class GatewayStreamConsumer:
if all_heads_delivered:
self._accumulated = chunks[-1]
- # The head chunks are sealed. Clear the edit target
- # so the remaining tail is sent as a fresh active
- # chunk, then edited by subsequent deltas.
- self._message_id = None
- self._message_created_ts = None
- self._last_sent_text = ""
- else:
- # A prior head may have landed before a later head
- # failed. Do not edit that sealed message with the
- # unsplit full payload; let the fallback path retry.
- self._message_id = None
- self._message_created_ts = None
- self._last_sent_text = ""
+ # Heads are sealed (or a later head failed): never edit a
+ # sealed message with the unsplit payload — the tail is
+ # sent fresh, or the fallback path retries.
+ self._message_id = None
+ self._message_created_ts = None
+ self._last_sent_text = ""
if chunks_delivered:
- # A sealed head is on screen, so this turn is now a
- # multi-message delivery. Flag it BEFORE the tail
- # send below: the fresh-final route replaces every
- # tracked preview with one message, which is only
- # valid while the active message holds the whole
- # answer. Once heads are sealed it does not, and
- # deleting them would drop delivered text (#78541).
+ # Flag BEFORE the tail send: fresh-final replaces
+ # every tracked preview with one message, which is
+ # only valid while the active message holds the whole
+ # answer — deleting sealed heads drops delivered text.
self._turn_split_delivery = True
self._last_edit_time = time.monotonic()
@@ -1620,16 +1211,11 @@ class GatewayStreamConsumer:
tail_delivered = await self._send_or_edit(
self._accumulated, finalize=True,
)
- # Only claim final delivery if the sealed chunks and
- # final tail actually landed. ``_already_sent`` may
- # be True from prior progress/fallback state (#10748).
+ # ``_already_sent`` may be True from prior
+ # progress/fallback state — only heads + tail count.
self._final_response_sent = chunks_delivered and tail_delivered
if self._final_response_sent:
self._final_content_delivered = True
- # Multi-message split delivery — record the
- # unsplit ledger payload so the gateway can
- # still reconcile against final_response
- # (#71643, #78541).
self._turn_split_delivery = True
self._record_turn_final_payload(self._accumulated)
return
@@ -1640,16 +1226,12 @@ class GatewayStreamConsumer:
if not self._accumulated:
continue
- # This iteration consumed a _FLUSH barrier and delivered
- # the buffered prose via the chunk loop above, then takes
- # an early `continue` that skips the bottom-of-loop set.
- # Signal here so flush_pending_sync() doesn't stall the
- # full timeout waiting on already-delivered content.
+ # Early `continue` skips the bottom-of-loop flush signal.
if got_flush:
self._signal_flush(flush_event)
continue
- # Existing message: edit it with the first chunk, then
- # start a new message for the overflow remainder.
+ # Existing message: seal it with the head, start a new
+ # message for the remainder.
while (
_len_fn(self._accumulated) > _safe_limit
and self._message_id is not None
@@ -1662,38 +1244,23 @@ class GatewayStreamConsumer:
if split_at < _cp_budget // 2:
split_at = _cp_budget
chunk = self._accumulated[:split_at]
- # finalize=True so the adapter applies platform-specific
- # rich-text markup (e.g. Telegram MarkdownV2). This
- # sealed chunk will never be edited again — _message_id
- # is reset to None right below — so it must receive its
- # final formatting pass now, or early split messages
- # render raw markdown while only the last chunk renders.
- # is_turn_final=False: this is the first of several split
- # messages, NOT the turn-final answer, so the fresh-final
- # path (opt-in fresh_final_after_seconds) must not mark
- # the turn delivered on it (#29346 semantics).
+ # finalize=True: this sealed chunk is never edited again,
+ # so it needs its rich-text pass now or it renders raw.
+ # is_turn_final=False: a split head is not the answer, so
+ # fresh-final must not mark the turn delivered on it.
ok = await self._send_or_edit(
chunk, finalize=True, is_turn_final=False,
)
if self._fallback_final_send or not ok:
- # Edit failed (or backed off due to flood control)
- # while attempting to split an oversized message.
- # Keep the full accumulated text intact so the
- # fallback final-send path can deliver the remaining
- # continuation without dropping content.
+ # Keep the full text intact for the fallback final send.
break
self._accumulated = self._accumulated[split_at:].lstrip("\n")
self._message_id = None
self._last_sent_text = ""
- # Sealed head chunk delivered — this turn is now a
- # multi-message delivery (#71643 record semantics).
self._turn_split_delivery = True
display_text = self._accumulated
if not got_done and not got_segment_break and commentary_text is None:
- # Native streaming with tool-progress: compose frame
- # content that includes tool status overlay. The cursor
- # is appended to the composed content for consistency.
if self._use_native_streaming:
display_text = self._compose_frame_content()
if display_text and self.cfg.cursor:
@@ -1701,12 +1268,9 @@ class GatewayStreamConsumer:
else:
display_text += self.cfg.cursor
- # Segment break: finalize the current message so platforms
- # that need explicit closure (e.g. DingTalk AI Cards) don't
- # leave the previous segment stuck in a loading state when
- # the next segment (tool progress, next chunk) creates a
- # new message below it. got_done has its own finalize
- # path below so we don't finalize here for it.
+ # Segment break finalizes so platforms needing explicit
+ # closure (DingTalk AI Cards) don't leave the previous
+ # segment stuck loading; got_done has its own finalize below.
draft_final_fresh_send = (
got_done
and self._use_draft_streaming
@@ -1715,38 +1279,28 @@ class GatewayStreamConsumer:
current_update_visible = await self._send_or_edit(
display_text,
finalize=(got_done or got_segment_break),
- # A segment-break finalize closes a preamble, not the
- # turn-final answer — only got_done marks delivered (#29346).
+ # A segment-break finalize closes a preamble, not the answer.
is_turn_final=got_done,
)
self._last_edit_time = time.monotonic()
- # Reset tool_progress_active flag after frame delivery —
- # the lines are still in _tool_progress_lines (for the next
- # frame's compose) but we don't need to trigger another
- # should_edit until new progress arrives.
+ # Lines stay in _tool_progress_lines for the next compose;
+ # only new progress should trigger another should_edit.
if self._tool_progress_active:
self._tool_progress_active = False
if got_done:
if self._accumulated or self._message_id is not None or self._already_sent:
await self._notify_before_finalize()
- # Final edit without cursor. If progressive editing failed
- # mid-stream, send a single continuation/fallback message
- # here instead of letting the base gateway path send the
- # full response again.
+ # Final edit without cursor; if progressive editing failed
+ # mid-stream, send one continuation here rather than letting
+ # the gateway resend the full response.
if (
self._awaiting_reopen_after_boundary
and not self._native_stream_opened
and not self._accumulated
):
- # Clarify reopen boundary (LAZY path), but the agent
- # produced no post-prompt content. The pre-prompt stream
- # was already finalized into a stable bubble at the
- # boundary, and no fresh stream was ever re-seeded, so
- # there is nothing on screen to close. Do NOT re-seed a
- # fresh stream just to emit a lone "✅" placeholder — that
- # would leave a meaningless empty bubble below the
- # question. Close quietly; the finalized bubble stands.
+ # Lazy reopen, no post-prompt content: nothing is open
+ # on screen, so don't re-seed just to emit a lone "✅".
logger.debug(
"Clarify reopen boundary with no post-prompt content "
"— skipping lone-placeholder finalize (turn=%s)",
@@ -1758,15 +1312,9 @@ class GatewayStreamConsumer:
and not self._accumulated
and not current_update_visible
):
- # EAGER-seed path: the typing bubble is ALREADY on screen
- # (opened the instant the user answered), but the agent
- # then produced no content. Unlike the lazy case we
- # cannot skip — an open, empty typing bubble would hang
- # forever. Close it with an empty finalize (NOT a lone
- # "✅", which would be a meaningless bubble below the
- # question). Leave the delivery flags as-is: nothing
- # substantive was delivered, so the gateway's own
- # whole-response filter still governs any fallback.
+ # Eager seed, no content: the typing bubble IS on screen
+ # and would hang forever — close it with an empty
+ # finalize (not a lone "✅"). Delivery flags untouched.
try:
await self.adapter.send_stream_frame(
"",
@@ -1781,10 +1329,6 @@ class GatewayStreamConsumer:
)
self._native_stream_opened = False
self._native_last_pushed_len = 0
- # Reset for symmetry with _suppress_silence_marker; the
- # consumer is per-turn today so this is defensive, but it
- # keeps the flag from leaking if a consumer is ever reused
- # across turns.
self._reopen_seeded_eagerly = False
logger.debug(
"Eager reopen seed but no post-answer content — "
@@ -1792,10 +1336,8 @@ class GatewayStreamConsumer:
self._turn_id,
)
elif self._use_native_streaming:
- # Native streaming MUST always close the stream with
- # finish=true — even when _accumulated is empty (e.g.
- # tool-only turns with no text output). Mirror OpenClaw's
- # finishThinkingStream: use a placeholder if needed.
+ # Native streams MUST close with finish=true even when
+ # empty (tool-only turns) — placeholder if needed.
if not current_update_visible:
close_text = self._accumulated or "✅"
self._final_response_sent = await self._send_or_edit(
@@ -1810,12 +1352,8 @@ class GatewayStreamConsumer:
if self._fallback_final_send:
await self._send_fallback_final(self._accumulated)
elif self._final_response_sent:
- # A finalize=True tick above already delivered the
- # final answer via the adapter's fresh-final path
- # (_try_fresh_final sent a fresh rich message and
- # deleted the preview). Running a second finalize
- # edit here would duplicate the message / re-delete,
- # so just record delivery and stop.
+ # Fresh-final already delivered above; a second
+ # finalize would duplicate / re-delete.
self._final_content_delivered = True
self._record_turn_final_payload(self._accumulated)
elif (
@@ -1826,34 +1364,16 @@ class GatewayStreamConsumer:
or draft_final_fresh_send
)
):
- # The update above already delivered the final
- # accumulated content. Native drafts have no
- # message id, so their got_done update is a fresh,
- # persistent send with finalize=True; running the
- # adapter's explicit finalize hook immediately
- # afterward would edit that already-final message
- # a second time. This is especially harmful for
- # Telegram, where a successful sendRichMessage was
- # being followed by editMessageText and could fall
- # back to the legacy table-to-bullets formatter.
- #
- # Also skip the redundant final edit for adapters
- # that don't need an explicit finalize signal, and
- # for any adapter when the update split-and-
- # delivered across continuations: that update
- # carried finalize=True itself, and re-finalizing
- # with the full text would overflow-split again into
- # the adopted continuation, duplicating chunks.
- #
- # Delivery is recorded via the shared helper so
- # the recorded payload is the last ACKED edit,
- # not the accumulated text (frozen-preview
- # incident class; see _mark_skip_redundant_finalize).
+ # The update above already delivered the final. A
+ # second finalize would re-edit an already-final
+ # message (Telegram: sendRichMessage followed by
+ # editMessageText falls back to the legacy
+ # formatter), or overflow-split again into an
+ # adopted continuation, duplicating chunks.
self._mark_skip_redundant_finalize()
elif self._message_id:
- # Either the mid-stream edit didn't run (no
- # visible update this tick) OR the adapter needs
- # explicit finalize=True to close the stream.
+ # No visible update this tick, or the adapter needs
+ # explicit finalize=True.
self._final_response_sent = await self._send_or_edit(
self._accumulated, finalize=True,
)
@@ -1861,23 +1381,17 @@ class GatewayStreamConsumer:
self._final_content_delivered = True
self._record_turn_final_payload(self._accumulated)
elif self._fallback_final_send:
- # The final edit attempt itself may be the one
- # that exhausts flood-control strikes and
- # promotes the consumer into fallback mode. Do
- # not return to the gateway with a full-response
- # fallback still pending; send only the unsent
- # tail here so the normal gateway send path does
- # not duplicate the visible prefix.
+ # This edit may have exhausted flood strikes and
+ # promoted fallback mode; send only the unsent
+ # tail now so the gateway doesn't duplicate the
+ # visible prefix.
await self._send_fallback_final(self._accumulated)
elif not self._already_sent:
- # Turn-final retry after the finalize tick above
- # failed (transport error, seal exception).
- # finalize=True so a stream-is-the-message adapter
- # can never route this through the draft-frame
- # branch: its no-op dedupe compares against the
- # last UNSEALED frame and would report success
- # without any transport call, recording a final
- # the user never received (silent-loss class).
+ # Retry after the finalize tick failed. finalize=True
+ # keeps stream-is-the-message adapters out of the
+ # draft-frame branch, whose dedupe against the last
+ # UNSEALED frame would report success with no
+ # transport call (silent loss).
self._final_response_sent = await self._send_or_edit(
self._accumulated, finalize=True,
)
@@ -1887,23 +1401,13 @@ class GatewayStreamConsumer:
return
if commentary_text is not None:
- # Stream-is-the-message adapters: commentary posts as its
- # own message (no notify → no seal-interception), and the
- # native stream continues cumulatively. Resetting here
- # would break the append-only invariant the connector's
- # delta computation depends on (whole-snapshot re-append).
- _stream_is_msg_c = self._stream_is_message()
- if _stream_is_msg_c and self._use_draft_streaming:
- await self._send_commentary(commentary_text)
- self._last_edit_time = time.monotonic()
- elif self._use_native_streaming:
- # Native streaming (WeCom): commentary is sent as an
- # independent message via adapter.send(), but we must
- # NOT reset _accumulated — the native stream is
- # cumulative and a reset would lose all pre-commentary
- # text. Subsequent frames must still carry the full
- # accumulated content. Same rationale as segment-break
- # no-op for native streaming.
+ # Cumulative transports (stream-is-the-message drafts, WeCom
+ # native): commentary posts as its own message and the
+ # stream continues — resetting _accumulated would break the
+ # append-only invariant / lose pre-commentary text.
+ if (
+ self._stream_is_message() and self._use_draft_streaming
+ ) or self._use_native_streaming:
await self._send_commentary(commentary_text)
self._last_edit_time = time.monotonic()
else:
@@ -1912,50 +1416,27 @@ class GatewayStreamConsumer:
self._last_edit_time = time.monotonic()
self._reset_segment_state()
- # Tool boundary: for edit-based platforms, reset message state
- # so the next text chunk creates a fresh message below tool-progress.
- # For WeCom native streaming: NO reset — stream uses cumulative text,
- # so resetting would lose pre-boundary content in subsequent frames.
- #
- # Exception: when _message_id is "__no_edit__" the platform
- # never returned a real message ID (e.g. Signal, webhook with
- # github_comment delivery). Resetting to None would re-enter
- # the "first send" path on every tool boundary and post one
- # platform message per tool call — that is what caused 155
- # comments under a single PR. Instead, preserve the sentinel
- # so the full continuation is delivered once via
- # _send_fallback_final.
- # (When editing fails mid-stream due to flood control the id is
- # a real string like "msg_1", not "__no_edit__", so that case
- # still resets and creates a fresh segment as intended.)
+ # Tool boundary: edit-based transports reset so the next chunk
+ # is a fresh message below tool progress. Cumulative transports
+ # (stream-is-the-message drafts, WeCom native) must NOT reset —
+ # clearing _accumulated makes the next frame a non-prefix
+ # snapshot and the connector re-appends the whole answer.
+ # preserve_no_edit: "__no_edit__" (platform never returned a
+ # real id — Signal, github_comment webhook) must keep its
+ # sentinel or every tool boundary posts a new message (155
+ # comments on one PR); the continuation goes out once via
+ # _send_fallback_final. A real id from a flood-failed edit
+ # still resets as intended.
if got_segment_break:
- # Stream-is-the-message adapters keep one cumulative native
- # stream for the whole turn. Clearing _accumulated here makes
- # the next frame a non-prefix snapshot, so the connector's
- # append fallback repeats the entire answer at every tool
- # boundary. Preserve all stream state; only non-native draft
- # and edit-based transports start a new segment.
- # ``is True`` + _use_draft_streaming: MagicMock adapters
- # return truthy auto-attributes, and an edit-based run on a
- # stream-capable adapter still needs the legacy reset.
- # WeCom native streaming also uses cumulative text — each
- # frame must carry the full content so far, so a segment
- # break must NOT reset accumulated state or subsequent
- # frames lose the pre-boundary text.
if (
self._stream_is_message()
and self._use_draft_streaming
) or self._use_native_streaming:
pass
else:
- # If the segment-break edit failed to deliver the
- # accumulated content (flood control that has not yet
- # promoted to fallback mode, or fallback mode itself),
- # _accumulated still holds pre-boundary text the user
- # never saw. Flush that tail as a continuation message
- # before the reset below wipes _accumulated — otherwise
- # text generated before the tool boundary is silently
- # dropped (issue #8124).
+ # If the segment-break edit didn't land (flood control /
+ # fallback mode), _accumulated holds unseen pre-boundary
+ # text — flush it before the reset wipes it.
if (
self._accumulated
and not current_update_visible
@@ -1965,23 +1446,18 @@ class GatewayStreamConsumer:
await self._flush_segment_tail_on_edit_failure()
self._reset_segment_state(preserve_no_edit=True)
- # Flush barrier satisfied: the buffered segment (if any) has now
- # been finalized and delivered above, so wake the thread blocked
- # in flush_pending_sync(). Done last so the waiter only unblocks
- # once everything queued before the barrier is on screen.
+ # Done last so the waiter unblocks only once everything queued
+ # before the barrier is on screen.
if got_flush:
self._signal_flush(flush_event)
await asyncio.sleep(0.05) # Small yield to not busy-loop
except asyncio.CancelledError:
- # Best-effort final edit on cancellation. finalize=True so
- # REQUIRES_EDIT_FINALIZE platforms (Telegram) apply final
- # formatting — a plain edit here would leave the entire reply
- # rendered as a raw streaming preview while the success flags
- # below suppress the gateway's formatted re-send.
- # is_turn_final=False keeps _try_fresh_final from setting
- # _final_response_sent itself; this handler owns the flags.
+ # Best-effort final edit. finalize=True so REQUIRES_EDIT_FINALIZE
+ # platforms apply formatting (the flags below suppress the gateway's
+ # formatted re-send); is_turn_final=False because this handler owns
+ # the flags, not _try_fresh_final.
_best_effort_ok = False
if self._accumulated and self._message_id:
with contextlib.suppress(Exception):
@@ -1991,20 +1467,13 @@ class GatewayStreamConsumer:
)
)
elif self._message_id is None:
- # Native draft path deliberately keeps _message_id=None, so
- # the best-effort edit above never runs for it — the stream
- # stayed visibly live (streaming indicator) forever and the
- # adapter kept armed interception state for the next turn
- # to inherit (review B8). Seal in place with what's already
- # on screen; sets no delivery flags.
+ # Draft path keeps _message_id=None, so the edit above never
+ # runs for it; seal in place (else the stream stays visibly
+ # live and the adapter keeps armed interception state for the
+ # next turn). Sets no delivery flags.
await self._abandon_native_stream()
- # Only confirm final delivery if the best-effort send above
- # actually succeeded OR if the final response was already
- # confirmed before we were cancelled. Previously this
- # promoted any partial send (already_sent=True) to
- # final_response_sent — which suppressed the gateway's
- # fallback send even when only intermediate text (e.g.
- # "Let me search…") had been delivered, not the real answer.
+ # Only a successful best-effort edit confirms delivery — a partial
+ # send (already_sent) may be just "Let me search…", not the answer.
if _best_effort_ok and not self._final_response_sent:
self._final_response_sent = True
self._final_content_delivered = True
@@ -2012,12 +1481,8 @@ class GatewayStreamConsumer:
except Exception as e:
logger.error("Stream consumer error: %s", e)
finally:
- # Safety net: if run() exits (normal return, cancellation, or
- # exception) while a _FLUSH barrier is still queued or was consumed
- # but not yet signaled, wake any waiters now. Without this a caller
- # blocked in flush_pending_sync() would stall the full timeout when
- # the consumer dies mid-flush. Bounded either way, but this makes
- # the common case instant instead of timeout-delayed.
+ # Wake any still-queued _FLUSH waiters so a consumer dying mid-flush
+ # doesn't stall flush_pending_sync() for its full timeout.
try:
while True:
item = self._queue.get_nowait()
@@ -2032,25 +1497,13 @@ class GatewayStreamConsumer:
except Exception:
pass
- # Strip MEDIA:<path> tags before display. Uses the shared anchored
- # MEDIA_TAG_CLEANUP_RE from gateway/platforms/base.py — only tags whose
- # path ends in a deliverable extension are removed, so an unknown-extension
- # path stays visible instead of being silently dropped (issue #34517).
- # Streaming and non-streaming paths share the same regex, so a tag is
- # treated identically whichever path delivered the text.
+ # Shared with the non-streaming path so a MEDIA tag is treated identically
+ # either way (only deliverable-extension paths are stripped).
_MEDIA_RE = MEDIA_TAG_CLEANUP_RE
@staticmethod
def _clean_for_display(text: str) -> str:
- """Strip MEDIA: directives and internal markers from text before display.
-
- The streaming path delivers raw text chunks that may include
- ``MEDIA:<path>`` tags and ``[[audio_as_voice]]`` directives meant for
- the platform adapter's post-processing. The actual media files are
- delivered separately via ``_deliver_media_from_response()`` after the
- stream finishes — we just need to hide the raw directives from the
- user.
- """
+ """Hide MEDIA:<path> / [[audio_as_voice]] directives; media is delivered after the stream."""
return _BasePlatformAdapter.strip_media_directives_for_display(text)
async def _send_new_chunk(
@@ -2060,10 +1513,7 @@ class GatewayStreamConsumer:
*,
final: bool = False,
) -> Optional[str]:
- """Send a new message chunk, optionally threaded to a previous message.
-
- Returns the message_id so callers can thread subsequent chunks.
- """
+ """Send a new chunk threaded to ``reply_to_id``; returns the new message_id."""
text = self._clean_for_display(text)
if not text.strip():
return reply_to_id
@@ -2082,8 +1532,6 @@ class GatewayStreamConsumer:
self._track_preview_ids_from_result(result)
self._already_sent = True
self._last_sent_text = text
- # Fresh content bubble — close off any stale tool bubble
- # above so the next tool starts a new bubble below.
self._notify_new_message()
return str(result.message_id)
else:
@@ -2107,34 +1555,13 @@ class GatewayStreamConsumer:
return final_text[len(prefix):].lstrip()
return final_text
- @staticmethod
- def _balance_fences_across_chunks(chunks: "list[str]") -> "list[str]":
- """Close orphaned ``` fences at each chunk boundary and reopen on the next.
-
- Thin delegate to the shared fence-chunker core in
- :mod:`gateway.platforms.helpers` (``balance_fences_across_chunks``);
- kept as a method for the existing call sites and tests.
- """
- from gateway.platforms.helpers import balance_fences_across_chunks
-
- return balance_fences_across_chunks(chunks)
-
@staticmethod
def _split_text_chunks(
text: str,
limit: int,
len_fn: "Callable[[str], int]" = len,
) -> list[str]:
- """Split text into reasonably sized chunks for fallback sends.
-
- Chunks are fence-balanced: a split inside a ``` code block closes the
- fence on the head chunk and reopens it on the tail, so no chunk leaves
- the rest of a message rendering as one giant code block.
-
- Delegates to the shared fence-chunker core
- (:func:`gateway.platforms.helpers.split_text_fence_aware`) with this
- consumer's knobs: newline-preferred splitting + fence balancing.
- """
+ """Split text for fallback sends: newline-preferred, fence-balanced across chunks."""
from gateway.platforms.helpers import split_text_fence_aware
return split_text_fence_aware(
@@ -2151,12 +1578,9 @@ class GatewayStreamConsumer:
limit: int,
len_fn: "Callable[[str], int]",
) -> list[str]:
- """Use the adapter's canonical splitter for streaming overflow.
+ """Split via the adapter's canonical truncate_message (platform-specific rules).
- Platform adapters may add word-boundary, code-fence, table, or
- platform-specific formatting rules. The consumer must not replace
- those rules with newline-only slicing. Non-base test doubles and
- legacy adapters retain the historical two-argument call shape.
+ Non-base test doubles / legacy adapters keep the two-argument call shape.
"""
truncate = getattr(self.adapter, "truncate_message", None)
if not callable(truncate):
@@ -2178,17 +1602,14 @@ class GatewayStreamConsumer:
Retries each chunk once on flood-control failures with a short delay.
"""
final_text = self._clean_for_display(text)
- # Ensure balanced code fences before computing continuation,
- # so the closing fence reaches the user even when the fallback
- # only delivers the tail after mid-stream edits failed.
+ # Balance fences BEFORE computing the continuation so the closing
+ # fence reaches the user even when only the tail is delivered.
final_text = ensure_closed_code_fences(final_text)
continuation = self._continuation_text(final_text)
self._fallback_final_send = False
if not continuation.strip():
- # Some platforms treat a successful streaming preview as durable
- # delivery. Telegram clients can instead lose or retain only part
- # of that preview after a failed final edit, so opt-in adapters
- # commit the completed answer with a fresh final send.
+ # Telegram clients can lose (part of) a streamed preview after a
+ # failed final edit, so opt-in adapters commit a fresh final send.
if (
final_text.strip()
and final_text == self._visible_prefix()
@@ -2205,44 +1626,28 @@ class GatewayStreamConsumer:
self._fallback_prefix = ""
self._fallback_preserve_partial_messages = False
if delivery in {"ambiguous", "preview"}:
- # A timeout may mean Telegram accepted the send but the
- # client never received the response. A flood rejection
- # leaves the complete, ACKed preview as the authoritative
- # delivery. Preserve duplicate suppression in both cases.
+ # Timeout: Telegram may have accepted the send. Flood
+ # rejection: the complete ACKed preview is authoritative.
+ # Keep duplicate suppression in both cases.
self._final_content_delivered = True
if delivery == "preview":
- # This branch is only reached when the ACKed preview
- # already shows the complete final text
- # (final_text == _visible_prefix()), so record it as
- # the turn-final payload: the gateway's reconciliation
- # then confirms delivery instead of re-sending a
- # second bubble next to the never-deleted preview
- # (#71047 Problem B).
+ # Preview already shows the full final (checked above);
+ # record it so the gateway doesn't re-send next to it.
self._record_turn_final_payload(final_text)
else:
self._delivery_ambiguous = True
else:
- # A confirmed failure leaves the gateway free to perform
- # its normal final send.
+ # Confirmed failure: gateway performs its normal final send.
self._final_response_sent = False
self._final_content_delivered = False
return
- # Nothing new to send — the visible partial already matches final text.
- # BUT: if final_text itself has meaningful content (e.g. a timeout
- # message after a long tool call), the prefix-based continuation
- # calculation may wrongly conclude "already shown" because the
- # streamed prefix was from a *previous* segment (before the tool
- # boundary). In that case, send the full final_text as-is (#10807).
+ # The prefix may be from a *previous* segment (before a tool
+ # boundary), wrongly reading as "already shown" — send final_text as-is.
if final_text.strip() and final_text != self._visible_prefix():
continuation = final_text
else:
- # Defence-in-depth for #7183: the last edit may still show the
- # cursor character because fallback mode was entered after an
- # edit failure left it stuck. Try one final edit to strip it
- # so the message doesn't freeze with a visible ▉. Best-effort
- # — if this edit also fails (flood control still active),
- # _try_strip_cursor has already been called on fallback entry
- # and the adaptive-backoff retries will have had their shot.
+ # Best-effort strip of a cursor left stuck by the edit failure
+ # that entered fallback mode.
if (
self._message_id
and self._last_sent_text
@@ -2262,11 +1667,7 @@ class GatewayStreamConsumer:
self._already_sent = True
self._final_response_sent = True
self._final_content_delivered = True
- # The visible partial equals the complete final text (#71643).
- # Route through the recorder so a split turn records the full
- # ledger rather than this tail-only payload — an unrecorded or
- # tail-only split now reads as a mismatch and would re-send
- # text the user already has (#78541).
+ # Recorder substitutes the full ledger on a split turn.
self._record_turn_final_payload(final_text)
return
@@ -2276,9 +1677,7 @@ class GatewayStreamConsumer:
if isinstance(self.adapter, _BasePlatformAdapter)
else len
)
- # Per-chat resolution (relay adapter fronting N platforms): the cap and
- # length unit follow the chat's underlying platform, not the adapter
- # scalar. Native adapters return their scalar/property unchanged.
+ # Per-chat cap/unit (relay adapter fronting N platforms).
if isinstance(self.adapter, _BasePlatformAdapter):
try:
raw_limit = self.adapter.max_message_length_for_chat(self.chat_id)
@@ -2293,7 +1692,6 @@ class GatewayStreamConsumer:
last_successful_chunk = ""
sent_any_chunk = False
for chunk in chunks:
- # Try sending with one retry on flood-control errors.
result = None
for attempt in range(2):
result = await self.adapter.send(
@@ -2315,19 +1713,15 @@ class GatewayStreamConsumer:
if not result or not result.success:
if sent_any_chunk:
- # Some continuation text already reached the user, but not
- # the full response. Do NOT set _final_response_sent — the
- # base gateway final-send path should still deliver the
- # complete response so the user gets the full answer.
- # Suppress only _already_sent to avoid a duplicate send
- # of the same partial content.
+ # Partial continuation landed: do NOT set _final_response_sent
+ # (gateway must still deliver the full answer); _already_sent
+ # only prevents a duplicate of the partial.
self._already_sent = True
self._message_id = last_message_id
self._last_sent_text = last_successful_chunk
self._fallback_prefix = ""
return
- # No fallback chunk reached the user — allow the normal gateway
- # final-send path to try one more time.
+ # Nothing landed — let the gateway final send try once more.
self._already_sent = False
self._message_id = None
self._last_sent_text = ""
@@ -2336,20 +1730,11 @@ class GatewayStreamConsumer:
sent_any_chunk = True
last_successful_chunk = chunk
last_message_id = result.message_id or last_message_id
- # Each fallback chunk is a fresh platform message — notify
- # so any stale tool-progress bubble gets closed off.
self._notify_new_message()
- # Remove the frozen partial message so the user only sees the
- # complete fallback response. ONLY safe when the fallback re-sent
- # the FULL final text (continuation == final_text). When the
- # prefix-based dedup above sent only the missing TAIL, the partial
- # message IS the head of the answer — deleting it leaves the user
- # with only the last part of the response (the "Gemini sent only
- # the second half" symptom). Best-effort — if the platform doesn't
- # implement ``delete_message``, the delete fails (flood control still
- # active, bot lacks permission, message too old to delete), the
- # partial remains but at least the full answer was delivered.
+ # Best-effort delete of the frozen partial — ONLY when the FULL final
+ # was re-sent. If only the missing tail went out, the partial IS the
+ # head of the answer ("sent only the second half" symptom).
if (
stale_message_id
and stale_message_id != last_message_id
@@ -2370,12 +1755,7 @@ class GatewayStreamConsumer:
self._already_sent = True
self._final_response_sent = True
self._final_content_delivered = True
- # The fallback delivered the complete ``final_text`` (as one message
- # or prefix + continuation chunks that union to it), so record it as
- # the turn-final payload for the gateway's reconciliation (#71643).
- # On a split turn ``final_text`` is only the tail — the recorder
- # substitutes the unsplit ledger so the sealed heads count as
- # delivered too (#78541).
+ # Recorder substitutes the unsplit ledger on a split turn.
self._record_turn_final_payload(final_text)
self._last_sent_text = chunks[-1]
self._fallback_prefix = ""
@@ -2384,14 +1764,11 @@ class GatewayStreamConsumer:
async def _send_empty_fallback_final(self, final_text: str) -> str:
"""Commit a completed answer after Telegram finalization fails.
- Returns ``delivered`` on confirmed success, ``failed`` when the
- gateway can safely retry, ``ambiguous`` when a timeout may have
- reached the platform already, and ``preview`` when flood control
- leaves the complete streamed preview as the authoritative delivery.
+ Returns "delivered", "failed" (gateway may retry), "ambiguous" (a
+ timeout may have reached the platform), or "preview" (flood control
+ leaves the complete streamed preview authoritative).
"""
- # Tool/segment boundaries intentionally preserve the run-wide preview
- # IDs for normal fresh-final cleanup. This recovery replaces only the
- # active final segment, so never delete an earlier finalized preamble.
+ # Segment-scoped only: never delete an earlier finalized preamble.
stale_ids = set(self._segment_preview_message_ids)
if self._message_id and self._message_id != "__no_edit__":
stale_ids.add(str(self._message_id))
@@ -2440,13 +1817,9 @@ class GatewayStreamConsumer:
try:
deleted = await delete_fn(self.chat_id, stale_id)
if deleted is False:
- # Telegram's delete_message reports failure by
- # returning False, not raising. The same flood
- # window that broke the finalize edit can reject
- # this delete too, leaving the preview bubble next
- # to the fresh final (#71047 Problem B). One short
- # bounded retry clears the common transient case;
- # a second failure stays best-effort.
+ # Telegram reports delete failure by returning False;
+ # the flood window that broke the finalize can reject
+ # this too. One bounded retry, then best-effort.
await asyncio.sleep(1.0)
await delete_fn(self.chat_id, stale_id)
except Exception as exc:
@@ -2461,15 +1834,9 @@ class GatewayStreamConsumer:
self._already_sent = True
self._final_response_sent = True
self._final_content_delivered = True
- # Fresh commit of the complete answer after a failed finalize (#71643).
- #
- # Record ``final_text`` VERBATIM -- do not route through
- # _record_turn_final_payload here. This recovery deleted the sealed
- # segment previews just above, so the only thing left on screen is the
- # message we just sent. On a split turn the ledger holds the sealed
- # heads too, and recording it would claim delivery for text this path
- # just removed -- the gateway would then suppress and the user would be
- # left with a fraction of the answer (the #78541 swallow, reintroduced).
+ # Record VERBATIM, not via _record_turn_final_payload: the sealed
+ # previews were just deleted, so the ledger (which still holds sealed
+ # heads) would claim delivery for text this path removed.
self._delivered_final_text = ensure_closed_code_fences(
self._clean_for_display(final_text or "")
).strip()
@@ -2511,36 +1878,22 @@ class GatewayStreamConsumer:
return "flood" in err_lower or "retry after" in err_lower or "rate" in err_lower
def _resolve_draft_streaming(self) -> bool:
- """Decide whether this run should use native draft streaming.
-
- Honors ``cfg.transport``:
- * ``"edit"`` → never use drafts (legacy progressive-edit path).
- * ``"draft"`` → require draft support; gracefully fall back to edit
- when the adapter declines. Logs the downgrade at debug.
- * ``"auto"`` → use drafts when the adapter supports them for this
- chat type; otherwise edit.
-
- Adapter eligibility is checked via
- :meth:`BasePlatformAdapter.supports_draft_streaming`, which considers
- the chat type (e.g. Telegram drafts are DM-only) and platform-version
- gates (e.g. python-telegram-bot 22.6+).
+ """Whether this run should use draft streaming per ``cfg.transport``.
+
+ "edit"/"off" → False. "draft"/"auto" → the adapter's
+ supports_draft_streaming probe (chat type, platform-version gates);
+ "draft" logs the downgrade when unsupported.
"""
transport = (self.cfg.transport or "edit").lower()
- if transport == "edit":
- return False
- # "off" is filtered upstream by the gateway; treat as edit defensively.
- if transport == "off":
+ if transport in ("edit", "off"):
return False
- # Test adapters are MagicMocks that don't subclass BasePlatformAdapter;
- # default them to edit so existing test behaviour is preserved.
+ # MagicMock test adapters default to edit.
if not isinstance(self.adapter, _BasePlatformAdapter):
return False
try:
try:
- # Per-chat capability (review r2, finding 2): multi-platform
- # relay adapters resolve draft support through the CHAT's
- # negotiated descriptor, not the primary identity's. Older
- # adapters without the kwarg keep the legacy probe.
+ # Per-chat probe (relay adapters resolve through the CHAT's
+ # descriptor); older adapters without the kwarg keep the legacy probe.
supported = self.adapter.supports_draft_streaming(
chat_type=self.cfg.chat_type or None,
metadata=self.metadata,
@@ -2565,23 +1918,10 @@ class GatewayStreamConsumer:
return True
def _resolve_native_streaming(self) -> bool:
- """Decide whether this run should use the native-streaming transport.
-
- Native streaming (e.g. WeCom's ``msgtype: "stream"``) routes ALL
- frames — first send, mid-stream updates, and the final ``finish=true``
- — through ``adapter.send_stream_frame()``. It takes precedence over
- both edit and draft transports because it provides the best client
- experience on platforms whose API is built for it (the WeCom client,
- for example, renders cumulative content updates in-place with a
- built-in typing animation while the stream stays open).
-
- Adapter eligibility:
- 1. Must subclass :class:`BasePlatformAdapter` (MagicMock test
- adapters fall back to edit).
- 2. Must declare ``SUPPORTS_NATIVE_STREAMING = True`` at the class
- level.
- 3. Must provide ``supports_native_streaming(chat_type, metadata)``
- returning truthy for this chat.
+ """Whether to use native streaming (adapter.send_stream_frame for ALL frames).
+
+ Requires a BasePlatformAdapter subclass with class-level
+ SUPPORTS_NATIVE_STREAMING and a truthy supports_native_streaming probe.
"""
if not isinstance(self.adapter, _BasePlatformAdapter):
return False
@@ -2603,25 +1943,19 @@ class GatewayStreamConsumer:
return bool(supported)
async def _send_draft_frame(self, text: str) -> bool:
- """Emit a single animated draft frame for the current accumulated text.
+ """Emit one draft frame; any failure permanently disables drafts for this run.
- Returns True when the frame landed. On any failure, permanently
- disables drafts for the remainder of this run so subsequent frames
- flow through the edit-based path (which can adapt with flood-control
- backoff, etc.). Drafts have no message_id and clear naturally on
- the client when the response finalizes via a regular sendMessage.
+ Drafts have no message_id and clear on the client when the final
+ sendMessage lands.
"""
if self._draft_id is None:
- # Defensive: should never happen — _use_draft_streaming gate is
- # set in tandem with _draft_id in run(). Disable to be safe.
+ # Should never happen (set in tandem with _use_draft_streaming in run()).
self._use_draft_streaming = False
return False
- # Carry the per-turn identity on EVERY frame (review B2): the
- # turn-final send goes out via _metadata_for_send, which stamps
- # reply_to_message_id — the relay adapter keys draft/seal state on
- # that identity, so frames must carry the same one or the final
- # cannot find the open stream (flat DMs have no thread metadata
- # at all and would otherwise key on the bare chat).
+ # Every frame must carry the same reply_to_message_id the final send
+ # gets from _metadata_for_send: the relay adapter keys draft/seal state
+ # on it, else the final can't find the open stream (flat DMs have no
+ # thread metadata and would key on the bare chat).
_md = dict(self.metadata) if self.metadata else {}
if self._initial_reply_to_id:
_md.setdefault("reply_to_message_id", self._initial_reply_to_id)
@@ -2647,21 +1981,15 @@ class GatewayStreamConsumer:
self._draft_failures += 1
self._use_draft_streaming = False
return False
- # Frame delivered. Track text for parity with edit-based no-op skip.
- self._last_sent_text = text
+ self._last_sent_text = text # parity with the edit-based no-op skip
return True
async def _abandon_native_stream(self) -> None:
- """Close an orphaned native draft stream on turn death (review B8).
-
- Stale-generation exits and cancellations previously returned with
- the stream still open: the platform message kept its live
- streaming indicator forever, and the adapter's armed interception
- state survived into the next turn. Seal in place with the last
- delivered frame (adds nothing new on screen), via the adapter's
- best-effort ``abandon_open_draft``. Never sets delivery flags —
- an abandoned turn's text was partial, and the gateway's normal
- paths still own whatever happens next.
+ """Seal an orphaned draft stream in place on turn death (stale exit / cancel).
+
+ Otherwise the message keeps its live indicator forever and the
+ adapter's armed interception state leaks into the next turn. Never
+ sets delivery flags — the gateway's normal paths own what happens next.
"""
if not self._use_draft_streaming:
return
@@ -2681,17 +2009,9 @@ class GatewayStreamConsumer:
logger.debug("abandon_open_draft failed (best-effort): %s", e)
async def _flush_segment_tail_on_edit_failure(self) -> None:
- """Deliver un-sent tail content before a segment-break reset.
+ """Send the unseen tail after the delivered prefix as a new message before a segment reset.
- When an edit fails (flood control, transport error) and a tool
- boundary arrives before the next retry, ``_accumulated`` holds text
- that was generated but never shown to the user. Without this flush,
- the segment reset would discard that tail and leave a frozen cursor
- in the partial message.
-
- Sends the tail that sits after the last successfully-delivered
- prefix as a new message, and best-effort strips the stuck cursor
- from the previous partial message.
+ Also best-effort strips the stuck cursor from the partial message.
"""
if not self._fallback_final_send:
await self._try_strip_cursor()
@@ -2703,9 +2023,7 @@ class GatewayStreamConsumer:
if not tail.strip():
return
try:
- # Interim declaration: this tail is pre-boundary text, not the
- # turn-final — never let it seal a native stream (see
- # _send_commentary).
+ # Interim: must never seal a native stream (see _send_commentary).
_md = dict(self.metadata) if self.metadata else {}
_md["_interim_send"] = True
result = await self.adapter.send(
@@ -2719,11 +2037,7 @@ class GatewayStreamConsumer:
logger.error("Segment-break tail flush error: %s", e)
async def _try_strip_cursor(self) -> None:
- """Best-effort edit to remove the cursor from the last visible message.
-
- Called when entering fallback mode so the user doesn't see a stuck
- cursor (▉) in the partial message.
- """
+ """Best-effort edit removing a stuck cursor when entering fallback mode."""
if not self._message_id or self._message_id == "__no_edit__":
return
prefix = self._visible_prefix()
@@ -2745,17 +2059,13 @@ class GatewayStreamConsumer:
if not text.strip():
return False
try:
- # Declare interim intent: this send is NOT the turn-final. A
- # stream-is-the-message adapter (relay Slack native streaming)
- # must not let its seal-interception convert this into
- # draft(final=true) — that would seal the live stream with
- # interim text and orphan the true final into a plain-send
- # duplicate (live finding, 2026-08-16 canary).
+ # Interim: a stream-is-the-message adapter's seal-interception must
+ # not turn this into draft(final=true), which would seal the live
+ # stream with interim text and orphan the true final.
_md = self._metadata_for_send(final=False) or {}
_md["_interim_send"] = True
- # Only pass reply_to for platforms that use reply-anchoring for
- # threading. Discord/Telegram use native thread_id in metadata;
- # passing reply_to on every commentary creates reply spam.
+ # reply_to only for reply-anchored threading; Discord/Telegram use
+ # thread_id metadata and reply_to on every commentary is spam.
_plat = getattr(getattr(self.adapter, "platform", None), "value", None)
_platform_name = str(_plat or getattr(self.adapter, "name", "")).lower()
_needs_reply_anchor = _platform_name in ("buzz", "slack", "mattermost", "feishu")
@@ -2765,19 +2075,11 @@ class GatewayStreamConsumer:
reply_to=self._initial_reply_to_id if _needs_reply_anchor else None,
metadata=_md,
)
- # Note: do NOT set _already_sent = True here.
- # Commentary messages are interim status updates (e.g. "Using browser
- # tool..."), not the final response. Setting already_sent would cause
- # the final response to be incorrectly suppressed when there are
- # multiple tool calls. See: https://github.com/NousResearch/hermes-agent/issues/10454
+ # Do NOT set _already_sent: commentary is interim, and the flag
+ # would suppress the real final after multiple tool calls.
if result.success:
- # Commentary counts as fresh content — close off any
- # stale tool bubble above it so the next tool starts a
- # new bubble below.
self._notify_new_message()
- # Record the exact delivered text so run.py can confirm whether
- # an interim "preview" actually carried the final response, vs.
- # unrelated commentary delivered during a session split (#14238).
+ # Lets run.py confirm whether an interim send carried the final.
self._delivered_commentary_texts.append(text)
return result.success
except Exception as e:
@@ -2785,17 +2087,7 @@ class GatewayStreamConsumer:
return False
def _should_send_fresh_final(self) -> bool:
- """Return True when a long-lived preview should be replaced with a
- fresh final message instead of an edit.
-
- Conditions:
- - Fresh-final is enabled (``fresh_final_after_seconds > 0``).
- - We have a real preview message id (not the ``__no_edit__`` sentinel
- and not ``None``).
- - The preview has been visible for at least the configured threshold.
-
- Ported from openclaw/openclaw#72038.
- """
+ """True when fresh-final is enabled and a real preview has been visible ≥ threshold."""
threshold = getattr(self.cfg, "fresh_final_after_seconds", 0.0) or 0.0
if threshold <= 0:
return False
@@ -2807,21 +2099,13 @@ class GatewayStreamConsumer:
return age >= threshold
def _raw_message_limit(self) -> int:
- """Per-message length budget (in the adapter's ``message_len_fn`` units)
- before the consumer splits an overflowing reply.
-
- Resolved PER-CHAT via ``max_message_length_for_chat`` — a relay adapter
- fronting N platforms has a different cap per chat (Discord 2000 vs
- Telegram 4096 vs Slack 39000); native adapters return their scalar
- ``MAX_MESSAGE_LENGTH`` unchanged. Adapters with a richer send/draft
- path (e.g. Telegram rich messages) can raise this above the base via
- ``streaming_overflow_limit`` so a reply that fits one rich message isn't
- fragmented at the legacy edit limit. Falls back to
- ``MAX_MESSAGE_LENGTH`` (4096 default) for everyone else.
+ """Per-chat length budget (adapter ``message_len_fn`` units) before overflow splits.
+
+ Rich-capable adapters may raise it via ``streaming_overflow_limit`` so a
+ reply that fits one rich message isn't fragmented at the edit limit.
"""
base = getattr(self.adapter, "MAX_MESSAGE_LENGTH", 4096)
- # isinstance gate: MagicMock adapters return mock objects (truthy, not
- # ints) for arbitrary attribute access — keep them on the base limit.
+ # isinstance gate keeps MagicMock adapters (mock attrs, not ints) on base.
if isinstance(self.adapter, _BasePlatformAdapter):
try:
base = self.adapter.max_message_length_for_chat(self.chat_id)
@@ -2844,9 +2128,7 @@ class GatewayStreamConsumer:
self._segment_preview_message_ids.add(message_id)
def _track_preview_ids_from_result(self, result: Any) -> None:
- """Record every message id a send/edit result exposes: the primary id
- plus any continuation ids from an oversized split
- (``continuation_message_ids`` or ``raw_response['message_ids']``)."""
+ """Record the primary id plus any continuation ids from an oversized split."""
self._track_preview_id(getattr(result, "message_id", None))
for mid in (getattr(result, "continuation_message_ids", None) or ()):
self._track_preview_id(mid)
@@ -2856,14 +2138,9 @@ class GatewayStreamConsumer:
self._track_preview_id(mid)
def _adapter_prefers_fresh_final(self, text: str) -> bool:
- """Return True when the adapter would rather finalize a streamed reply
- by sending a fresh message and deleting the preview than by editing the
- preview in place — e.g. Telegram, whose ``sendRichMessage`` send path
- currently renders richer markdown than Hermes' MarkdownV2 edit path.
-
- Returns False when there is no real preview to replace (no message id,
- or the ``__no_edit__`` sentinel), when the adapter doesn't expose the
- hook, or on any error (the consumer then keeps the edit-in-place path).
+ """Adapter's prefers_fresh_final_streaming hook (e.g. Telegram's richer send path).
+
+ False when there's no real preview, no hook, or on any error.
"""
if not self._message_id or self._message_id == "__no_edit__":
return False
@@ -2872,55 +2149,31 @@ class GatewayStreamConsumer:
return False
try:
try:
- # Pass the chat id so multi-platform adapters (relay) resolve
- # the decision through THIS chat's negotiated platform, not
- # the primary identity's. Without it a Slack-primary relay
- # with unfurl force-on misroutes a fronted Telegram/Discord
- # chat's final through the fresh-send lane (duplicate
- # delivery: those descriptors advertise no ``delete`` op),
- # and the mirror posture leaves fronted Slack chats dark.
+ # chat_id lets relay adapters decide via THIS chat's platform;
+ # otherwise a Slack-primary relay misroutes fronted chats
+ # through the fresh-send lane (duplicates: no delete op).
result = fn(text, metadata=self.metadata, chat_id=self.chat_id)
except TypeError:
try:
- # Single-platform hook signature (Telegram, base class):
- # (content, metadata=None) — no chat_id keyword.
- result = fn(text, metadata=self.metadata)
+ result = fn(text, metadata=self.metadata) # single-platform signature
except TypeError:
- # Adapter / test double whose hook doesn't accept the
- # metadata keyword — fall back to the positional-only form.
- result = fn(text)
+ result = fn(text) # test doubles without the metadata kwarg
except Exception as e:
logger.debug("prefers_fresh_final_streaming check failed: %s", e)
return False
- # ``is True`` (not ``bool(...)``) so a MagicMock adapter's auto-child
- # method — truthy by default in tests — does not wrongly enable the
- # fresh-final path. Mirrors the REQUIRES_EDIT_FINALIZE gate in __init__.
+ # ``is True`` keeps MagicMock auto-children from enabling fresh-final.
return result is True
async def _try_fresh_final(self, text: str, *, is_turn_final: bool = True) -> bool:
- """Send ``text`` as a brand-new message (best-effort delete the old
- preview) so the platform's visible timestamp reflects completion
- time. Returns True on successful delivery, False on any failure so
- the caller falls back to the normal edit path.
-
- ``is_turn_final`` is False when finalizing an interim segment at a tool
- boundary (a preamble) rather than the turn-final answer; the
- final-delivery flag is then left unset so the gateway still delivers the
- real answer from the next API call (#29346).
+ """Send ``text`` as a fresh message and best-effort delete the preview(s).
- Ported from openclaw/openclaw#72038.
+ Returns False on any failure so the caller falls back to edit.
+ ``is_turn_final=False`` (interim segment at a tool boundary) leaves the
+ final-delivery flag unset so the gateway still delivers the real answer.
"""
- # Every preview message the user has seen for this response: the
- # current one plus any continuation fragments tracked while streaming
- # (an oversized reply split across the platform's edit limit). All of
- # them are replaced by the single fresh message below.
- #
- # That replacement is only sound while ``text`` holds the whole answer.
- # On a multi-message split the head chunks were sealed and dropped out
- # of ``_accumulated``, so ``text`` is just the tail — deleting the
- # sealed heads would erase text the user already received and leave the
- # complete reply nowhere on screen (#78541). Keep the sealed messages
- # and take the normal edit path instead.
+ # Replacing every tracked preview is only sound while ``text`` holds
+ # the whole answer; after a split, deleting sealed heads would erase
+ # delivered text — take the edit path instead.
if self._turn_split_delivery:
return False
stale_ids = set(self._preview_message_ids)
@@ -2937,16 +2190,8 @@ class GatewayStreamConsumer:
return False
if not getattr(result, "success", False):
return False
- # Adopt the new message id as the current message so subsequent
- # callers (e.g. overflow split loops, finalize retries) see a
- # consistent state.
new_message_id = getattr(result, "message_id", None)
- # Successful fresh send — try to delete the stale preview(s) so the
- # user doesn't see the old edit-stuck message(s) underneath. Cleanup
- # is best-effort; platforms that don't implement ``delete_message``
- # just leave the preview behind (still an acceptable outcome — the
- # visible final timestamp is the important part). Never delete the
- # message we just sent.
+ # Best-effort preview cleanup; never delete the message just sent.
delete_fn = getattr(self.adapter, "delete_message", None)
if delete_fn is not None:
for stale_id in stale_ids:
@@ -2964,43 +2209,25 @@ class GatewayStreamConsumer:
self._message_id = new_message_id
self._message_created_ts = time.monotonic()
else:
- # Send succeeded but platform didn't return an id — treat the
- # delivery as final-only and fall back to "__no_edit__" so we
- # don't try to edit something we can't address.
+ # No id returned: sentinel so we never try to edit it.
self._message_id = "__no_edit__"
self._message_created_ts = None
self._already_sent = True
self._last_sent_text = text
if is_turn_final:
self._final_response_sent = True
- # Fresh send carried exactly ``text`` — record it so the gateway
- # can reconcile the flag against the completed response
- # (#71643/#95382 content-vs-flag contract).
self._record_turn_final_payload(text)
return True
async def _suppress_silence_marker(self) -> None:
- """Retract any streamed preview when the final reply is a silence marker.
-
- The agent chose not to respond and emitted a bare control marker. Any
- preview message the consumer already put on screen (a partial marker
- flushed on an interval tick, or a preamble before a tool boundary) must
- be removed so the raw marker is never left visible. Deletion reuses the
- same best-effort ``delete_message`` path as :meth:`_try_fresh_final`.
-
- Crucially, the delivery flags (``_final_response_sent`` /
- ``_final_content_delivered``) are left **False**: nothing was delivered.
- The gateway then does not mistake the marker for a delivered reply, and
- its own whole-response filter turns the marker into "" so no fallback
- send happens either. ``_already_sent`` is likewise cleared so the
- gateway's ``already_sent`` short-circuits do not fire.
+ """Retract any streamed preview when the final reply is a bare silence marker.
+
+ Delivery flags and ``_already_sent`` are left False: nothing was
+ delivered, and the gateway's whole-response filter turns the marker
+ into "" so no fallback send happens either.
"""
- # Native-stream bubbles (e.g. WeCom) are NOT deletable messages — they
- # are an open stream closed by a finalize frame, not delete_message.
- # If a stream is open (notably one opened by an EAGER re-seed after a
- # clarify answer, where the typing bubble is already on screen with no
- # content), close it with an empty finalize so it doesn't hang forever.
- # Do this before the delete loop; keep the delivery flags False below.
+ # A native-stream bubble isn't a deletable message — close an open one
+ # (e.g. from an eager re-seed) with an empty finalize so it doesn't hang.
if self._native_stream_opened:
try:
await self.adapter.send_stream_frame(
@@ -3052,43 +2279,26 @@ class GatewayStreamConsumer:
async def _send_or_edit(
self, text: str, *, finalize: bool = False, is_turn_final: bool = True,
) -> bool:
- """Send or edit the streaming message.
-
- Returns True if the text was successfully delivered (sent or edited),
- False otherwise. Callers like the overflow split loop use this to
- decide whether to advance past the delivered chunk.
+ """Send or edit the streaming message; True if delivered.
- ``finalize`` is True when this is the last edit in a streaming
- sequence.
+ ``finalize`` marks the last edit of a streaming sequence. Callers such
+ as the overflow split loop use the result to decide whether to advance.
"""
- # Strip MEDIA: directives so they don't appear as visible text.
- # Media files are delivered as native attachments after the stream
- # finishes (via _deliver_media_from_response in gateway/run.py).
text = self._clean_for_display(text)
- # Preserve the pre-fence-closed form for stream-is-the-message draft
- # frames: appending a closing ``` to a mid-code-block frame makes
- # frame N not a prefix of frame N+1, so the connector's append-only
- # delta computation falls back to a whole-snapshot re-append (the
- # stacked-copies class). Native streams render unclosed fences
- # progressively; the finalize path below still fence-closes the
- # real final message.
+ # Stream-is-the-message draft frames must stay prefix-stable: a closing
+ # ``` appended to a mid-code-block frame makes frame N not a prefix of
+ # N+1 and the connector re-appends the whole snapshot. The final
+ # message is still fence-closed below.
_pre_fence_text = text
- # Ensure code fences are balanced before send/edit. Model output
- # truncated mid-code-block (e.g. finish_reason="length") leaves an
- # orphaned ``` which, on Discord/Slack/Matrix, causes the entire
- # remaining output to render as a single code block. This covers
- # the streaming edit path (G2) and first-send path alike.
text = ensure_closed_code_fences(text)
- # A bare streaming cursor is not meaningful user-visible content and
- # can render as a stray tofu/white-box message on some clients.
+ # A bare cursor renders as a stray tofu box on some clients.
visible_without_cursor = text
if self.cfg.cursor:
visible_without_cursor = visible_without_cursor.replace(self.cfg.cursor, "")
_visible_stripped = visible_without_cursor.strip()
if not _visible_stripped:
- # For native streaming: even when the display text is empty (e.g.
- # MEDIA-only response cleaned away), we MUST send a finalize frame
- # to close the thinking bubble. Use placeholder text.
+ # Native streams MUST still get a finalize frame (placeholder) to
+ # close the thinking bubble, e.g. for a MEDIA-only response.
if finalize and self._use_native_streaming and self._native_stream_opened:
try:
ok = await self.adapter.send_stream_frame(
@@ -3106,15 +2316,9 @@ class GatewayStreamConsumer:
return True # cursor-only / whitespace-only update
if not text.strip():
return True # nothing to send is "success"
- # Guard: do not create a brand-new standalone message when the only
- # visible content is a handful of characters alongside the streaming
- # cursor. During rapid tool-calling the model often emits 1-2 tokens
- # before switching to tool calls; the resulting "X ▉" message risks
- # leaving the cursor permanently visible if the follow-up edit (to
- # strip the cursor on segment break) is rate-limited by the platform.
- # This was reported on Telegram, Matrix, and other clients where the
- # ▉ block character renders as a visible white box ("tofu").
- # Existing messages (edits) are unaffected — only first sends gated.
+ # Don't open a new message for 1-2 tokens + cursor (rapid tool-calling):
+ # if the cursor-strip edit is then rate-limited, "X ▉" stays forever.
+ # Only first sends are gated.
_MIN_NEW_MSG_CHARS = 4
if (self._message_id is None
and self.cfg.cursor
@@ -3122,95 +2326,53 @@ class GatewayStreamConsumer:
and len(_visible_stripped) < _MIN_NEW_MSG_CHARS):
return True # too short for a standalone message — accumulate more
- # Native streaming transport (e.g. WeCom): every frame — first send,
- # mid-stream updates, and the final answer — flows through
- # adapter.send_stream_frame(), which manages the underlying stream
- # lifecycle (init seed → cumulative updates → finish=true). The
- # adapter's send/edit_message paths are NOT touched in this mode.
- #
- # Throttling: WeCom AI Bot caps replies at ~30 frames/min per chat.
- # With 15 concurrent users, we need ≤2 frames per turn on average
- # to stay under the limit. 60 chars ≈ one short sentence, which
- # produces 3-5 frames per turn — close to OpenClaw's block-level cadence.
- if self._use_native_streaming:
- # Re-seed if stream was closed (e.g., by approval boundary)
- # and we have new content to send.
- if not self._native_stream_opened and text:
- try:
- seed_ok = await self.adapter.send_stream_frame(
- "",
- chat_id=self.chat_id,
- reply_to=self._initial_reply_to_id,
- turn_id=self._turn_id,
+ # Native streaming: every frame goes through send_stream_frame(); the
+ # adapter's send/edit paths are not touched in this mode. Lazy re-seed
+ # here after a boundary closed the stream.
+ if self._use_native_streaming and not self._native_stream_opened and text:
+ try:
+ seed_ok = await self.adapter.send_stream_frame(
+ "",
+ chat_id=self.chat_id,
+ reply_to=self._initial_reply_to_id,
+ turn_id=self._turn_id,
+ )
+ if seed_ok:
+ self._native_stream_opened = True
+ self._awaiting_reopen_after_boundary = False
+ # Paired with the boundary-finalize INFO: typing-reappear latency.
+ logger.info(
+ "[latency] Re-opened native stream after boundary "
+ "(turn=%s, waited for first delta)",
+ self._turn_id,
)
- if seed_ok:
- self._native_stream_opened = True
- # A fresh stream is open — post-prompt content will
- # stream into it, so got_done no longer needs the
- # lone-placeholder guard for this turn.
- self._awaiting_reopen_after_boundary = False
- # INFO (temporary latency probe): this is the moment the
- # C bubble / typing animation first becomes visible after
- # a clarify answer. Comparing this timestamp to the
- # boundary-finalize log below quantifies the "typing is
- # slow to reappear" delay the user reported.
- logger.info(
- "[latency] Re-opened native stream after boundary "
- "(turn=%s, waited for first delta)",
- self._turn_id,
- )
- else:
- self._use_native_streaming = False
- except Exception as e:
- logger.debug("Re-seed failed, disabling native streaming: %s", e)
+ else:
self._use_native_streaming = False
+ except Exception as e:
+ logger.debug("Re-seed failed, disabling native streaming: %s", e)
+ self._use_native_streaming = False
if self._use_native_streaming:
- # For WeCom native streaming: segment breaks should NOT finalize
- # the stream. WeCom renders each finalize as a separate message bubble.
- # Only turn-final (got_done) and approval boundary should close the stream.
- # Tool boundary segment breaks just continue accumulating in the same stream.
+ # WeCom renders each finalize as a separate bubble: only the
+ # turn-final and boundaries close the stream, not segment breaks.
if finalize and not is_turn_final:
finalize = False
- # Fire-and-forget: send immediately when content differs from
- # the last pushed frame. No buffering / throttle — WeCom long-
- # connection mode has no polling cadence, so every cumulative
- # update is pushed as soon as it arrives.
if not finalize and text == self._last_sent_text:
return True # unchanged — skip
- # B2 — timeout-inversion race fix. For a finalize frame, mark
- # delivery OPTIMISTICALLY, before send_stream_frame blocks on the
- # ack. The finalize frame's bytes are written to the wire by an
- # independent control-worker task *before* the ack wait begins, and
- # for WeCom a frame on the wire is already rendered by the client
- # (the same premise the ack-timeout-as-success path already relies
- # on). Setting the flag here means a gateway join-cancel during the
- # ack wait — the timeout inversion between run.py's stream_task join
- # and adapter._REPLY_ACK_TIMEOUT — can no longer strand
- # final_content_delivered=False while WeCom has already shown the
- # message, which is what produced the duplicate normal send
- # (see tests/gateway/test_wecom_double_send.py and
- # docs/rca-wecom-stream-final-ack-timeout-duplicate.md).
- #
- # A DEFINITIVE dispatch failure (ok is False below: stream never
- # opened, 846608 expired, errcode 6000, or the call raised) rolls
- # the mark back so the edit/send fallback still delivers exactly
- # once. Residual window: if the consumer is cancelled between this
- # optimistic mark and the control worker actually writing the bytes
- # (queue latency, sub-ms in practice), the message could be
- # suppressed without being sent — far rarer than the guaranteed
- # duplicate this replaces, and the send-path idempotency guard
- # cannot help there (nothing was sent). Accepted trade-off.
+ # Mark a finalize frame delivered OPTIMISTICALLY, before the ack
+ # wait: the bytes hit the wire (and WeCom renders them) before the
+ # ack, so a gateway join-cancel during the ack wait must not strand
+ # final_content_delivered=False and cause a duplicate normal send
+ # (docs/rca-wecom-stream-final-ack-timeout-duplicate.md). A
+ # definitive dispatch failure rolls the mark back below. Residual
+ # window (cancel between mark and wire write, sub-ms) is accepted.
_optimistic_finalize = bool(finalize)
if _optimistic_finalize:
self._final_response_sent = True
self._final_content_delivered = True
- # Record what this finalize frame carries so the gateway's
- # content reconciliation (#71643/#95382) can judge the flag:
- # a frame holding only a stale/partial snapshot must not
- # suppress the corrective send of the complete response.
+ # Recorded so a stale/partial frame can't suppress the corrective send.
self._record_turn_final_payload(text)
ok = False
@@ -3237,25 +2399,19 @@ class GatewayStreamConsumer:
self._final_content_delivered = True
return True
- # Dispatch failed definitively — roll back the optimistic finalize
- # mark so the edit/send fallback below delivers the content once.
+ # Definitive failure: roll back the optimistic mark so the
+ # edit/send fallback delivers exactly once.
if _optimistic_finalize:
self._final_response_sent = False
self._final_content_delivered = False
- # Roll back the recorded payload too — nothing was delivered.
self._delivered_final_text = None
- # Native streaming refused / failed — switch off so this and
- # subsequent frames take the edit/send fallback path below.
- # The adapter is responsible for marking the chat as expired
- # so it doesn't keep retrying the dead stream session.
+ # Subsequent frames take the edit/send fallback; the adapter marks
+ # the chat expired so it doesn't retry the dead stream.
self._use_native_streaming = False
- # If the stream bubble was opened (seed frame succeeded), try
- # best-effort finalize to close it before falling back to send().
- # This prevents leaving an unclosed thinking stream visible to the
- # user. Check _native_stream_opened (not _native_last_pushed_len)
- # because the seed frame has zero length but still opens the bubble.
+ # Best-effort close of an opened bubble (seed frame has zero length
+ # but still opens it — hence _native_stream_opened, not pushed_len).
if self._native_stream_opened:
try:
await self.adapter.send_stream_frame(
@@ -3266,114 +2422,59 @@ class GatewayStreamConsumer:
turn_id=self._turn_id,
)
logger.debug("Native fallback: finalized stream (best-effort close)")
- # DO NOT mark _final_content_delivered here.
- # The finalize frame closes the typing bubble, but WeCom may
- # not actually render the content (e.g., errcode 6000 race).
- # Let the fallback send() path deliver the content reliably.
+ # DO NOT mark delivered: the frame closes the bubble but
+ # WeCom may not render the content (errcode 6000 race).
except Exception as e:
logger.debug(
"Native fallback: failed to finalize stream: %s", e,
)
- # Fall through to the edit/send paths so any accumulated text
- # still reaches the user as a one-shot proactive markdown send.
-
-
- # The final answer is delivered via the regular sendMessage path
- # below — drafts have no message_id so we can't finalize them
- # in-place; the regular sendMessage clears the draft naturally on
- # the client and gives the user a real message in their history.
- # Skip when:
- # * finalize=True (this is the final answer; needs to be a real message)
- # * an edit path is already established (message_id is set, e.g. after
- # a tool-boundary segment break where the prior text was finalized
- # as a real sendMessage and the next text segment continues editing
- # that one — staying on edit-based for that segment is correct).
- # Stream-is-the-message exception (finding #5, live canary): for
- # adapters like relay Slack native streaming, a segment-break
- # finalize must NOT become a real send — the adapter's seal
- # interception would convert it to draft(final=true), sealing the
- # stream at EVERY tool boundary (one frozen cumulative message per
- # segment; only the turn-final seal belongs). Those adapters keep
- # ONE stream per turn: mid-turn boundaries just emit another
- # cumulative frame; only got_done (is_turn_final) seals.
+ # Fall through so accumulated text still reaches the user via edit/send.
+
+ # Drafts have no message_id: the final answer goes through the regular
+ # send below (which clears the draft client-side). Skip drafts when
+ # finalizing or when an edit path is already established. Exception:
+ # stream-is-the-message adapters keep ONE stream per turn, so a
+ # segment-break finalize must NOT become a real send (seal interception
+ # would seal the stream at every tool boundary); only got_done seals.
_stream_is_msg = self._stream_is_message()
if (
self._use_draft_streaming
and self._message_id is None
and (not finalize or (_stream_is_msg and not is_turn_final))
):
- # Stream-is-the-message frames must stay prefix-stable: use the
- # pre-fence-closed text (see _pre_fence_text above). The turn
- # final still goes through the fence-closed path below.
_frame_text = _pre_fence_text if _stream_is_msg else text
- # Finding #6 (live canary, the duplicate-content root cause):
- # strip the gateway's text cursor from draft frames. Native
- # streams render their own typing indicator, and a cursor-
- # suffixed frame breaks the connector's prefix-delta check on
- # EVERY tick ("...text▉" is never a prefix of "...text more▉"),
- # triggering its whole-text fallback append — the user saw each
- # cumulative snapshot stacked inside one message, ▉ included.
+ # Strip the cursor: native streams render their own indicator, and
+ # "...text▉" is never a prefix of "...text more▉", which forces the
+ # connector's whole-text re-append on EVERY tick (stacked copies).
if self.cfg.cursor and _frame_text.endswith(self.cfg.cursor):
_frame_text = _frame_text[: -len(self.cfg.cursor)]
- # No-op skip: identical to the last frame we sent.
if _frame_text == self._last_sent_text:
return True
ok = await self._send_draft_frame(_frame_text)
if ok:
- # Drafts mark "we put something on screen" but DO NOT set
- # _already_sent — that flag gates the gateway's fallback
- # final-send path and we still need that to fire so the
- # user gets a real message (drafts have no message_id).
+ # Deliberately NOT _already_sent: the gateway's fallback final
+ # send must still fire so the user gets a real message.
return True
- # Failure already disabled drafts for this run; fall through to
- # the regular edit/send path below.
+ # Failure disabled drafts; fall through to edit/send.
self._last_edit_overflowed = False
try:
if self._message_id is not None:
if self._edit_supported:
- # Skip if text is identical to what we last sent.
- # Exception: adapters that require an explicit finalize
- # call (REQUIRES_EDIT_FINALIZE) must still receive the
- # finalize=True edit even when content is unchanged, so
- # their streaming UI can transition out of the in-
- # progress state. Everyone else short-circuits.
+ # REQUIRES_EDIT_FINALIZE adapters need the finalize=True
+ # edit even when unchanged; everyone else short-circuits.
if text == self._last_sent_text and not (
finalize and self._adapter_requires_finalize
):
return True
- # Fresh-final for long-lived previews: when finalizing
- # the last edit in a streaming sequence, if the
- # original preview has been visible for at least
- # ``fresh_final_after_seconds``, send the completed
- # reply as a fresh message so the platform's visible
- # timestamp reflects completion time instead of the
- # preview creation time. Best-effort cleanup of the
- # old preview follows. Ported from
- # openclaw/openclaw#72038. Gated by config so the
- # legacy edit-in-place path stays the default.
- #
- # Adapters can also opt in regardless of the time threshold
- # via prefers_fresh_final_streaming (e.g. Telegram, whose
- # send path renders richer markdown than its edit path):
- # finalizing through edit would visibly downgrade a rich
- # preview, so re-deliver as a fresh message + delete the
- # preview instead.
- #
- # When the adapter exposes prefers_fresh_final_streaming
- # and explicitly returns False, the time-based threshold
- # must NOT override that decision. On Telegram the
- # fresh-final path sends a Rich Message (sendRichMessage)
- # that overlaps with the legacy MarkdownV2 preview already
- # visible from streaming — both remain on screen because
- # the old message is only best-effort deleted. Adapters
- # without the hook still get the time-based fresh-final.
- # (#47048)
- # Check the *class* for the hook so MagicMock adapters
- # (which auto-create attributes on access) are not
- # falsely detected as having it. Also check instance
- # __dict__ for test doubles that explicitly assign the
- # attribute (e.g. adapter.prefers_fresh_final_streaming
- # = MagicMock(return_value=False)).
+ # Fresh-final: replace a long-lived preview with a fresh
+ # message (timestamp reflects completion), or whenever the
+ # adapter prefers it (Telegram's send path renders richer
+ # markdown than its edit path). An explicit hook returning
+ # False must NOT be overridden by the time threshold — on
+ # Telegram both messages would stay on screen since the
+ # delete is best-effort. Check the CLASS (MagicMock
+ # auto-creates attrs) plus instance __dict__ (test doubles
+ # assign the hook explicitly).
_has_prefers_hook = (
hasattr(type(self.adapter),
"prefers_fresh_final_streaming")
@@ -3403,20 +2504,11 @@ class GatewayStreamConsumer:
)
if result.success:
self._already_sent = True
- # Record any continuation fragments an oversized edit
- # split off, so fresh-final can clean them all up.
self._track_preview_ids_from_result(result)
- # Adapter may have split-and-delivered an oversized
- # edit across the original message + N continuations.
- # When that happens, ``message_id`` is the LAST visible
- # continuation and ``_last_sent_text`` no longer reflects
- # the on-screen content (the new message only holds the
- # final chunk's text), so subsequent edits must target
- # the new id and skip-if-same comparisons must reset.
- # Fire on_new_message so tool-progress bubbles linearize
- # below the new continuation, not the original.
- # ``getattr`` with default keeps backwards compat with
- # SimpleNamespace mocks in tests that pre-date the field.
+ # Oversized edit split across continuations: message_id
+ # is now the LAST continuation, which holds only the
+ # final chunk — retarget edits and reset skip-if-same.
+ # getattr keeps SimpleNamespace test mocks working.
_continuation_ids = getattr(result, "continuation_message_ids", ()) or ()
if (
_continuation_ids
@@ -3424,8 +2516,6 @@ class GatewayStreamConsumer:
and result.message_id != self._message_id
):
self._last_edit_overflowed = True
- # Adapter adopted continuation messages — this
- # turn is a multi-message delivery (#71643).
self._turn_split_delivery = True
self._message_id = str(result.message_id)
self._message_created_ts = time.monotonic()
@@ -3433,7 +2523,6 @@ class GatewayStreamConsumer:
self._notify_new_message()
else:
self._last_sent_text = text
- # Successful edit — reset flood strike counter
self._flood_strikes = 0
return True
else:
@@ -3445,30 +2534,17 @@ class GatewayStreamConsumer:
and self._last_sent_text.endswith(self.cfg.cursor)
and self._visible_prefix() == text
):
- # The final clean-up edit failed, but the complete
- # answer is already visible from the last streaming
- # frame (usually with only the cursor still stuck on
- # screen). Mark the content delivered so the
- # gateway suppresses its normal full final send;
- # otherwise users see the same long answer twice
- # when Telegram/Discord rate-limit this cosmetic
- # final edit (#36965, #25349).
+ # Cosmetic final edit was rate-limited but the full
+ # answer is already on screen (cursor stuck): mark
+ # delivered so the gateway doesn't send it twice,
+ # and record the on-screen payload.
self._final_content_delivered = True
- # ``text`` is already cleaned/fence-closed here and
- # equals the visible prefix — the on-screen content
- # IS this finalize payload (#71643). Record it on
- # split turns too: post-#78541 an unrecorded split
- # reads as a mismatch and would re-send this
- # already-visible answer, reintroducing the
- # duplicate #45517 fixed (#36965 / #25349).
self._record_turn_final_payload(text)
raw_response = getattr(result, "raw_response", None)
if isinstance(raw_response, dict) and raw_response.get("partial_overflow"):
- # Telegram edited/sent one or more overflow chunks,
- # but not the complete response. Preserve the
- # visible prefix so the got_done fallback sends the
- # missing tail instead of marking a clipped topic
- # reply as final delivery.
+ # Some overflow chunks landed but not the whole
+ # response: preserve the visible prefix so got_done
+ # sends the missing tail.
self._message_id = str(
raw_response.get("last_message_id")
or result.message_id
@@ -3491,10 +2567,8 @@ class GatewayStreamConsumer:
self._notify_new_message()
return False
- # Edit failed. If this looks like flood control / rate
- # limiting, use adaptive backoff: double the edit interval
- # and retry on the next cycle. Only permanently disable
- # edits after _MAX_FLOOD_STRIKES consecutive failures.
+ # Flood control: adaptive backoff (double the interval);
+ # disable edits only after _MAX_FLOOD_STRIKES in a row.
if self._is_flood_error(result):
self._flood_strikes += 1
self._current_edit_interval = min(
@@ -3520,10 +2594,7 @@ class GatewayStreamConsumer:
self._flood_strikes < self._MAX_FLOOD_STRIKES
and not immediate_final_fallback
):
- # Don't disable edits yet — just slow down.
- # Update _last_edit_time so the next edit
- # respects the new interval.
- self._last_edit_time = time.monotonic()
+ self._last_edit_time = time.monotonic() # honor the new interval
return False
if immediate_final_fallback:
@@ -3532,9 +2603,7 @@ class GatewayStreamConsumer:
"entering fallback immediately"
)
- # Non-flood error OR flood strikes exhausted: enter
- # fallback mode — send only the missing tail once the
- # final response is available.
+ # Fallback mode: send only the missing tail at got_done.
logger.debug(
"Edit failed (strikes=%d), entering fallback mode",
self._flood_strikes,
@@ -3543,21 +2612,15 @@ class GatewayStreamConsumer:
self._fallback_final_send = True
self._edit_supported = False
self._already_sent = True
- # Best-effort: strip the cursor from the last visible
- # message so the user doesn't see a stuck ▉. A
- # turn-final Telegram flood skips this cosmetic edit:
- # another edit would consume the same flood budget and
- # delay the fallback send that carries the answer.
+ # A turn-final flood skips the cosmetic cursor strip: it
+ # would burn the same flood budget and delay the answer.
if not immediate_final_fallback:
await self._try_strip_cursor()
return False
else:
- # Editing not supported — skip intermediate updates.
- # The final response will be sent by the fallback path.
- return False
+ return False # edits unsupported; fallback path sends the final
else:
- # First message — send new, threaded to the original user message
- # so it lands in the correct topic/thread.
+ # First send, threaded to the user's message (correct topic/thread).
result = await self.adapter.send(
chat_id=self.chat_id,
content=text,
@@ -3570,12 +2633,7 @@ class GatewayStreamConsumer:
if result.success:
if result.message_id:
self._message_id = result.message_id
- # Track when the preview first became visible to
- # the user so fresh-final logic can detect stale
- # preview timestamps on long-running responses.
self._message_created_ts = time.monotonic()
- # Record this (and any continuation fragments from an
- # oversized first send) for fresh-final cleanup.
self._track_preview_ids_from_result(result)
else:
self._edit_supported = False
@@ -3584,18 +2642,12 @@ class GatewayStreamConsumer:
if not result.message_id:
self._fallback_prefix = self._visible_prefix()
self._fallback_final_send = True
- # Sentinel prevents re-entering the first-send path on
- # every delta/tool boundary when platforms accept a
- # message but do not return an editable message id.
+ # Sentinel: no editable id, don't re-enter first-send
+ # on every delta/tool boundary.
self._message_id = "__no_edit__"
- # Notify the gateway that a fresh content bubble was
- # created so any accumulated tool-progress bubble above
- # gets closed off — the next tool fires into a new
- # bubble below, preserving chronological order.
self._notify_new_message()
return True
else:
- # Initial send failed — disable streaming for this session
self._edit_supported = False
return False
except Exception as e:
diff --git a/gateway/systemd_notify.py b/gateway/systemd_notify.py
index 4fb2b9d5ead..f3e973171a9 100644
--- a/gateway/systemd_notify.py
+++ b/gateway/systemd_notify.py
@@ -3,36 +3,29 @@
from __future__ import annotations
import asyncio
+import contextlib
import math
import os
import socket
from typing import Optional
-def _notify_address(raw: str) -> str:
- """Translate systemd's ``@abstract`` notation to Python's address form."""
- return "\0" + raw[1:] if raw.startswith("@") else raw
-
-
def notify(message: str) -> bool:
"""Send one nonblocking sd_notify datagram when systemd configured it.
- Notification failures are deliberately non-fatal: a missing socket or an
- older platform must never prevent the gateway from starting.
+ Failures are non-fatal: a missing socket or an older platform must never
+ prevent the gateway from starting.
"""
address = os.environ.get("NOTIFY_SOCKET", "").strip()
- if not address:
- return False
- if not isinstance(message, str) or not message:
- return False
- if not hasattr(socket, "AF_UNIX"):
+ if not address or not isinstance(message, str) or not message or not hasattr(socket, "AF_UNIX"):
return False
try:
payload = message.encode("utf-8")
with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as sender:
# A full receiver buffer must not stall the gateway event loop.
sender.setblocking(False)
- sender.connect(_notify_address(address))
+ # systemd's ``@abstract`` notation -> Python's leading-NUL address form.
+ sender.connect("\0" + address[1:] if address.startswith("@") else address)
sender.send(payload)
return True
except (OSError, UnicodeError, ValueError):
@@ -41,9 +34,7 @@ def notify(message: str) -> bool:
def watchdog_interval_seconds() -> Optional[float]:
"""Return systemd's configured watchdog interval in seconds."""
- if not os.environ.get("NOTIFY_SOCKET", "").strip():
- return None
- if not hasattr(socket, "AF_UNIX"):
+ if not os.environ.get("NOTIFY_SOCKET", "").strip() or not hasattr(socket, "AF_UNIX"):
return None
raw = os.environ.get("WATCHDOG_USEC", "").strip()
if not raw:
@@ -52,20 +43,13 @@ def watchdog_interval_seconds() -> Optional[float]:
interval = float(raw) / 1_000_000.0
except (TypeError, ValueError):
return None
- if not math.isfinite(interval) or interval <= 0:
- return None
- return interval
+ return interval if math.isfinite(interval) and interval > 0 else None
class SystemdWatchdog:
"""Feed systemd while the asyncio event loop continues to make progress."""
- def __init__(
- self,
- *,
- config_enabled: bool = True,
- lag_tolerance_seconds: Optional[float] = None,
- ) -> None:
+ def __init__(self, *, config_enabled: bool = True, lag_tolerance_seconds: Optional[float] = None) -> None:
self._config_enabled = bool(config_enabled)
self.interval_seconds = watchdog_interval_seconds()
self._lag_tolerance_seconds = lag_tolerance_seconds
@@ -87,17 +71,14 @@ class SystemdWatchdog:
return self._task
def _lag_tolerance(self) -> float:
- interval = self.interval_seconds or 0.0
- configured = self._lag_tolerance_seconds
- if configured is None:
- return max(0.1, interval * 0.25)
+ default = max(0.1, (self.interval_seconds or 0.0) * 0.25)
+ if self._lag_tolerance_seconds is None:
+ return default
try:
- value = float(configured)
+ value = float(self._lag_tolerance_seconds)
except (TypeError, ValueError):
- return max(0.1, interval * 0.25)
- if not math.isfinite(value):
- return max(0.1, interval * 0.25)
- return max(0.0, value)
+ return default
+ return max(0.0, value) if math.isfinite(value) else default
def start(self) -> bool:
"""Start the loop-progress sampler when systemd watchdog is enabled."""
@@ -144,7 +125,7 @@ class SystemdWatchdog:
cadence = max(0.01, interval / 2.0)
loop = asyncio.get_running_loop()
scheduled_at = loop.time() + cadence
- try:
+ with contextlib.suppress(asyncio.CancelledError):
while not self._stopping and not self._unhealthy:
await asyncio.sleep(max(0.0, scheduled_at - loop.time()))
now = loop.time()
@@ -153,23 +134,16 @@ class SystemdWatchdog:
scheduled_at += cadence
if scheduled_at < now:
scheduled_at = now + cadence
- except asyncio.CancelledError:
- return
async def stop(self) -> None:
"""Stop feeding systemd and emit ``STOPPING=1`` at most once."""
self._stopping = True
task = self._task
- current = asyncio.current_task()
- if task is not None and task is not current:
+ if task is not None and task is not asyncio.current_task():
if not task.done():
task.cancel()
- try:
+ with contextlib.suppress(asyncio.CancelledError, Exception):
await task
- except asyncio.CancelledError:
- pass
- except Exception:
- pass
self._task = None
if self.enabled and not self._stopping_notified:
notify("STOPPING=1")
diff --git a/gateway/turn_context.py b/gateway/turn_context.py
index 02fa8d23c96..192a7766ae9 100644
--- a/gateway/turn_context.py
+++ b/gateway/turn_context.py
@@ -1,26 +1,20 @@
-"""Per-turn context shared between ``GatewayRunner._run_agent_inner`` and the
-``TurnRunner`` collaborator (gateway/run.py).
-
-``_run_agent_inner`` historically defined its tool-progress plumbing as nested
-closures (``progress_callback`` ~250 LOC, ``send_progress_messages`` ~353 LOC)
-that closed over ~20 enclosing locals. ``TurnContext`` is the extraction seam:
-each closed-over local becomes a field on this dataclass, so the closure bodies
-can move onto ``TurnRunner`` methods unchanged modulo ``name`` -> ``ctx.name``
-rewrites.
-
-Field notes:
-
-- All fields are written once by ``_run_agent_inner`` while wiring up the turn
- (a few — ``_progress_metadata``, ``_progress_reply_to``, ``agent_holder`` —
- are computed slightly later than construction and assigned onto the ctx as
- soon as the original locals were bound). None of the original closures
- *rebound* their captured names (no ``nonlocal``); mutable state uses the
- same single-element-list containers as before (``last_progress_msg``,
- ``repeat_count``, ...), so mutation stays visible to the outer body through
- the shared objects exactly as it did through the shared closure cells.
-- ``_run_still_current`` stays a callable (it captures ``self``/
- ``session_key``/``run_generation``); carrying the callable keeps the
- extracted bodies byte-identical.
+"""Per-turn context shared between ``GatewayRunner._run_agent_inner`` and
+``TurnRunner`` (gateway/run.py).
+
+``_run_agent_inner`` once defined its tool-progress plumbing and ``run_sync`` as
+nested closures over ~20 locals. ``TurnContext`` is the extraction seam: each
+closed-over local is a field here, so the closure bodies moved onto ``TurnRunner``
+methods unchanged modulo ``name`` -> ``ctx.name`` rewrites.
+
+Invariants:
+- Fields are written once by ``_run_agent_inner`` while wiring the turn (a few are
+ assigned onto the ctx slightly after construction, at the original binding sites).
+- The original closures never rebound captured names except ``message`` (formerly
+ ``nonlocal``): rebind sites now write ``ctx.message`` and the outer body reads it.
+ Other mutable state keeps the single-element-list containers so mutation stays
+ visible to the outer body through the shared objects.
+- ``_run_still_current`` stays a callable (captures ``self``/``session_key``/
+ ``run_generation``) so the extracted bodies remain byte-identical.
"""
from __future__ import annotations
@@ -33,7 +27,7 @@ from typing import Any, Callable, List, Optional
class TurnContext:
"""Closed-over locals of ``_run_agent_inner`` needed by ``TurnRunner``."""
- # --- read-only turn identity / wiring -------------------------------
+ # --- read-only turn identity / wiring ---
source: Any = None
_run_still_current: Callable[[], bool] = None # type: ignore[assignment]
_live_status_adapter: Any = None
@@ -43,11 +37,11 @@ class TurnContext:
progress_grouping: str = "grouped"
tool_progress_enabled: bool = False
- # --- queues ----------------------------------------------------------
+ # --- queues ---
progress_queue: Any = None
log_queue: Any = None
- # --- mutable single-element containers (shared with the outer body) --
+ # --- mutable single-element containers (shared with the outer body) ---
last_progress_msg: list = field(default_factory=lambda: [None])
last_tool: list = field(default_factory=lambda: [None])
last_was_terminal_block: list = field(default_factory=lambda: [False])
@@ -55,29 +49,19 @@ class TurnContext:
long_tool_hint_fired: list = field(default_factory=lambda: [False])
agent_holder: list = field(default_factory=lambda: [None])
- # --- constants / cleanup bookkeeping ---------------------------------
+ # --- constants / cleanup bookkeeping ---
_LONG_TOOL_THRESHOLD_S: float = 30.0
_cleanup_progress: bool = False
_cleanup_msg_ids: List[str] = field(default_factory=list)
- # --- progress threading metadata (assigned after construction, before
- # send_progress_messages is scheduled) ----------------------------
+ # --- progress threading metadata (assigned before send_progress_messages runs) ---
_progress_metadata: Optional[dict] = None
_progress_reply_to: Optional[Any] = None
- # ------------------------------------------------------------------
- # run_sync extraction (second wave of the seam): the closed-over locals
- # of ``_run_agent_inner`` that ``run_sync`` (and the four sibling bridge
- # callbacks) captured. Same rules as above: read-only snapshots or
- # shared mutable containers; ``message`` is the ONE exception — the old
- # closure rebound it via ``nonlocal``, so the rebind sites now write
- # ``ctx.message`` and the outer body reads ``ctx.message`` afterwards.
- # ------------------------------------------------------------------
-
- # --- the ex-``nonlocal`` turn message (rebindable) --------------------
+ # --- run_sync seam: the ex-``nonlocal`` turn message (rebindable) ---
message: Optional[str] = None
- # --- turn parameters / config snapshots (read-only in run_sync) -------
+ # --- turn parameters / config snapshots (read-only in run_sync) ---
history: Any = None
context_prompt: Optional[str] = None
channel_prompt: Optional[str] = None
@@ -88,18 +72,17 @@ class TurnContext:
process_baseline: frozenset[str] = field(default_factory=frozenset)
_interrupt_depth: int = 0
event_message_id: Optional[str] = None
- # Raw platform-side id of the INBOUND user message (event.message_id),
- # distinct from event_message_id which is the reply/thread anchor and can
- # be the replied-to message on Slack/Mattermost/Buzz or None for Telegram
- # topics. Used to stamp platform_message_id on the persisted user turn.
+ # Raw platform id of the INBOUND user message (event.message_id), distinct from
+ # event_message_id (the reply/thread anchor, which may be the replied-to message
+ # on Slack/Mattermost/Buzz or None for Telegram topics). Stamped as
+ # platform_message_id on the persisted user turn.
inbound_message_id: Optional[str] = None
moa_config: Optional[dict] = None
persist_user_message: Optional[Any] = None
persist_user_timestamp: Optional[float] = None
- # display_kind stamped on the persisted user row at turn start when this
- # turn was self-injected (MessageEvent.internal), e.g.
- # "internal_notification" for async-delegation/background notifications
- # (#82888). DB-only presentation metadata; never sent to the provider.
+ # display_kind for the persisted user row when the turn was self-injected
+ # (MessageEvent.internal), e.g. "internal_notification". DB-only presentation
+ # metadata; never sent to the provider.
persist_user_display_kind: Optional[str] = None
user_config: Any = None
enabled_toolsets: Any = None
@@ -108,43 +91,38 @@ class TurnContext:
interim_assistant_messages_enabled: bool = False
needs_progress_queue: bool = False
- # --- lazy-imported callables captured from the outer body -------------
+ # --- lazy-imported callables captured from the outer body ---
AIAgent: Any = None
resolve_display_setting: Any = None
- # --- mutable holder cells (shared-list pattern; outer body + the
- # post-executor closures read mutations through the same objects) --
+ # --- mutable holder cells (shared-list pattern) ---
result_holder: list = field(default_factory=lambda: [None])
tools_holder: list = field(default_factory=lambda: [None])
stream_consumer_holder: list = field(default_factory=lambda: [None])
streaming_tts_consumer_holder: list = field(default_factory=lambda: [None])
- # --- voice-ack wiring --------------------------------------------------
+ # --- voice-ack wiring ---
_voice_ack_fired: list = field(default_factory=lambda: [False])
_voice_ack_guild: list = field(default_factory=lambda: [None])
_voice_ack_loop: Any = None
- # --- hook / status bridge wiring (published at original binding sites) -
+ # --- hook / status bridge wiring (published at original binding sites) ---
_loop_for_step: Any = None
_hooks_ref: Any = None
_status_adapter: Any = None
_status_chat_id: Any = None
_status_thread_metadata: Optional[dict] = None
- # --- extracted sibling callbacks (bound TurnRunner methods; run_sync
- # reads them through the ctx exactly where it used to close over
- # the sibling closures) ---------------------------------------------
+ # --- extracted sibling callbacks (bound TurnRunner methods read via ctx) ---
progress_callback: Optional[Callable] = None
voice_ack_callback: Optional[Callable] = None
_step_callback_sync: Optional[Callable] = None
_event_callback_sync: Optional[Callable] = None
_status_callback_sync: Optional[Callable] = None
- # --- Slack-native task-card progress (opt-in; #29483) ------------------
- # True when the Slack adapter's ``native_task_cards_enabled()`` opt-in is
- # set for this turn's platform. The ID-bearing lifecycle callbacks are
- # published by TurnRunner (like voice_ack_callback above) so tool starts
- # and completions correlate by real tool-call ID instead of tool name.
+ # --- Slack-native task-card progress (opt-in via the adapter's
+ # native_task_cards_enabled()). ID-bearing lifecycle callbacks are published
+ # by TurnRunner so tool starts/completions correlate by tool-call ID. ---
_native_slack_task_cards: bool = False
native_tool_start_callback: Optional[Callable] = None
native_tool_complete_callback: Optional[Callable] = None
diff --git a/gateway/wake.py b/gateway/wake.py
index deaaf28d3eb..618c250c013 100644
--- a/gateway/wake.py
+++ b/gateway/wake.py
@@ -1,35 +1,27 @@
"""Wake an existing agent session from a background completion event.
-Two delivery strategies, selected by the target adapter's
-``supports_async_delivery`` capability flag:
+Two delivery strategies, selected by the adapter's ``supports_async_delivery``
+capability flag:
* Push-capable adapters (telegram, discord, plugin platforms, ...): inject a
- synthetic ``MessageEvent(internal=True)`` through ``adapter.handle_message``
- — the pre-existing wake path, preserved exactly.
+ synthetic ``MessageEvent(internal=True)`` through ``adapter.handle_message``.
* Stateless request/response adapters (the API server,
``supports_async_delivery = False``): ``handle_message`` would run the wake
- turn under a ``build_session_key()``-derived key
- (``agent:main:api_server:group:<sid>``) that NEVER matches the raw
- ``X-Hermes-Session-Id`` key real gateway/HQ turns run under
- (``_bind_api_server_session``), so the wake lands in a parallel, invisible
- session. Instead we self-POST ``/v1/chat/completions`` on the in-pod API
- server with the raw session id in the ``X-Hermes-Session-Id`` header — the
- exact entry point real turns use — so the wake turn resumes the REAL
- session, with full history, and its result is visible the next time the
- client polls/reopens the conversation.
-
-Async-delegation completions are the exception on the stateless path
-(#85957): after the parent turn ends (``finish_reason=stop``, SSE
-``event.complete``) the CLIENT owns the next turn, so a completion must never
-be self-POSTed as a new ``role=user`` prompt — that starts an unauthorized
-agent turn that can blow through a pending human-confirmation gate. Instead
-``persist_delegation_delivery`` writes the completion into the session
-transcript as a durable DELIVERY row (``role=user`` +
-``display_kind="async_delegation_complete"`` — the same bookkeeping shape the
-TUI/desktop pollers use), so clients polling
-``GET /api/sessions/{id}/messages`` see the result immediately and the next
-REAL client turn carries it as context, without any model turn running.
+ under a ``build_session_key()``-derived key that never matches the raw
+ ``X-Hermes-Session-Id`` key real turns run under, landing in an invisible
+ parallel session. Instead we self-POST ``/v1/chat/completions`` on the
+ in-pod API server with the raw session id header — the exact entry point
+ real turns use — so the wake resumes the REAL session with full history.
+
+Async-delegation completions are the exception on the stateless path: after
+the parent turn ends the CLIENT owns the next turn, so a completion must never
+be self-POSTed as a new ``role=user`` prompt (that starts an unauthorized agent
+turn that can cross a pending human-confirmation gate). Instead
+``persist_delegation_delivery`` writes it into the session transcript as a
+durable DELIVERY row (``role=user`` + ``display_kind="async_delegation_complete"``,
+the shape the TUI/desktop pollers use) so pollers see it immediately and the
+next REAL client turn carries it as context, without any model turn running.
Failures RAISE (after bounded retries on transient errors) so callers can
rewind cursors / retry instead of silently losing the event.
@@ -43,58 +35,40 @@ from typing import Any, Optional
logger = logging.getLogger(__name__)
-# A wake self-post runs the entire agent turn synchronously (stream=false);
+# A wake self-post runs the whole agent turn synchronously (stream=false);
# generous ceiling so long tool-using turns aren't killed mid-flight.
WAKE_TURN_TIMEOUT_SECONDS = 600.0
-# Backoff delays between retries on transient failures (429 concurrency cap,
-# connection errors). The API server has no per-session lock — concurrent
-# turns on one session are last-writer-wins — but it DOES enforce a global
-# max_concurrent_runs cap via HTTP 429, which is worth waiting out.
+# Backoff between retries on transient failures. The API server has no
+# per-session lock (concurrent turns are last-writer-wins) but DOES enforce a
+# global max_concurrent_runs cap via HTTP 429, which is worth waiting out.
_RETRY_DELAYS_SECONDS = (2.0, 5.0, 10.0)
def adapter_supports_push(adapter: Any) -> bool:
"""Whether this adapter can push a message to the user after a turn ends.
- Mirrors ``gateway.session_context.async_delivery_supported`` but reads the
- capability off the adapter class (``supports_async_delivery``) instead of
- the request-scoped contextvar — background watchers run outside any bound
+ Reads ``supports_async_delivery`` off the adapter class rather than the
+ request-scoped contextvar — background watchers run outside any bound
session context. Adapters that don't declare the flag are push-capable.
"""
return bool(getattr(adapter, "supports_async_delivery", True))
-async def deliver_wake(
- adapter: Any,
- *,
- text: str,
- session_id: str = "",
- source: Any = None,
-) -> None:
+async def deliver_wake(adapter: Any, *, text: str, session_id: str = "", source: Any = None) -> None:
"""Deliver a wake turn to the session behind ``adapter``.
- ``session_id`` is the RAW session id (the ``X-Hermes-Session-Id`` value /
- ``state.db`` key) — required for non-push adapters. ``source`` is the
- ``SessionSource`` used to build the synthetic event — required for
- push-capable adapters.
-
- Raises on failure (bad arguments, exhausted retries, HTTP error) so the
- caller can rewind/retry instead of treating the wake as delivered.
+ ``session_id`` is the RAW session id (``X-Hermes-Session-Id`` / state.db
+ key) — required for non-push adapters. ``source`` is the ``SessionSource``
+ for the synthetic event — required for push-capable adapters. Raises on
+ failure so the caller can rewind/retry.
"""
if adapter_supports_push(adapter):
if source is None:
- raise ValueError(
- "deliver_wake: push-capable adapter requires a SessionSource"
- )
+ raise ValueError("deliver_wake: push-capable adapter requires a SessionSource")
from gateway.platforms.base import MessageEvent, MessageType
- synth_event = MessageEvent(
- text=text,
- message_type=MessageType.TEXT,
- source=source,
- internal=True,
- )
+ synth_event = MessageEvent(text=text, message_type=MessageType.TEXT, source=source, internal=True)
await adapter.handle_message(synth_event)
return
@@ -109,21 +83,14 @@ async def deliver_wake(
def _delegation_display_metadata(evt: dict) -> dict:
"""Display-only metadata for a persisted delegation delivery row.
- Mirrors ``tui_gateway.server._async_delegation_display_metadata`` (the
- same ``display_kind`` consumer contract) without importing the TUI stack
- into the gateway.
+ Mirrors ``tui_gateway.server._async_delegation_display_metadata`` (same
+ ``display_kind`` consumer contract) without importing the TUI stack.
"""
raw_results = evt.get("results")
- results = [r for r in raw_results if isinstance(r, dict)] if isinstance(
- raw_results, list
- ) else []
+ results = [r for r in raw_results if isinstance(r, dict)] if isinstance(raw_results, list) else []
task_count = len(results) or 1
- completed_count = sum(
- 1 for r in results if r.get("status") in {"completed", "success"}
- )
- failed_count = sum(
- 1 for r in results if r.get("status") in {"failed", "error"}
- )
+ completed_count = sum(1 for r in results if r.get("status") in {"completed", "success"})
+ failed_count = sum(1 for r in results if r.get("status") in {"failed", "error"})
metadata = {
"delegation_id": str(evt.get("delegation_id") or ""),
"task_count": task_count,
@@ -136,24 +103,11 @@ def _delegation_display_metadata(evt: dict) -> dict:
return metadata
-async def persist_delegation_delivery(
- adapter: Any, *, text: str, session_id: str, evt: Optional[dict] = None
-) -> None:
- """Persist an async-delegation completion as a durable DELIVERY row.
-
- #85957: on stateless api_server sessions the client owns the turn after
- ``event.complete`` — a completion must never become a new ``role=user``
- prompt via the self-post (that starts an unauthorized agent turn and can
- cross a pending human-confirmation gate). Instead, append the completion
- to the session transcript as a timeline bookkeeping row
- (``display_kind="async_delegation_complete"`` + display metadata — the
- exact shape the TUI/desktop delivery path persists), WITHOUT running any
- agent turn. Clients polling ``GET /api/sessions/{id}/messages`` see it
- immediately; the pre-request repair belt folds it into the next real
- client turn as context.
+async def persist_delegation_delivery(adapter: Any, *, text: str, session_id: str, evt: Optional[dict] = None) -> None:
+ """Persist an async-delegation completion as a durable DELIVERY row
+ (see module docstring) WITHOUT running any agent turn.
- Raises on failure so the caller can release the durable claim and retry
- instead of losing the completion.
+ Raises on failure so the caller can release the durable claim and retry.
"""
if not session_id:
raise ValueError(
@@ -168,37 +122,28 @@ async def persist_delegation_delivery(
f"cannot persist completion for session {session_id}"
)
await asyncio.to_thread(
- db.append_message,
- session_id,
- "user",
- content=text,
+ db.append_message, session_id, "user", content=text,
display_kind="async_delegation_complete",
display_metadata=_delegation_display_metadata(evt or {}),
)
logger.info(
- "async delegation completion persisted as delivery row for "
- "api_server session %s (no wake turn)",
+ "async delegation completion persisted as delivery row for api_server session %s (no wake turn)",
session_id,
)
-async def _self_post_chat_completion(
- adapter: Any, *, text: str, session_id: str
-) -> None:
+async def _self_post_chat_completion(adapter: Any, *, text: str, session_id: str) -> None:
"""POST the wake text to the in-pod API server as a normal session turn.
- Uses the adapter's own bind host/port/key (``ApiServerAdapter.__init__``).
- Session continuation via ``X-Hermes-Session-Id`` is 403-gated on
- ``API_SERVER_KEY`` being configured, so a missing key is a hard error —
- raise loudly rather than run the wake in a fresh fingerprint-derived
- session nobody is looking at.
+ Uses the adapter's own bind host/port/key. Session continuation via
+ ``X-Hermes-Session-Id`` is 403-gated on ``API_SERVER_KEY``, so a missing
+ key is a hard error rather than a wake in a fresh session nobody watches.
"""
import aiohttp
host = str(getattr(adapter, "_host", "") or "127.0.0.1")
if host in ("0.0.0.0", "::", "*"):
- # Wildcard bind address — connect over loopback.
- host = "127.0.0.1"
+ host = "127.0.0.1" # wildcard bind — connect over loopback
port = int(getattr(adapter, "_port", 0) or 8642)
api_key = str(getattr(adapter, "_api_key", "") or "")
if not api_key:
@@ -211,10 +156,7 @@ async def _self_post_chat_completion(
if ":" in host and not host.startswith("["):
host = f"[{host}]" # bare IPv6 literal
url = f"http://{host}:{port}/v1/chat/completions"
- headers = {
- "Authorization": f"Bearer {api_key}",
- "X-Hermes-Session-Id": session_id,
- }
+ headers = {"Authorization": f"Bearer {api_key}", "X-Hermes-Session-Id": session_id}
payload = {
"model": str(getattr(adapter, "_model_name", "") or "hermes-agent"),
"messages": [{"role": "user", "content": text}],
@@ -231,42 +173,28 @@ async def _self_post_chat_completion(
async with aiohttp.ClientSession(timeout=timeout) as http:
async with http.post(url, json=payload, headers=headers) as resp:
if resp.status == 429:
- # Global concurrency cap (max_concurrent_runs) —
- # transient; back off and retry.
+ # Global concurrency cap — transient; back off and retry.
last_err = RuntimeError(
- f"wake self-post got HTTP 429 (concurrency cap) "
- f"for session {session_id}"
- )
- logger.warning(
- "%s; attempt %d/%d", last_err, attempt + 1, attempts
+ f"wake self-post got HTTP 429 (concurrency cap) for session {session_id}"
)
+ logger.warning("%s; attempt %d/%d", last_err, attempt + 1, attempts)
continue
if resp.status >= 400:
body = (await resp.text())[:300]
# Non-transient (auth/validation) — fail immediately.
raise RuntimeError(
- f"wake self-post failed for session {session_id}: "
- f"HTTP {resp.status}: {body}"
+ f"wake self-post failed for session {session_id}: HTTP {resp.status}: {body}"
)
await resp.read()
- logger.info(
- "wake self-post delivered for session %s (attempt %d)",
- session_id,
- attempt + 1,
- )
+ logger.info("wake self-post delivered for session %s (attempt %d)", session_id, attempt + 1)
return
except (aiohttp.ClientError, asyncio.TimeoutError, OSError) as exc:
last_err = exc
logger.warning(
- "wake self-post transient failure for session %s "
- "(attempt %d/%d): %s",
- session_id,
- attempt + 1,
- attempts,
- exc,
+ "wake self-post transient failure for session %s (attempt %d/%d): %s",
+ session_id, attempt + 1, attempts, exc,
)
continue
raise RuntimeError(
- f"wake self-post gave up for session {session_id} after "
- f"{attempts} attempts: {last_err}"
+ f"wake self-post gave up for session {session_id} after {attempts} attempts: {last_err}"
) from last_err
diff --git a/gateway/whatsapp_identity.py b/gateway/whatsapp_identity.py
index 19fade10b4e..5271f45f4b9 100644
--- a/gateway/whatsapp_identity.py
+++ b/gateway/whatsapp_identity.py
@@ -1,31 +1,11 @@
"""Shared helpers for canonicalising WhatsApp sender identity.
-WhatsApp's bridge can surface the same human under two different JID shapes
-within a single conversation:
-
-- LID form: ``999999999999999@lid``
-- Phone form: ``[email protected]``
-
-Both the authorisation path (:mod:`gateway.run`) and the session-key path
-(:mod:`gateway.session`) need to collapse these aliases to a single stable
-identity. This module is the single source of truth for that resolution so
-the two paths can never drift apart.
-
-Public helpers:
-
-- :func:`normalize_whatsapp_identifier` — strip JID/LID/device/plus syntax
- down to the bare numeric identifier.
-- :func:`canonical_whatsapp_identifier` — walk the bridge's
- ``lid-mapping-*.json`` files and return a stable canonical identity
- across phone/LID variants.
-- :func:`expand_whatsapp_aliases` — return the full alias set for an
- identifier. Used by authorisation code that needs to match any known
- form of a sender against an allow-list.
-
-Plugins that need per-sender behaviour on WhatsApp (role-based routing,
-per-contact authorisation, policy gating in a gateway hook) should use
-``canonical_whatsapp_identifier`` so their bookkeeping lines up with
-Hermes' own session keys.
+The bridge can surface the same human as a LID (``999...@lid``) or a phone
+JID (``[email protected]``) within one conversation. Authorisation
+(:mod:`gateway.run`) and session keys (:mod:`gateway.session`) both resolve
+those aliases here so the two paths can never drift apart. Plugins needing
+per-sender behaviour on WhatsApp should use :func:`canonical_whatsapp_identifier`
+so their bookkeeping lines up with Hermes' own session keys.
"""
from __future__ import annotations
@@ -35,28 +15,24 @@ import logging
import re
from typing import Set
+from hermes_constants import get_hermes_dir
+
logger = logging.getLogger(__name__)
-# WhatsApp JIDs are numeric (or plus-prefixed numeric) with optional
-# ``@``, ``.`` and ``:`` separators. ``\w`` is pinned to ASCII so
-# full-width digits / Unicode word chars can't sneak through.
+# WhatsApp JIDs are numeric (or plus-prefixed) with ``@``/``.``/``:`` separators.
+# Explicit ASCII class so full-width digits / Unicode word chars can't sneak through.
_SAFE_IDENTIFIER_RE = re.compile(r"^[A-Za-z0-9@.+\-]+$")
-from hermes_constants import get_hermes_dir
+# "Just a phone number": optional ``+`` then digits and human separators.
+# Anything carrying ``@`` is already a JID (``@g.us``, ``@lid``, ``status@broadcast``).
+_BARE_PHONE_RE = re.compile(r"^\+?[\d\s().\-]+$")
def normalize_whatsapp_identifier(value: str) -> str:
- """Strip WhatsApp JID/LID syntax down to its stable numeric identifier.
+ """Strip JID/LID/device/plus syntax down to the bare numeric identifier.
- Accepts any of the identifier shapes the WhatsApp bridge may emit:
- ``"[email protected]"``, ``"60123456789:[email protected]"``,
- ``"60123456789@lid"``, or a bare ``"+601****6789"`` / ``"60123456789"``.
- Returns just the numeric identifier (``"60123456789"``) suitable for
- equality comparisons.
-
- Useful for plugins that want to match sender IDs against
- user-supplied config (phone numbers in ``config.yaml``) without
- worrying about which variant the bridge happens to deliver.
+ ``"60123456789:[email protected]"``, ``"60123456789@lid"`` and
+ ``"+60123456789"`` all become ``"60123456789"``.
"""
return (
str(value or "")
@@ -67,46 +43,23 @@ def normalize_whatsapp_identifier(value: str) -> str:
)
-# A target that is "just a phone number" — optional leading ``+`` then digits
-# and the usual human separators (spaces, dots, dashes, parens). Anything that
-# already carries an ``@`` is a fully-qualified JID and must pass through
-# untouched (group ``@g.us``, LID ``@lid``, ``status@broadcast`` etc.).
-_BARE_PHONE_RE = re.compile(r"^\+?[\d\s().\-]+$")
-
-
def to_whatsapp_jid(value: str) -> str:
- """Normalize an *outbound* WhatsApp target to a bridge-safe JID.
-
- Baileys' ``jidDecode`` crashes on a bare phone number — it expects a
- fully-qualified JID such as ``[email protected]``. This helper
- is the inverse of :func:`normalize_whatsapp_identifier`: instead of
- stripping a JID down to its numeric core for comparison, it *builds* the
- JID a send must use.
-
- Behaviour:
+ """Normalize an *outbound* target to a bridge-safe JID (inverse of normalize).
- - ``"+50766715226"`` / ``"50766715226"`` → ``"[email protected]"``
- - ``"[email protected]"`` → unchanged
- - ``"[email protected]"`` / ``"130631430344750@lid"`` → unchanged
- - ``"user:[email protected]"`` style colon-before-``@`` → ``@`` form
- - anything that isn't a recognizable bare phone → returned unchanged so
- the bridge can surface a meaningful error rather than us mangling it.
-
- Returns ``""`` for an empty/whitespace input.
+ Baileys' ``jidDecode`` crashes on a bare phone number, so bare phones become
+ ``<digits>@s.whatsapp.net``; ``user:device@domain`` collapses to
+ ``user@domain``; anything else already carrying ``@`` or not recognizable
+ as a phone is returned unchanged so the bridge can surface a real error.
+ Returns ``""`` for empty input.
"""
if not value:
return ""
normalized = str(value).strip()
- # Drop a device suffix before the domain: ``user:device@domain`` is a
- # legacy Baileys shape whose ``:device`` part is not addressable — collapse
- # it to ``user@domain``. (Mirrors normalize_whatsapp_identifier, which
- # splits the bare id on ``:`` for the same reason.)
if ":" in normalized and "@" in normalized:
prefix, _, domain = normalized.partition("@")
normalized = f"{prefix.split(':', 1)[0]}@{domain}"
- # Already a fully-qualified JID — leave it alone.
if "@" in normalized:
return normalized
@@ -119,15 +72,10 @@ def to_whatsapp_jid(value: str) -> str:
def expand_whatsapp_aliases(identifier: str) -> Set[str]:
- """Resolve WhatsApp phone/LID aliases via bridge session mapping files.
-
- Returns the set of all identifiers transitively reachable through the
- bridge's ``$HERMES_HOME/whatsapp/session/lid-mapping-*.json`` files,
- starting from ``identifier``. The result always includes the
- normalized input itself, so callers can safely ``in`` check against
- the return value without a separate fallback branch.
+ """Return all identifiers transitively reachable via the bridge's ``lid-mapping-*.json`` files.
- Returns an empty set if ``identifier`` normalizes to empty.
+ Always includes the normalized input itself, so callers can ``in``-check
+ without a fallback branch. Empty set if ``identifier`` normalizes to empty.
"""
normalized = normalize_whatsapp_identifier(identifier)
if not normalized:
@@ -141,14 +89,9 @@ def expand_whatsapp_aliases(identifier: str) -> Set[str]:
current = queue.pop(0)
if not current or current in resolved:
continue
- # Defense-in-depth: reject identifiers that could sneak path
- # separators / traversal segments into the ``lid-mapping-{current}``
- # filename below. The hardcoded ``lid-mapping-`` prefix already
- # prevents escape via pathlib's component split (an attacker can't
- # create ``lid-mapping-..`` as a real directory in session_dir), but
- # this keeps the identifier space to the characters WhatsApp JIDs
- # actually use and avoids depending on that filesystem-layout
- # invariant.
+ # Defense-in-depth against path separators / traversal in the
+ # ``lid-mapping-{current}`` filename; the fixed prefix already prevents
+ # escape, but this avoids depending on that filesystem-layout invariant.
if not _SAFE_IDENTIFIER_RE.match(current):
continue
@@ -171,36 +114,16 @@ def expand_whatsapp_aliases(identifier: str) -> Set[str]:
def canonical_whatsapp_identifier(identifier: str) -> str:
- """Return a stable WhatsApp sender identity across phone-JID/LID variants.
-
- WhatsApp may surface the same person under either a phone-format JID
- (``[email protected]``) or a LID (``1234567890@lid``). This
- applies to a DM ``chat_id`` *and* to the ``participant_id`` of a
- member inside a group chat — both represent a user identity, and the
- bridge may flip between the two for the same human.
-
- This helper reads the bridge's ``whatsapp/session/lid-mapping-*.json``
- files, walks the mapping transitively, and picks the shortest
- (numeric-preferred) alias as the canonical identity.
- :func:`gateway.session.build_session_key` uses this for both WhatsApp
- DM chat_ids and WhatsApp group participant_ids, so callers get the
- same session-key identity Hermes itself uses.
-
- Plugins that need per-sender behaviour (role-based routing,
- authorisation, per-contact policy) should use this so their
- bookkeeping lines up with Hermes' session bookkeeping even when
- the bridge reshuffles aliases.
-
- Returns an empty string if ``identifier`` normalizes to empty. If no
- mapping files exist yet (fresh bridge install), returns the
- normalized input unchanged.
+ """Return a stable sender identity across phone-JID/LID variants.
+
+ Applies to DM ``chat_id`` and group ``participant_id`` alike (the bridge
+ may flip between forms for the same human). Picks the shortest alias from
+ :func:`expand_whatsapp_aliases`, which degrades to the normalized input
+ when no mapping files exist yet. Empty string for empty input.
"""
normalized = normalize_whatsapp_identifier(identifier)
if not normalized:
return ""
- # expand_whatsapp_aliases always includes `normalized` itself in the
- # returned set, so the min() below degrades gracefully to `normalized`
- # when no lid-mapping files are present.
aliases = expand_whatsapp_aliases(normalized)
return min(aliases, key=lambda candidate: (len(candidate), candidate))
diff --git a/tests/gateway/relay/stub_connector.py b/tests/gateway/relay/stub_connector.py
index 9283883531a..3f55cadca22 100644
--- a/tests/gateway/relay/stub_connector.py
+++ b/tests/gateway/relay/stub_connector.py
@@ -36,7 +36,7 @@ class StubConnector:
self.follow_ups: List[Dict[str, Any]] = []
self.follow_up_platforms: List[Optional[str]] = []
# The fronted (platform, bot_id) identity set (Phase 1.5). Mirrors the real
- # transport's _identities so RelayAdapter._platform_is_fronted resolves; a
+ # transport's _identities so RelayAdapter.fronts_platform resolves; a
# single-identity default keeps existing tests' behaviour unchanged.
self._identities: List[tuple] = [(descriptor.platform, "")]
self.chat_info: Dict[str, Dict[str, Any]] = {}
diff --git a/tests/gateway/relay/test_relay_adapter.py b/tests/gateway/relay/test_relay_adapter.py
index 54612c249d2..e821d7b0a62 100644
--- a/tests/gateway/relay/test_relay_adapter.py
+++ b/tests/gateway/relay/test_relay_adapter.py
@@ -96,7 +96,7 @@ class _CaptureTransport:
def __init__(self):
self.sent = None
self.sent_platform = None
- # No concrete fronted identities ⇒ _platform_is_fronted is a no-op here.
+ # No concrete fronted identities ⇒ fronts_platform is a no-op here.
self._identities = []
def set_inbound_handler(self, h): # noqa: D401