Files
Hermes_rocket.chat_Plugin/plugin/archivar/presence_engine.py
T
Bernd (Hermes) df14b4b931 fix(presence): Busy-Done-Debounce verhindert vorzeitiges mark_busy_done (V8.9 P1)
PROBLEM:
mark_busy_done im finally-Block von _process_incoming feuert 25ms nach
mark_busy_started — der Status geht auf Grün, während der Agent noch
30-90s arbeitet. Ursache: handle_message() dispatched den Agent
asynchron und kehrt sofort zurück, aber der finally-Block wartet nicht
auf die tatsächliche Agent-Fertigstellung.

LÖSUNG:
Busy-Done-Debounce: Statt sofort mark_busy_done zu rufen, startet der
finally-Block einen 3s-Timer. Jeder send()-Call resettet den Timer.
Erst wenn 3s lang keine Nachricht mehr gesendet wurde, ist der Agent
wirklich fertig und mark_busy_done wird aufgerufen.

ÄNDERUNGEN (adapter.py):
- __init__: _agent_dispatched_this_turn, _busy_done_debounce_task,
  _busy_done_debounce_lock
- _process_incoming: Flag-Reset vor mark_busy_started; finally-Block
  startet _start_busy_done_debounce() statt sofort mark_busy_done
- _dispatch_agent + main dispatch path: Flag auf True setzen
- send(): _reset_busy_done_debounce() nach erfolgreichem Post
- _send_split(): _reset_busy_done_debounce() pro Chunk
- disconnect(): _cancel_busy_done_debounce()
- Neue Methoden: _start_busy_done_debounce, _busy_done_debounce_timer,
  _reset_busy_done_debounce, _cancel_busy_done_debounce

EDGE CASES:
- Kein Agent dispatched (Inline-Command, Onboarding-Guard):
  mark_busy_done sofort
- Agent sendet mehrere Nachrichten: Timer wird jedes Mal reset
- Agent sendet Split-Nachrichten: Timer wird pro Chunk reset
- disconnect(): Timer wird gecancelled

ZUSÄTZLICH (presence_engine.py):
pgrep-Block von pid_used/gateway_used/plugin_used entkoppelt —
pgrep läuft jetzt immer (bereits deployed von Bernd).
2026-08-02 20:07:43 +02:00

