Files
Hermes_rocket.chat_Plugin/plugin/archivar/presence_engine.py
T

1150 lines
46 KiB
Python

"""
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 subprocess
import threading
import time
import urllib.request
import urllib.error
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
# ═══════════════════════════════════════════════════════════════════════════
# 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.
"""
# 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()
# 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.
# on_agent_busy() pauses the pulse, 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.
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 to online now
self._cancel_honeymoon_timer()
self.update_presence()
logger.debug(
"[presence] Honeymoon abgelaufen (%.2fs) → online", 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 _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.
"""
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 → online"
)
self.update_presence()
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.
Returns:
New counter value.
"""
with self._background_tasks_lock:
self._background_tasks += 1
count = self._background_tasks
self._pulse_controller.set_background_count(count)
return count
def decrement_background_tasks(self) -> int:
"""Decrement background tasks counter. Thread-safe.
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)
if count == 0:
self._pulse_controller.stop()
return count
# ── 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()
def on_agent_busy(self, room_name: str = "") -> None:
"""Hook: Agent is processing a message — pause pulse, set busy.
Priority 1 (highest): busy (rot) — Nachricht wird verarbeitet.
"""
self.set_current_room(room_name)
self.increment_active_tasks()
self.update_presence()
# Pause pulse if running
self._pulse_controller.pause()
def on_message_received(self, room_name: str = "") -> None:
"""Hook: Message received — same as on_agent_busy.
Alias for on_agent_busy for semantic clarity.
"""
self.on_agent_busy(room_name=room_name)
# ═══════════════════════════════════════════════════════════════════════════
# 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: bool = False # P0-2: skip next tick flag
# P1-2 O-2: Async-await bridge
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._await_timeout: float = 2.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 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 = True
logger.debug("[pulse] cancel_pending: next tick will be skipped")
# ── 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-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, loop=%s",
self._phase,
self._ddp is not None,
self._paused.is_set(),
self._cancel_pending,
self._loop is not None,
)
# P0-2: Check cancel_pending flag (set by PresenceEngine._set_presence)
if self._cancel_pending:
self._cancel_pending = False
logger.debug("[pulse] _pulse_tick skip: cancel_pending was set")
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)
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()
logger.debug("[pulse] _pulse_tick DDP set_status OK: %s", status)
return
except Exception as e:
logger.info("[pulse] _pulse_tick DDP set_status failed: %s", e)
# REST fallback for message text
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()
logger.debug("[pulse] _pulse_tick REST setStatus OK: %s", status)
except Exception as e:
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.
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()
logger.debug("[pulse] _pulse_tick_async DDP set_status_async OK: %s", status)
return
except Exception as e:
logger.info(
"[pulse] _pulse_tick_async DDP set_status_async failed: %s — "
"falling back to REST",
e,
)
# REST fallback for message text
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()
logger.debug("[pulse] _pulse_tick_async REST setStatus OK: %s", status)
except Exception as e:
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.
P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
pgrep is SECONDARY/CONFIRM — used as fallback when gateway_state is
unavailable or returns 0/1 (ambiguous).
pgrep pattern: 'hermes_cli|hermes chat' (catches subagents AND gateway
subprocesses). Self-pid exclude is preserved.
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,
):
"""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.
"""
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
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(self) -> bool:
"""Check if background agents are active.
P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
pgrep is SECONDARY/CONFIRM — used as fallback when gateway_state is
unavailable or returns 0/1 (ambiguous).
pgrep pattern expanded from 'hermes chat --profile' to
'hermes_cli|hermes chat' to catch subagents AND gateway subprocesses.
Self-pid exclude is preserved.
Returns:
True if background agents are detected, False otherwise.
"""
self._check_count += 1
self._increment_telemetry()
result = False
pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error
gateway_active = 0
gateway_used = False # True if gateway_state was the deciding signal
# ── PRIMARY: gateway_state.json ────────────────────────────────────
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)
if gateway_active > 1:
result = True
gateway_used = True
except (json.JSONDecodeError, IOError, OSError) as e:
logger.debug("[detection] gateway_state.json read failed: %s", e)
# Fall through to pgrep
# ── SECONDARY: pgrep — run when gateway_state didn't decide ───────
if not gateway_used:
try:
own_pid = os.getpid()
# P1b: Expanded pattern catches subagents AND gateway subprocesses
proc = subprocess.run(
["pgrep", "-f", "hermes_cli|hermes chat"],
capture_output=True,
text=True,
timeout=5,
)
# Parse PIDs and self-exclude
raw_lines = [l.strip() for l in proc.stdout.strip().split("\n") if l.strip()]
all_pids = [int(l) for l in raw_lines if l.isdigit()]
pids = [p for p in all_pids if p != own_pid]
pgrep_pids = len(pids)
result = pgrep_pids > 0
except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
logger.debug("[detection] pgrep failed: %s", e)
# pgrep_pids stays -1 (error sentinel)
# ── Log: both signals, result ─────────────────────────────────────
pgrep_str = str(pgrep_pids) if pgrep_pids >= 0 else "error"
logger.info(
"[detection] check #%d: gateway_state=%d (primary=%s), pgrep=%s, result=%s",
self._check_count, gateway_active,
"yes" if gateway_used else "no",
pgrep_str,
"active" if result else "inactive",
)
# 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
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