1755 lines
71 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
V8.6: PresenceEngine — Rocket.Chat User-Status automatisch setzen.
Phase 1: Basis-PresenceEngine mit Status-Modell, Coalesce-Timer, Caching.
Phase 2: Heartbeat-Pulsieren (Flughafen-Prinzip) für Background-Tasks.
Zero external dependencies — stdlib only.
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import tempfile
import threading
import time
import urllib.request
import urllib.error
from datetime import datetime, timezone
from typing import Optional, Dict, Callable
logger = logging.getLogger(__name__)
# Ensure presence_engine logs are visible in journalctl by adding a stderr handler
if not logger.handlers:
_pe_handler = logging.StreamHandler()
_pe_handler.setLevel(logging.INFO)
_pe_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))
logger.addHandler(_pe_handler)
logger.propagate = False # Don't double-log to root
# ═══════════════════════════════════════════════════════════════════════════
# P1-2: Plugin-State-Datei — atomare Hilfsfunktionen
# ═══════════════════════════════════════════════════════════════════════════
PLUGIN_STATE_DIR = os.path.expanduser("~/.hermes/plugin_state")
PLUGIN_STATE_FILENAME = "hermes_rocket_plugin.json"
PLUGIN_STATE_SCHEMA_VERSION = 1
def _get_plugin_state_path() -> str:
"""Return the path to the plugin state file.
Returns:
Absolute path to ~/.hermes/plugin_state/hermes_rocket_plugin.json
"""
return os.path.join(PLUGIN_STATE_DIR, PLUGIN_STATE_FILENAME)
def _read_plugin_state(path: str) -> dict:
"""Read the plugin state file, returning {} if missing or corrupt.
Args:
path: Absolute path to the plugin state JSON file.
Returns:
Parsed dict, or empty dict on any error.
"""
try:
if not os.path.exists(path):
return {}
with open(path, 'r') as f:
return json.load(f)
except (json.JSONDecodeError, IOError, OSError) as e:
logger.debug("[plugin_state] read failed: %s", e)
return {}
def _write_plugin_state(path: str, data: dict) -> None:
"""Atomically write the plugin state file (write-temp + rename).
Args:
path: Absolute path to the plugin state JSON file.
data: Dict to serialize as JSON.
"""
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
# Write to temp file in same directory (same filesystem → atomic rename)
fd, tmp_path = tempfile.mkstemp(
suffix=".tmp",
prefix="plugin_state_",
dir=os.path.dirname(path),
)
try:
with os.fdopen(fd, 'w') as f:
json.dump(data, f, ensure_ascii=False)
os.replace(tmp_path, path) # atomic on POSIX
except Exception:
# Clean up temp file on write failure
try:
os.unlink(tmp_path)
except OSError:
pass
raise
except Exception as e:
logger.debug("[plugin_state] write failed: %s", e)
# ═══════════════════════════════════════════════════════════════════════════
# Pure Function: _format_presence_message
# ═══════════════════════════════════════════════════════════════════════════
def _format_presence_message(
status: str,
room_name: str = "",
error: str = "",
background_count: int = 0,
) -> str:
"""Format a presence status message as a pure function.
Args:
status: One of 'online', 'busy', 'away_onboarding', 'away_move_request',
'away_error', 'heartbeat'.
room_name: Room name for busy/move_request messages.
error: Error description for away_error.
background_count: Number of background tasks for heartbeat.
Returns:
Formatted message string (empty string for online/idle).
"""
if status == "online":
return ""
elif status == "busy":
return f"Verarbeitet in {room_name}" if room_name else "Verarbeitet"
elif status == "away_onboarding":
return "Onboarding läuft"
elif status == "away_move_request":
return f"Wartet auf Bestätigung in {room_name}" if room_name else "Wartet auf Bestätigung"
elif status == "away_clarification":
return "Klärung läuft — wartet auf Antwort"
elif status == "away_error":
return f"⚠️ Fehler: {error}" if error else "⚠️ Fehler"
elif status == "heartbeat":
return f"wartet — {background_count} Aufträge im Hintergrund"
else:
return ""
# ═══════════════════════════════════════════════════════════════════════════
# PresenceEngine
# ═══════════════════════════════════════════════════════════════════════════
class PresenceEngine:
"""Manages Rocket.Chat user presence status with coalescing and heartbeat.
Thread-safe: uses threading.Lock for all counter operations.
Coalesce-Timer: prevents flickering by delaying status updates by 2s.
Heartbeat: pulses online↔away when background_tasks > 0 and agent is idle.
P1a: Honeymoon-Timer ensures busy status is visible for at least
MIN_BUSY_VISIBLE_S (1.0s) before transitioning to online.
Lock-Order (Rainers Pflicht-Nachbesserung #1):
─────────────────────────────────────────────
Race-Bedingung: Honeymoon-Expiry (_honeymoon_expired) kann parallel zu
PulseController.set_pulse_target() laufen. Beide greifen auf
_transition_from_busy → _update_presence_with_subagents → set_pulse_target.
LOCK-ORDER (immer in dieser Reihenfolge):
1. _busy_honeymoon_lock (PresenceEngine)
2. _mode_lock (PulseController)
_honeymoon_expired() acquired _busy_honeymoon_lock zuerst, dann
ruft es _transition_from_busy() → set_pulse_target() → _mode_lock.
Externe Aufrufer von set_pulse_target() (z.B. mark_busy_done) MÜSSEN
sicherstellen dass _busy_honeymoon_lock NICHT gehalten wird wenn sie
_mode_lock anfordern — sonst Deadlock.
"""
# P1a: Minimum time busy status must be visible (prevents coalesce race)
MIN_BUSY_VISIBLE_S = 1.0
def __init__(
self,
rest=None,
enabled: bool = True,
coalesce_ms: int = 2000,
pulse_interval: float = 1.5,
gateway_state_path: str = "",
_clamp_pulse: bool = True,
):
"""Initialize the PresenceEngine.
Args:
rest: RocketChatREST instance for API calls.
enabled: Whether presence updates are enabled.
coalesce_ms: Coalesce delay in milliseconds (default 2000).
pulse_interval: PulseController interval in seconds (0.5-30, default 1.5).
gateway_state_path: Path to gateway_state.json. Defaults to
ROCKETCHAT_GATEWAY_STATE_PATH env var or ~/.hermes/gateway_state.json.
_clamp_pulse: If True, clamp pulse_interval to 0.5-30. Set False for testing.
"""
self._rest = rest
self._enabled = enabled
# Coalesce
self._coalesce_ms = coalesce_ms
self._coalesce_timer: Optional[threading.Timer] = None
self._coalesce_lock = threading.Lock()
# Pending state
self._pending_status: Optional[str] = None
self._pending_message: str = ""
# Caching
self._last_sent_status: Optional[str] = None
self._last_sent_message: str = ""
# Active tasks counter (threading.Lock, NOT asyncio.Lock)
self._active_tasks: int = 0
self._active_tasks_lock = threading.Lock()
# Sentinels for special states
self._onboarding_active: bool = False
self._move_request_pending: Dict[str, str] = {} # room_id → room_name
self._error_state: Optional[str] = None
# P2-2: Klärungsflow — Butler wartet auf Antwort (gelb/away)
self._clarification_pending: set = set() # Set[str] of room_ids
# Current room name for busy messages
self._current_room_name: str = ""
# Background tasks counter (for display + PulseController coordination)
self._background_tasks: int = 0
self._background_tasks_lock = threading.Lock()
# P1-2: Plugin-State-Datei für DetectionTimer (Gateway-interne Subagenten)
self._plugin_state_path: str = _get_plugin_state_path()
self._plugin_state_lock = threading.Lock() # Thread-safe, nicht asyncio
# P1a: Honeymoon-Timer — busy status minimum 1s sichtbar
self._busy_started_at: float = 0.0 # time.monotonic() when busy started
self._busy_honeymoon_timer: Optional[threading.Timer] = None
self._busy_honeymoon_lock = threading.Lock()
self._busy_counter: int = 0 # multi-turn: count concurrent busy starts
# P0-1: PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s)
self._pulse_controller = PulseController(
pulse_interval=pulse_interval,
_clamp_pulse=_clamp_pulse,
)
# P0-1: DetectionTimer — erkennt Hintergrund-Agenten, steuert PulseController
self._detection_timer = DetectionTimer(
gateway_state_path=gateway_state_path,
detection_interval=10.0,
on_change=self._on_detection_change,
)
# P1b: DetectionTimer NICHT im Init starten — erst nach on_connected_cb.
# Der Adapter ruft _detection_timer.start() explizit auf, sobald die
# DDP-Verbindung steht. Das verhindert eine Race-Condition bei der
# ersten gateway_state.json-Auswertung (Datei existiert ggf. noch nicht).
# ── Public API ───────────────────────────────────────────────────────
def is_enabled(self) -> bool:
"""Check if presence updates are enabled."""
return self._enabled
def start_detection(self) -> None:
"""P1b: Start DetectionTimer — called after DDP connection is established.
Must be called explicitly by the adapter in on_connected_cb.
Prevents race condition where gateway_state.json doesn't exist yet
at PresenceEngine init time.
"""
if self._enabled:
self._detection_timer.start()
def enable(self) -> None:
"""Enable presence updates. DetectionTimer must be started externally
via start_detection() after DDP connection is established."""
self._enabled = True
logger.info("[presence] PresenceEngine enabled")
def disable(self) -> None:
"""Disable presence updates. Stops PulseController and DetectionTimer."""
self._enabled = False
self._pulse_controller.stop()
self._detection_timer.stop()
logger.info("[presence] PresenceEngine disabled")
def increment_active_tasks(self) -> int:
"""Increment the active tasks counter. Thread-safe.
Returns:
New counter value.
"""
with self._active_tasks_lock:
self._active_tasks += 1
return self._active_tasks
def decrement_active_tasks(self) -> int:
"""Decrement the active tasks counter. Thread-safe.
Returns:
New counter value.
"""
with self._active_tasks_lock:
if self._active_tasks > 0:
self._active_tasks -= 1
count = self._active_tasks
# FIX: Resume pulse when all active tasks complete.
# mark_busy_started() pauses the pulse via adapter, but resume()
# was never called in production — the pulse stayed paused forever.
if count == 0:
self._pulse_controller.resume()
logger.info("[presence] active_tasks=0 → pulse resumed")
return count
# ── P1a: Honeymoon-Timer — busy minimum 1s sichtbar ──────────────────
def mark_busy_started(self, room_name: str = "") -> None:
"""P1a: Mark the start of a busy period with honeymoon protection.
Sets the room, increments active_tasks, and schedules a busy status.
If a honeymoon timer is already running (multi-turn), only increments
the counter — no duplicate timer.
Args:
room_name: Room name for the busy status message.
"""
self.set_current_room(room_name)
self.increment_active_tasks()
self.update_presence() # sets pending_status="busy"
# P1a: Busy sofort flushen — nicht auf 2s Coalesce warten.
# Der Honeymoon-Timer (1s) würde sonst vor dem Coalesce feuern.
self._flush_presence()
with self._busy_honeymoon_lock:
self._busy_counter += 1
if self._busy_honeymoon_timer is None:
# B2: _busy_started_at nur beim ERSTEN busy-Start setzen.
# Wenn der Honeymoon-Timer bereits abgelaufen ist (Timer=None)
# aber _busy_started_at noch existiert (weil active > 0),
# dann NICHT neu setzen — sonst künstliche Verlängerung um 1s.
if self._busy_started_at == 0.0:
self._busy_started_at = time.monotonic()
self._busy_honeymoon_timer = threading.Timer(
self.MIN_BUSY_VISIBLE_S,
self._honeymoon_expired,
)
self._busy_honeymoon_timer.daemon = True
self._busy_honeymoon_timer.start()
logger.debug(
"[presence] Honeymoon-Timer gestartet (%.1fs), counter=%d, started_at=%.3f",
self.MIN_BUSY_VISIBLE_S, self._busy_counter, self._busy_started_at,
)
else:
logger.debug(
"[presence] Honeymoon-Timer läuft bereits, counter=%d",
self._busy_counter,
)
def mark_busy_done(self) -> None:
"""P1a: Mark the end of a busy period.
Decrements the busy counter. If the counter reaches 0 and the
honeymoon has elapsed, transitions to online immediately.
If the honeymoon hasn't elapsed yet, the timer callback will
handle the transition when it fires.
Phase 5: Wenn background_tasks > 0, NICHT auf online gehen.
Stattdessen _update_presence_with_subagents() aufrufen.
Must be called in a finally block to ensure counter balance
even on exceptions.
"""
with self._busy_honeymoon_lock:
if self._busy_counter > 0:
self._busy_counter -= 1
counter = self._busy_counter
# Decrement the underlying active_tasks counter
self.decrement_active_tasks()
if counter == 0:
elapsed = time.monotonic() - self._busy_started_at
if elapsed >= self.MIN_BUSY_VISIBLE_S:
# Honeymoon already elapsed — transition now
self._cancel_honeymoon_timer()
# Phase 5: Check background_tasks before going online
self._transition_from_busy()
logger.debug(
"[presence] Honeymoon abgelaufen (%.2fs) → transition", elapsed,
)
else:
# Honeymoon still running — timer callback will handle it
logger.debug(
"[presence] Honeymoon läuft noch (%.2fs/%.1fs) — Timer übernimmt",
elapsed, self.MIN_BUSY_VISIBLE_S,
)
else:
logger.debug(
"[presence] mark_busy_done: counter=%d (weitere Tasks aktiv)", counter,
)
def _transition_from_busy(self) -> None:
"""Phase 5: Transition from busy — check subagents before going online.
Called when mark_busy_done or _honeymoon_expired would normally
transition to online. If background_tasks > 0 or pgrep finds subagents,
has active entries, start/keep PulseController instead.
"""
with self._background_tasks_lock:
bg = self._background_tasks
# Phase 5: Auch pgrep prüfen
subagent_count = self._read_subagent_count()
if bg > 0 or subagent_count > 0:
# Subagenten laufen noch — Pulse-Modus statt online
self._update_presence_with_subagents(max(bg, subagent_count))
else:
# Keine Subagenten — klassischer Pfad: online
self.update_presence()
def _read_subagent_count(self) -> int:
"""V8.7: Read active subagent count via pgrep /proc scan.
Scannt /proc/*/cmdline nach 'hermes' + 'chat' + '--profile' Prozessen.
Schließt die eigene PID aus. Kein subprocess — direkt /proc lesen.
Returns:
Number of active hermes chat --profile processes (excluding self).
"""
return DetectionTimer._pgrep_hermes_subagents()
def _update_presence_with_subagents(self, subagent_count: int) -> None:
"""Phase 5: Set presence when subagents are active.
Two modes:
1. Hauptagent busy (_active_tasks > 0): Status bleibt "busy",
Message = "Verarbeitet in X (N Subagent)"
2. Hauptagent idle (_active_tasks == 0): PulseController mit
pulse_target="away", Message = "N Subagent läuft"
Args:
subagent_count: Number of active subagents.
"""
with self._active_tasks_lock:
active = self._active_tasks
if active > 0:
# Hauptagent busy + Subagenten → busy mit erweiterter Message
msg = f"Verarbeitet in {self._current_room_name} ({subagent_count} Subagent)" if self._current_room_name else f"Verarbeitet ({subagent_count} Subagent)"
self._set_presence("busy", msg)
# PulseController im busy-Modus halten für Message-Pulse
if not self._pulse_controller.is_running():
self._pulse_controller.set_pulse_target("busy")
self._pulse_controller.start()
else:
self._pulse_controller.set_pulse_target("busy")
logger.info(
"[presence] Subagent-Pulse: busy+%d subagents (active_tasks=%d)",
subagent_count, active,
)
else:
# Hauptagent idle + Subagenten → Pulse online↔away
msg = f"{subagent_count} Subagent läuft"
self._pulse_controller.set_pulse_target("away")
if not self._pulse_controller.is_running():
self._pulse_controller.start()
# Set initial status to away (Pulse toggles from here)
self._set_presence("away", msg)
logger.info(
"[presence] Subagent-Pulse: idle+%d subagents → away-pulse",
subagent_count,
)
def _honeymoon_expired(self) -> None:
"""P1a: Honeymoon timer callback — transition to online if idle.
Called by threading.Timer after MIN_BUSY_VISIBLE_S.
If no active tasks remain, sets status to online.
B3: Checks pending_status under _active_tasks_lock to prevent
race with mark_busy_started.
Phase 5: Nutzt _transition_from_busy() statt direkt update_presence(),
damit Subagent-Check auch im Honeymoon-Pfad greift.
"""
with self._busy_honeymoon_lock:
self._busy_honeymoon_timer = None
with self._active_tasks_lock:
active = self._active_tasks
if active == 0:
# B3: Race-Schutz — prüfe ob pending_status 'busy' ist.
# mark_busy_started könnte parallel update_presence() mit
# pending='busy' aufgerufen haben. Dann NICHT überschreiben.
with self._coalesce_lock:
pending = self._pending_status
if pending == "busy":
logger.debug(
"[presence] Honeymoon-Timer abgelaufen, aber pending_status=busy — "
"nicht überschreiben (Race-Schutz)"
)
return
# B2: Reset _busy_started_at when honeymoon fully expires
# and no active tasks remain — next busy cycle starts fresh.
self._busy_started_at = 0.0
logger.info(
"[presence] Honeymoon-Timer abgelaufen, active_tasks=0 → transition"
)
# Phase 5: _transition_from_busy prüft pgrep
self._transition_from_busy()
else:
logger.debug(
"[presence] Honeymoon-Timer abgelaufen, aber active_tasks=%d — kein Wechsel",
active,
)
def _cancel_honeymoon_timer(self) -> None:
"""P1a: Cancel the honeymoon timer if running."""
with self._busy_honeymoon_lock:
if self._busy_honeymoon_timer is not None:
self._busy_honeymoon_timer.cancel()
self._busy_honeymoon_timer = None
def set_onboarding_active(self, active: bool) -> None:
"""Set the onboarding sentinel."""
self._onboarding_active = active
def set_move_request_pending(self, room_id: str, room_name: str) -> None:
"""Set a move request as pending."""
self._move_request_pending[room_id] = room_name
def clear_move_request(self, room_id: str) -> None:
"""Clear a move request."""
self._move_request_pending.pop(room_id, None)
def set_clarification_pending(self, room_id: str) -> None:
"""P2-2: Markiere Raum als wartend auf Klärungsantwort."""
self._clarification_pending.add(room_id)
def clear_clarification_pending(self, room_id: str) -> None:
"""P2-2: Klärung für Raum abgeschlossen."""
self._clarification_pending.discard(room_id)
def set_error_state(self, error: Optional[str]) -> None:
"""Set or clear the error state."""
self._error_state = error
def set_current_room(self, room_name: str) -> None:
"""Set the current room name for busy messages."""
self._current_room_name = room_name
def increment_background_tasks(self) -> int:
"""Increment background tasks counter. Thread-safe.
P1-2: Persists to plugin state file for DetectionTimer.
E1: Lock-Scope erweitert — _persist_plugin_state wird jetzt unter
_background_tasks_lock aufgerufen, sodass kein veralteter Count
persistiert werden kann (Race zwischen zwei konkurrierenden Threads).
Returns:
New counter value.
"""
with self._background_tasks_lock:
self._background_tasks += 1
count = self._background_tasks
self._pulse_controller.set_background_count(count)
self._persist_plugin_state(count)
return count
def decrement_background_tasks(self) -> int:
"""Decrement background tasks counter. Thread-safe.
P1-2: Persists to plugin state file for DetectionTimer.
E1: Lock-Scope erweitert — _persist_plugin_state wird jetzt unter
_background_tasks_lock aufgerufen, sodass kein veralteter Count
persistiert werden kann (Race zwischen zwei konkurrierenden Threads).
Phase 5: stop()-Aufruf entfernt. PulseController wird jetzt von
_update_presence_with_subagents() gesteuert, nicht vom Counter.
Returns:
New counter value.
"""
with self._background_tasks_lock:
if self._background_tasks > 0:
self._background_tasks -= 1
count = self._background_tasks
self._pulse_controller.set_background_count(count)
# Phase 5: stop() NICHT hier — _update_presence_with_subagents()
# entscheidet basierend auf pgrep + background_tasks
self._persist_plugin_state(count)
return count
def _persist_plugin_state(self, background_tasks: int) -> None:
"""P1-2: Persist background_tasks to plugin state file.
Thread-safe via _plugin_state_lock. Writes atomically via
_write_plugin_state (temp + rename).
Args:
background_tasks: Current background tasks count.
"""
with self._plugin_state_lock:
data = {
"background_tasks": background_tasks,
"last_update_iso": datetime.now(timezone.utc).isoformat(),
"source": "plugin_internal",
"schema_version": PLUGIN_STATE_SCHEMA_VERSION,
}
_write_plugin_state(self._plugin_state_path, data)
# ── Internal: Presence Setting ───────────────────────────────────────
def _set_presence(self, status: str, message: str) -> None:
"""Schedule a presence update with coalescing.
The update is delayed by coalesce_ms to prevent flickering.
If called again before the timer fires, the timer is reset.
Args:
status: Rocket.Chat status ('online', 'away', 'busy').
message: Custom status message.
"""
if not self._enabled:
return
# EC-5: Cancel pending pulse when higher-priority status fires.
# Only cancel for non-online statuses — "online" is the pulse's own
# target and cancelling it would prevent the pulse from working.
if status != "online":
self.cancel_pending()
with self._coalesce_lock:
self._pending_status = status
self._pending_message = message
# Cancel existing timer
if self._coalesce_timer is not None:
self._coalesce_timer.cancel()
self._coalesce_timer = None
# Start new timer
delay = self._coalesce_ms / 1000.0
self._coalesce_timer = threading.Timer(delay, self._flush_presence)
self._coalesce_timer.daemon = True
self._coalesce_timer.start()
def _flush_presence(self) -> None:
"""Flush the pending presence update immediately.
Skips the REST call if the (status, message) pair is identical
to the last sent one (caching).
"""
with self._coalesce_lock:
status = self._pending_status
message = self._pending_message
self._pending_status = None
self._pending_message = ""
self._coalesce_timer = None
if status is None:
return
# Caching: skip if identical to last sent
if status == self._last_sent_status and message == self._last_sent_message:
return
if not self._enabled:
return
# Send via REST API
self._send_rest(status, message)
# Update cache
self._last_sent_status = status
self._last_sent_message = message
def _send_rest(self, status: str, message: str) -> None:
"""Send the presence update via REST API.
POST /api/v1/users.setStatus with {"status": "...", "message": "..."}
Called in a background thread (via Timer), non-blocking.
Args:
status: Rocket.Chat status ('online', 'away', 'busy').
message: Custom status message.
"""
if self._rest is None:
return
if not self._rest.auth_token:
return
try:
data = {"status": status}
if message:
data["message"] = message
self._rest._request("POST", "/api/v1/users.setStatus",
headers={
"X-Auth-Token": self._rest.auth_token,
"X-User-Id": self._rest.user_id,
},
data=data)
logger.info(
"[presence] Status set: status=%s, message=%s",
status, message[:50] if message else "",
)
except Exception as e:
logger.warning("[presence] Failed to set status: %s", e)
# ── DetectionTimer Callback ──────────────────────────────────────────
def _on_detection_change(self, is_active: bool) -> None:
"""Callback from DetectionTimer: start/stop PulseController.
When background agents are detected (is_active=True), start pulsing.
When no background agents (is_active=False), stop pulsing.
"""
if not self._enabled:
return
if is_active:
if not self._pulse_controller.is_running():
self._pulse_controller.start()
logger.info("[presence] PulseController gestartet (Hintergrund-Agenten erkannt)")
else:
if self._pulse_controller.is_running():
self._pulse_controller.stop()
logger.info("[presence] PulseController gestoppt (keine Hintergrund-Agenten)")
# ── Convenience: Determine and set appropriate presence ──────────────
def update_presence(self) -> None:
"""Determine the appropriate presence state and schedule an update.
Priority (highest first):
1. Error state → away + error message
2. Onboarding active → away + onboarding message
3. Move request pending → away + move request message
4. Active tasks > 0 → busy + room message
5. Active tasks == 0 → online
"""
if not self._enabled:
return
# 1. Error state
if self._error_state:
msg = _format_presence_message("away_error", error=self._error_state)
self._set_presence("away", msg)
return
# 2. Onboarding active
if self._onboarding_active:
msg = _format_presence_message("away_onboarding")
self._set_presence("away", msg)
return
# 3. Move request pending
if self._move_request_pending:
# Use the first pending room name
room_name = next(iter(self._move_request_pending.values()), "")
msg = _format_presence_message("away_move_request", room_name=room_name)
self._set_presence("away", msg)
return
# 3b. P2-2: Clarification pending (nach Move-Request, vor Active-Tasks)
if self._clarification_pending:
msg = _format_presence_message("away_clarification")
self._set_presence("away", msg)
return
# 4. Active tasks
with self._active_tasks_lock:
active = self._active_tasks
if active > 0:
msg = _format_presence_message("busy", room_name=self._current_room_name)
self._set_presence("busy", msg)
else:
self._set_presence("online", "")
def shutdown(self) -> None:
"""Clean shutdown: stop PulseController, DetectionTimer, cancel coalesce timer."""
self._pulse_controller.stop()
self._detection_timer.stop()
self._cancel_honeymoon_timer()
with self._coalesce_lock:
if self._coalesce_timer is not None:
self._coalesce_timer.cancel()
self._coalesce_timer = None
# ── PulseController Integration ──────────────────────────────────────
def cancel_pending(self) -> None:
"""Cancel any pending pulse tick (K2: API auf PresenceEngine).
Called by _set_presence when a higher-priority status fires
while the PulseController is running (EC-5).
"""
self._pulse_controller.cancel_pending()
# ═══════════════════════════════════════════════════════════════════════════
# PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s Intervall)
# ═══════════════════════════════════════════════════════════════════════════
class PulseController:
"""DDP-based pulse timer: toggles online↔away at configurable interval.
Uses DDP set_status (NOT REST) for the status toggle.
REST fallback only for message text (K1: DDP set_status has no message variant).
Thread-safe: uses threading.Event for start/stop signalling.
Coalesce: skips duplicate status calls (if already away and tick wants away).
"""
def __init__(
self,
pulse_interval: float = 1.5,
_clamp_pulse: bool = True,
):
"""Initialize PulseController.
Args:
pulse_interval: Pulse interval in seconds (default 1.5).
_clamp_pulse: If True, clamp to 0.5-30s. Set False for testing.
"""
if _clamp_pulse:
self._pulse_interval: float = max(0.5, min(30.0, float(pulse_interval)))
else:
self._pulse_interval: float = float(pulse_interval)
self._ddp: Optional[object] = None
self._rest: Optional[object] = None
self._thread: Optional[threading.Thread] = None
self._running = threading.Event()
self._paused = threading.Event()
self._phase: bool = False # False=online, True=away
self._last_sent_phase: Optional[bool] = None
self._background_count: int = 0
self._cancel_pending_event = threading.Event() # B6: thread-safe via Event statt bool
# P1-2 O-2: Async-await bridge
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._await_timeout: float = 1.0 # V8.8: 1.0s statt 2.0s — schneller fail bei 429
# Phase 5: pulse_target — "away" (default) oder "busy"
# "away": pulsiert online↔away (Subagent läuft, Hauptagent idle)
# "busy": pulsiert Message bei busy-Status (Subagent läuft, Hauptagent busy)
self._pulse_target: str = "away"
self._mode_lock = threading.Lock() # Mode-Sentinel (Risiko #2)
self._tick_counter: int = 0 # für Message-only-every-2-ticks
# V8.8: Mode-abhängige Pulse-Intervalle
# away-pulse: 3.0s (weniger aggressiv, vermeidet 429)
# busy-pulse: 1.5s (schnelle Reaktion auf busy-Status)
self._away_pulse_interval: float = 3.0
self._busy_pulse_interval: float = 1.5
# P1: Circuit-Breaker — verhindert 429-Endlosschleife im Gateway
# States: CLOSED (normal) → OPEN (nach N×429: Pause) → HALF_OPEN (Test-Ping)
self._breaker_state: str = "CLOSED"
self._consecutive_429s: int = 0
self._breaker_opened_at: float = 0.0
self._breaker_cooldown_s: float = 30.0
self._breaker_429_threshold: int = 1 # V8.8: 1 statt 3 — sofort nach erstem 429
self._base_pulse_interval: float = self._pulse_interval
self._backoff_level: int = 0
# Adaptive Backoff: pulse_interval wird bei OPEN eskaliert
self._backoff_intervals: tuple = (5.0, 15.0, 60.0)
# ── Public API ───────────────────────────────────────────────────────
def bind_ddp(self, ddp: object) -> None:
"""Bind a DDP client reference for set_status calls.
Args:
ddp: DDPClient instance with set_status(status) method.
"""
self._ddp = ddp
def bind_rest(self, rest: object) -> None:
"""Bind a REST client reference for fallback status+message calls.
Args:
rest: RocketChatREST instance with _request method.
"""
self._rest = rest
def bind_loop(self, loop: asyncio.AbstractEventLoop) -> None:
"""P1-2 O-2: Bind the asyncio event loop for async-await bridge.
When a loop is bound, _pulse_tick delegates to _pulse_tick_async
via run_coroutine_threadsafe. Without a loop, the legacy sync
path is used (graceful degradation).
Args:
loop: The running asyncio event loop.
"""
self._loop = loop
def set_background_count(self, count: int) -> None:
"""Set the background task count for heartbeat messages."""
self._background_count = count
def set_pulse_target(self, target: str) -> bool:
"""Phase 5: Set the pulse target mode with Mode-Sentinel.
V8.8: Mode-abhängige Pulse-Intervalle:
- "away": 3.0s (weniger aggressiv, vermeidet 429)
- "busy": 1.5s (schnelle Reaktion auf busy-Status)
Args:
target: "away" (pulse online↔away) or "busy" (pulse message while busy).
Returns:
True if mode was changed, False if already in that mode.
Raises:
ValueError: if target is not "away" or "busy".
"""
if target not in ("away", "busy"):
raise ValueError(f"pulse_target must be 'away' or 'busy', got '{target}'")
with self._mode_lock:
if self._pulse_target == target:
return False
old = self._pulse_target
self._pulse_target = target
# V8.8: Dynamisches Pulse-Interval je nach Mode
# Nur anpassen wenn Circuit-Breaker CLOSED (nicht im Backoff)
if self._breaker_state == "CLOSED":
if target == "away":
self._pulse_interval = self._away_pulse_interval
self._base_pulse_interval = self._away_pulse_interval
else: # busy
self._pulse_interval = self._busy_pulse_interval
self._base_pulse_interval = self._busy_pulse_interval
logger.info(
"[pulse] pulse_target: %s → %s (interval=%.1fs)",
old, target, self._pulse_interval,
)
return True
def get_pulse_target(self) -> str:
"""Phase 5: Get the current pulse target mode."""
return self._pulse_target
def start(self) -> None:
"""Start the pulse thread."""
logger.info(
"[pulse] start() called, _running=%s, _ddp=%s, _phase=%s, _paused=%s",
self._running.is_set(),
self._ddp is not None,
self._phase,
self._paused.is_set(),
)
if self._running.is_set():
logger.info("[pulse] start() skip: already running")
return
# P1-1: Check DDP availability before starting
if self._ddp is None:
logger.warning(
"[pulse] PulseController.start() called without DDP bound — "
"pulses will have no effect until bind_ddp() is called"
)
self._running.set()
self._paused.clear()
self._phase = False # Start with online
self._last_sent_phase = None
self._thread = threading.Thread(
target=self._pulse_loop,
daemon=True,
name="pulse-controller",
)
self._thread.start()
logger.info(
"[pulse] PulseController started (interval=%.1fs, loop-bound=%s, async-path=%s)",
self._pulse_interval,
self._loop is not None,
self._loop is not None and self._loop.is_running(),
)
def stop(self) -> None:
"""Stop the pulse thread and wait for it to finish."""
if not self._running.is_set():
return
self._running.clear()
self._paused.clear()
if self._thread is not None and self._thread.is_alive():
self._thread.join(timeout=self._pulse_interval + 1)
self._thread = None
logger.info("[pulse] PulseController stopped")
def pause(self) -> None:
"""Pause pulsing without stopping the thread (EC-2: reconnect race)."""
self._paused.set()
logger.debug("[pulse] PulseController paused")
def resume(self) -> None:
"""Resume pulsing after pause (EC-2: reconnect race)."""
self._paused.clear()
logger.debug("[pulse] PulseController resumed")
def is_running(self) -> bool:
"""Check if the pulse thread is running."""
return self._running.is_set()
def cancel_pending(self) -> None:
"""Cancel any pending pulse tick (K2: EC-5).
Called by PresenceEngine._set_presence when a higher-priority
status fires while the PulseController is running.
Sets a flag that the next tick will skip.
"""
self._cancel_pending_event.set()
logger.debug("[pulse] cancel_pending: next tick will be skipped")
# ── P1: Circuit-Breaker — 429-Schutz ──────────────────────────────────
def _classify_ddp_error(self, error: Exception) -> str:
"""Classify a DDP error to decide whether it triggers REST fallback.
'server returned false' is a transient DDP protocol quirk — NOT a
real error. It must NOT trigger a REST fallback, because that REST
call would itself hit 429 and cascade into the Gateway hang.
Returns:
'429' — rate-limit error (triggers breaker)
'ddp_transient' — DDP protocol noise, no fallback
'other' — real error, REST fallback allowed
"""
error_str = str(error).lower()
if "429" in error_str or "too many requests" in error_str or "rate limit" in error_str:
return "429"
if "server returned false" in error_str:
return "ddp_transient"
return "other"
def _record_429(self) -> None:
"""Record a 429 error and transition breaker state.
CLOSED + consecutive_429s >= threshold → OPEN (pause + backoff)
HALF_OPEN + 429 → OPEN (stay open, escalate backoff)
"""
self._consecutive_429s += 1
logger.warning(
"[pulse] Circuit-Breaker: 429 #%d/%d (state=%s)",
self._consecutive_429s, self._breaker_429_threshold, self._breaker_state,
)
if self._breaker_state == "CLOSED" and self._consecutive_429s >= self._breaker_429_threshold:
self._breaker_state = "OPEN"
self._breaker_opened_at = time.monotonic()
# Use current backoff_level, THEN increment for next cycle
self._pulse_interval = self._backoff_intervals[self._backoff_level]
self._backoff_level = min(self._backoff_level + 1, len(self._backoff_intervals) - 1)
logger.warning(
"[pulse] Circuit-Breaker: CLOSED→OPEN (cooldown=%.0fs, backoff_level=%d, "
"pulse_interval=%.1fs)",
self._breaker_cooldown_s, self._backoff_level, self._pulse_interval,
)
elif self._breaker_state == "HALF_OPEN":
self._breaker_state = "OPEN"
self._breaker_opened_at = time.monotonic()
# Use current backoff_level, THEN increment for next cycle
self._pulse_interval = self._backoff_intervals[self._backoff_level]
self._backoff_level = min(self._backoff_level + 1, len(self._backoff_intervals) - 1)
logger.warning(
"[pulse] Circuit-Breaker: HALF_OPEN→OPEN (test ping failed, "
"backoff_level=%d, pulse_interval=%.1fs)",
self._backoff_level, self._pulse_interval,
)
def _record_success(self) -> None:
"""Record a successful status set and reset breaker to CLOSED."""
if self._breaker_state != "CLOSED":
logger.info(
"[pulse] Circuit-Breaker: %s→CLOSED (success, backoff_level=%d→0, "
"pulse_interval=%.1fs→%.1fs)",
self._breaker_state, self._backoff_level,
self._pulse_interval, self._base_pulse_interval,
)
self._breaker_state = "CLOSED"
self._consecutive_429s = 0
self._backoff_level = 0
self._pulse_interval = self._base_pulse_interval
def _check_breaker(self) -> bool:
"""Check if the circuit breaker allows a tick.
CLOSED: allow
OPEN: if cooldown elapsed → HALF_OPEN (allow one test ping), else block
HALF_OPEN: allow (the test ping)
Returns:
True if tick is allowed, False if blocked.
"""
if self._breaker_state == "CLOSED":
return True
if self._breaker_state == "OPEN":
elapsed = time.monotonic() - self._breaker_opened_at
if elapsed >= self._breaker_cooldown_s:
self._breaker_state = "HALF_OPEN"
logger.info(
"[pulse] Circuit-Breaker: OPEN→HALF_OPEN (cooldown elapsed, "
"sending test ping, pulse_interval=%.1fs)",
self._pulse_interval,
)
return True
else:
logger.debug(
"[pulse] Circuit-Breaker: OPEN (cooldown %.0f/%.0fs remaining)",
self._breaker_cooldown_s - elapsed, self._breaker_cooldown_s,
)
return False
# HALF_OPEN: allow the test ping
return True
def get_breaker_state(self) -> str:
"""Return current breaker state (for testing)."""
return self._breaker_state
def get_consecutive_429s(self) -> int:
"""Return current consecutive 429 count (for testing)."""
return self._consecutive_429s
def get_effective_pulse_interval(self) -> float:
"""Return current effective pulse interval (for testing)."""
return self._pulse_interval
# ── Internal: Pulse Loop ─────────────────────────────────────────────
def _pulse_loop(self) -> None:
"""Background thread: pulse between online and away."""
logger.info("[pulse] _pulse_loop started, interval=%.1fs", self._pulse_interval)
iteration = 0
while self._running.is_set():
iteration += 1
# Check if paused
if self._paused.is_set():
if iteration == 1 or iteration % 50 == 0:
logger.debug(
"[pulse] _pulse_loop iteration=%d: PAUSED (waiting for resume)",
iteration,
)
time.sleep(0.1)
continue
logger.debug(
"[pulse] _pulse_loop iteration=%d: calling _pulse_tick, phase=%s, ddp=%s",
iteration,
self._phase,
self._ddp is not None,
)
self._pulse_tick()
# Sleep for pulse interval, checking running flag periodically
for _ in range(int(self._pulse_interval * 10)):
if not self._running.is_set():
break
if self._paused.is_set():
break
time.sleep(0.1)
def _pulse_tick(self) -> None:
"""Execute one pulse tick: toggle phase and send status.
P1: Circuit-Breaker check before any I/O — if OPEN and cooldown
not elapsed, skip the tick entirely. DDP errors are classified:
'server returned false' does NOT trigger REST fallback.
P1-2 O-2: When an asyncio loop is bound, delegates to
_pulse_tick_async via run_coroutine_threadsafe. Otherwise
uses the legacy sync path (graceful degradation).
"""
logger.debug(
"[pulse] _pulse_tick fired, phase=%s, ddp=%s, paused=%s, cancel_pending=%s, "
"breaker=%s, loop=%s",
self._phase,
self._ddp is not None,
self._paused.is_set(),
self._cancel_pending_event.is_set(),
self._breaker_state,
self._loop is not None,
)
# P0-2: Check cancel_pending flag (set by PresenceEngine._set_presence)
# B6: thread-safe via threading.Event statt bool
if self._cancel_pending_event.is_set():
self._cancel_pending_event.clear()
logger.debug("[pulse] _pulse_tick skip: cancel_pending was set")
return
# P1: Circuit-Breaker — block tick if OPEN and cooldown not elapsed
if not self._check_breaker():
logger.debug("[pulse] _pulse_tick skip: circuit breaker OPEN")
return
# Toggle phase
self._phase = not self._phase
# Coalesce: skip if same phase as last sent
if self._phase == self._last_sent_phase:
logger.debug(
"[pulse] _pulse_tick skip: coalesce (phase=%s == last_sent)",
self._phase,
)
return
# P1-2 O-2: Delegate to async path if loop is bound and running
if self._loop is not None and self._loop.is_running():
try:
future = asyncio.run_coroutine_threadsafe(
self._pulse_tick_async(),
self._loop,
)
# B5: Polling mit Pause-Check — pause() wirkt in 50ms statt 1.5s.
# future.result(timeout=...) blockiert bis zu pulse_interval,
# währenddessen kann pause() nicht greifen.
while not future.done():
if self._paused.is_set():
future.cancel()
logger.debug("[pulse] _pulse_tick async cancelled by pause")
break
time.sleep(0.05)
if not future.cancelled():
future.result(timeout=0) # already done, no blocking
return
except Exception as e:
logger.info(
"[pulse] _pulse_tick async path failed: %s — falling back to sync",
e,
)
# Fall through to legacy sync path below
# ── Legacy sync path (no loop bound, or async path failed) ──────
status = "away" if self._phase else "online"
logger.debug("[pulse] _pulse_tick sending (sync): status=%s", status)
# Try DDP first (K1: DDP set_status has no message variant)
ddp_error_type = None
if self._ddp is not None and getattr(self._ddp, 'connected', False):
try:
self._ddp.set_status(status)
self._last_sent_phase = self._phase
self._increment_telemetry()
self._record_success()
logger.debug("[pulse] _pulse_tick DDP set_status OK: %s", status)
return
except Exception as e:
ddp_error_type = self._classify_ddp_error(e)
logger.info(
"[pulse] _pulse_tick DDP set_status failed: %s (classified=%s)",
e, ddp_error_type,
)
if ddp_error_type == "429":
self._record_429()
return # P1: 429 → no REST fallback, stop here
# ddp_transient: no REST fallback, just skip
if ddp_error_type == "ddp_transient":
return
# 'other': fall through to REST fallback
# REST fallback for message text (only for non-429, non-transient DDP errors)
if self._rest is not None and getattr(self._rest, 'auth_token', None):
try:
msg = ""
if self._phase:
msg = _format_presence_message("heartbeat", background_count=self._background_count)
self._rest._request(
"POST", "/api/v1/users.setStatus",
headers={
"X-Auth-Token": self._rest.auth_token,
"X-User-Id": self._rest.user_id,
},
data={"status": status, "message": msg} if msg else {"status": status},
)
self._last_sent_phase = self._phase
self._increment_telemetry()
self._record_success()
logger.debug("[pulse] _pulse_tick REST setStatus OK: %s", status)
except Exception as e:
error_str = str(e).lower()
if "429" in error_str or "too many requests" in error_str:
self._record_429()
return # P1: 429 → stop here, symmetric with DDP path
logger.info("[pulse] _pulse_tick REST setStatus failed: %s", e)
else:
logger.debug(
"[pulse] _pulse_tick skip: no DDP and no REST available (ddp=%s, rest=%s)",
self._ddp is not None,
self._rest is not None,
)
async def _pulse_tick_async(self) -> None:
"""P1-2 O-2: Async pulse tick using await set_status_async.
P1: DDP errors are classified — 'server returned false' does NOT
trigger REST fallback. 429 errors trigger circuit breaker.
Runs on the asyncio event loop (dispatched via
run_coroutine_threadsafe from the pulse thread).
Uses DDPClient.set_status_async for true await-semantics
with timeout and error handling.
"""
status = "away" if self._phase else "online"
logger.debug("[pulse] _pulse_tick_async sending: status=%s", status)
# Try DDP with await-semantics
if self._ddp is not None and getattr(self._ddp, 'connected', False):
try:
await self._ddp.set_status_async(status, timeout=self._await_timeout)
self._last_sent_phase = self._phase
self._increment_telemetry()
self._record_success()
logger.debug("[pulse] _pulse_tick_async DDP set_status_async OK: %s", status)
return
except Exception as e:
ddp_error_type = self._classify_ddp_error(e)
logger.info(
"[pulse] _pulse_tick_async DDP set_status_async failed: %s (classified=%s)",
e, ddp_error_type,
)
if ddp_error_type == "429":
self._record_429()
return # P1: 429 → no REST fallback
if ddp_error_type == "ddp_transient":
return # P1: transient → no REST fallback
# 'other': fall through to REST fallback
# REST fallback for message text (only for non-429, non-transient DDP errors)
if self._rest is not None and getattr(self._rest, 'auth_token', None):
try:
msg = ""
if self._phase:
msg = _format_presence_message("heartbeat", background_count=self._background_count)
self._rest._request(
"POST", "/api/v1/users.setStatus",
headers={
"X-Auth-Token": self._rest.auth_token,
"X-User-Id": self._rest.user_id,
},
data={"status": status, "message": msg} if msg else {"status": status},
)
self._last_sent_phase = self._phase
self._increment_telemetry()
self._record_success()
logger.debug("[pulse] _pulse_tick_async REST setStatus OK: %s", status)
except Exception as e:
error_str = str(e).lower()
if "429" in error_str or "too many requests" in error_str:
self._record_429()
return # P1: 429 → stop here, symmetric with DDP path
logger.info("[pulse] _pulse_tick_async REST setStatus failed: %s", e)
else:
logger.debug(
"[pulse] _pulse_tick_async skip: no DDP and no REST available",
)
def _increment_telemetry(self) -> None:
"""Increment the heartbeat_pulse telemetry counter.
NOTE: Coupled to archivar.routing_telemetry.routing_telemetry.
This is a cross-module dependency that should be refactored
to use a shared telemetry interface or event bus.
"""
try:
from archivar.routing_telemetry import routing_telemetry
routing_telemetry.heartbeat_pulse += 1
except Exception:
pass
# ═══════════════════════════════════════════════════════════════════════════
# DetectionTimer — erkennt Hintergrund-Agenten (10s Intervall)
# ═══════════════════════════════════════════════════════════════════════════
class DetectionTimer:
"""Detects whether background agents are active.
P2 Fix Option D: PID-Sentinel ist PRIMARY — prüft ob Gateway-Prozess lebt.
gateway_state.json ist SECONDARY — active_agents > 0 bedeutet Subagenten aktiv.
plugin_state.json ist TERTIARY — background_tasks > 0 bedeutet aktiv.
pgrep ist QUATERNARY/FALLBACK — 'hermes_cli|hermes chat|gateway run'.
pgrep pattern: 'hermes_cli|hermes chat|gateway run' (fängt Subagenten
UND Gateway-Prozess). Self-pid exclude bleibt erhalten.
Semantik: Idle ≠ Abwesend. Wenn PID-Sentinel 'alive' liefert UND keine
Subagenten aktiv → Status 'online' (grün), nicht 'inactive'.
'inactive' (gelb) bedeutet NUR: Gateway-Prozess nicht gefunden.
Calls on_change callback when detection state changes.
"""
def __init__(
self,
gateway_state_path: str = "",
detection_interval: float = 10.0,
on_change: Optional[Callable[[bool], None]] = None,
plugin_state_path: str = "",
):
"""Initialize DetectionTimer.
Args:
gateway_state_path: Path to gateway_state.json.
detection_interval: Check interval in seconds (default 10).
on_change: Callback(is_active) when detection state changes.
plugin_state_path: P1-2: Path to plugin state file. Defaults to
~/.hermes/plugin_state/hermes_rocket_plugin.json.
"""
if not gateway_state_path:
gateway_state_path = os.environ.get(
"ROCKETCHAT_GATEWAY_STATE_PATH",
os.path.expanduser("~/.hermes/gateway_state.json"),
)
self._gateway_state_path = gateway_state_path
# P1-2: Plugin-State-Datei für Gateway-interne Subagenten
if not plugin_state_path:
plugin_state_path = _get_plugin_state_path()
self._plugin_state_path = plugin_state_path
self._detection_interval = detection_interval
self._on_change = on_change
self._thread: Optional[threading.Thread] = None
self._running = threading.Event()
self._last_result: Optional[bool] = False # Start with False to avoid spurious first callback
self._check_count: int = 0 # P0-1: tick counter for diagnostic logging
def start(self) -> None:
"""Start the detection timer thread."""
if self._running.is_set():
return
self._running.set()
self._thread = threading.Thread(
target=self._detection_loop,
daemon=True,
name="detection-timer",
)
self._thread.start()
logger.info("[detection] DetectionTimer started (interval=%.1fs)", self._detection_interval)
def stop(self) -> None:
"""Stop the detection timer thread."""
if not self._running.is_set():
return
self._running.clear()
if self._thread is not None and self._thread.is_alive():
self._thread.join(timeout=self._detection_interval + 1)
self._thread = None
logger.info("[detection] DetectionTimer stopped")
def _check_gateway_pid_alive(self) -> bool:
"""P2 Fix Option D: PID-Sentinel — prüft ob der Gateway-Prozess lebt.
Verwendet os.getppid() um den Parent-PID (Gateway-Prozess) zu ermitteln
und prüft ob /proc/<ppid> existiert. Dies ist das zuverlässigste Signal
für die Gateway-Präsenz, da es keine Datei-I/O oder Prozess-Suche benötigt.
Returns:
True wenn der Gateway-Parent-Prozess existiert, False sonst.
"""
try:
ppid = os.getppid()
# /proc/<ppid> existiert nur wenn der Prozess lebt
return os.path.exists(f"/proc/{ppid}")
except (OSError, ValueError):
return False
def check(self) -> bool:
"""Check if background agents are active.
P2 Fix Option D: PID-Sentinel ist PRIMARY — prüft ob Gateway-Prozess lebt.
gateway_state.json ist SECONDARY — active_agents > 0 bedeutet Subagenten aktiv.
plugin_state.json ist TERTIARY — background_tasks > 0 bedeutet aktiv.
pgrep ist QUATERNARY/FALLBACK — 'hermes_cli|hermes chat|gateway run'.
pgrep pattern: 'hermes_cli|hermes chat|gateway run' (fängt Subagenten
UND Gateway-Prozess). Self-pid exclude bleibt erhalten.
Semantik: Idle ≠ Abwesend. Wenn PID-Sentinel 'alive' liefert UND keine
Subagenten aktiv → Status 'online' (grün), nicht 'inactive'.
'inactive' (gelb) bedeutet NUR: Gateway-Prozess nicht gefunden.
Returns:
True if background agents are detected, False otherwise.
"""
self._check_count += 1
self._increment_telemetry()
result = False
gateway_active = 0
pid_used = False # P2: True if PID-Sentinel was the deciding signal
gateway_used = False # True if gateway_state was the deciding signal
plugin_used = False # P1-2: True if plugin_state was the deciding signal
plugin_bg_tasks = -1 # P1-2: -1 = not read, >=0 = count
detection_source = "none" # P1-2: which signal decided
# ── P2 PRIMARY: PID-Sentinel — prüft ob Gateway-Prozess lebt ────────
if self._check_gateway_pid_alive():
result = True
pid_used = True
detection_source = "gateway_pid"
# ── P2 SECONDARY: gateway_state.json (Schwelle >0, war >1) ──────────
if not pid_used:
try:
if os.path.exists(self._gateway_state_path):
with open(self._gateway_state_path, 'r') as f:
state = json.load(f)
gateway_active = state.get("active_agents", 0)
# P2 Fix: Schwelle >0 statt >1
if gateway_active > 0:
result = True
gateway_used = True
detection_source = "gateway"
except (json.JSONDecodeError, IOError, OSError) as e:
logger.debug("[detection] gateway_state.json read failed: %s", e)
# Fall through to plugin_state
# ── P1-2: TERTIARY: plugin_state.json ────────────────────────────────
if not pid_used and not gateway_used:
plugin_state = _read_plugin_state(self._plugin_state_path)
plugin_bg_tasks = plugin_state.get("background_tasks", 0)
if plugin_bg_tasks > 0:
result = True
plugin_used = True
detection_source = "plugin_state"
# ── V8.7: pgrep /proc scan — hermes chat --profile Prozesse ──
# Ersetzt subagent_status.json als vierte Quelle.
# Direkt /proc lesen, kein subprocess.
# V8.9: pgrep ALWAYS runs — not gated behind pid_sentinel/gateway_state.
# PID-Sentinel says "Gateway alive" (always true), pgrep says "Subagent active".
# Different semantics — pgrep must run independently.
pgrep_count = self._pgrep_hermes_subagents()
if pgrep_count > 0:
result = True
detection_source = "pgrep"
# ── Log: all signals, result, source ───────────────────────────────
plugin_str = str(plugin_bg_tasks) if plugin_bg_tasks >= 0 else "n/a"
logger.info(
"[detection] check #%d: pid_sentinel=%s, gateway_state=%d (primary=%s), "
"plugin_state=%s (bg_tasks=%s), pgrep=%d, "
"result=%s, source=%s",
self._check_count,
"alive" if pid_used else "dead",
gateway_active,
"yes" if gateway_used else "no",
"yes" if plugin_used else "no",
plugin_str,
pgrep_count,
"active" if result else "inactive",
detection_source,
)
# P1-2: Set telemetry source
self._set_detection_source_telemetry(detection_source)
# Notify on change (P1-2: callback fires from check() itself)
if result != self._last_result and self._on_change is not None:
try:
logger.info(
"[detection] state changed: %s→%s",
"active" if self._last_result else "inactive",
"active" if result else "inactive",
)
self._on_change(result)
except Exception as e:
logger.debug("[detection] on_change callback failed: %s", e)
self._last_result = result
return result
@staticmethod
def _pgrep_hermes_subagents() -> int:
"""V8.7: Scan /proc/*/cmdline for 'hermes chat --profile' processes.
V8.8: argv-basierter Scanner — verhindert False-Positives auf
Shell-Befehle die 'hermes'+'chat'+'--profile' als Text enthalten.
Algorithmus:
1. /proc/<pid>/cmdline lesen → null-byte-split → argv array
2. argv[0] basename prüfen: 'hermes', 'python', 'python3'
3. 'hermes': 'chat' und '--profile' als eigene argv-Elemente
4. 'python'/'python3': '-m hermes_cli.main' oder hermes-Skript-Pfad
in argv, UND 'chat' UND '--profile' als eigene Elemente
5. 'chat' muss eigenes argv-Element sein (kein Substring)
6. '--profile' muss eigenes argv-Element sein
7. Gateway-PID aus gateway_state.json ausschließen
8. Eigene PID ausschließen
Returns:
Number of matching processes (excluding self and gateway).
"""
own_pid = os.getpid()
# Gateway-PID aus gateway_state.json lesen
gateway_pid = DetectionTimer._read_gateway_pid()
count = 0
try:
for entry in os.listdir("/proc"):
if not entry.isdigit():
continue
pid = int(entry)
if pid == own_pid:
continue
if pid == gateway_pid:
continue
try:
with open(f"/proc/{entry}/cmdline", "rb") as f:
raw = f.read()
# cmdline is null-separated; decode and split into argv
argv = [a for a in raw.decode("utf-8", errors="replace").split("\x00") if a]
if not argv:
continue
# argv[0] basename
argv0 = os.path.basename(argv[0])
# Check: 'chat' and '--profile' must be separate argv elements
has_chat = "chat" in argv
has_profile = "--profile" in argv
if not (has_chat and has_profile):
continue
if argv0 == "hermes":
count += 1
elif argv0 in ("python", "python3"):
# Check for '-m hermes_cli.main' or hermes script path
is_hermes_python = False
for i, arg in enumerate(argv):
if arg == "-m" and i + 1 < len(argv):
if argv[i + 1].startswith("hermes_cli"):
is_hermes_python = True
break
elif os.path.basename(arg) == "hermes":
is_hermes_python = True
break
if is_hermes_python:
count += 1
except (OSError, IOError, PermissionError):
# Process may have exited or be inaccessible
continue
except (OSError, IOError):
pass
return count
@staticmethod
def _read_gateway_pid() -> Optional[int]:
"""V8.8: Gateway-PID aus gateway_state.json lesen.
Returns:
Gateway PID or None if not available.
"""
gateway_state_path = os.environ.get(
"ROCKETCHAT_GATEWAY_STATE_PATH",
os.path.expanduser("~/.hermes/gateway_state.json"),
)
try:
if os.path.exists(gateway_state_path):
with open(gateway_state_path, 'r') as f:
state = json.load(f)
return state.get("pid")
except (json.JSONDecodeError, IOError, OSError):
pass
return None
@staticmethod
def _pid_is_alive(pid: int) -> bool:
"""Check if a process with the given PID is alive.
Uses os.kill(pid, 0) which sends no signal but checks permissions
and process existence. Falls back to /proc/<pid>/ check.
Args:
pid: Process ID to check.
Returns:
True if the process exists, False otherwise.
"""
try:
os.kill(pid, 0)
return True
except OSError:
# Fallback: /proc/<pid>/ check
return os.path.exists(f"/proc/{pid}")
def _detection_loop(self) -> None:
"""Background thread: periodically check for background agents."""
tick = 0
while self._running.is_set():
tick += 1
try:
logger.info(
"[detection] tick #%d (interval=%.1fs)",
tick, self._detection_interval,
)
self.check() # check() now handles logging + callback
except Exception as e:
logger.debug("[detection] check failed: %s", e)
# Sleep for detection interval
for _ in range(int(self._detection_interval * 10)):
if not self._running.is_set():
break
time.sleep(0.1)
def _increment_telemetry(self) -> None:
"""Increment the heartbeat_detection telemetry counter.
NOTE: Coupled to archivar.routing_telemetry.routing_telemetry.
This is a cross-module dependency that should be refactored
to use a shared telemetry interface or event bus.
"""
try:
from archivar.routing_telemetry import routing_telemetry
routing_telemetry.heartbeat_detection += 1
except Exception:
pass
def _set_detection_source_telemetry(self, source: str) -> None:
"""P1-2: Set the heartbeat_detection_source telemetry field.
Args:
source: One of 'gateway', 'plugin_state', 'pgrep', 'none'.
"""
try:
from plugin.archivar.routing_telemetry import routing_telemetry
except ImportError:
try:
from archivar.routing_telemetry import routing_telemetry
except ImportError:
return
try:
routing_telemetry.heartbeat_detection_source = source
except Exception:
pass