V9: Presence-Engine Schachuhr-Architektur — ereignisgesteuert via Core-Hooks
presence_engine.py: 1754→~400 Zeilen (-77%)
- PulseController (575 Z.) ENTFERNT
- DetectionTimer (Polling) ENTFERNT
- Coalesce-Timer ENTFERNT
- Honeymoon-Timer ENTFERNT
- DDP setDefaultStatus ENTFERNT
- gateway_state.json-Polling ENTFERNT
- pgrep-Scanner ENTFERNT
+ Counter-Dict {main_agent, delegate_subagent, chat_profile, background_term}
+ State-Maschine: ONLINE↔BUSY via sum(counters)
+ schedule_transition(): last-wins, asyncio.create_task
+ away-grace: 1 async Task (2s), gecancelt bei naechstem BUSY-Hook
+ REST-only: POST /api/v1/users.setStatus
+ 8 Hook-Callbacks (6 Core + 2 Tool-Filter fuer O-1 Workaround)
adapter.py: Alle V8.x-Referenzen entfernt
- Kein PulseController, kein DDP-Binding, kein DetectionTimer
- Kein Busy-Done-Debounce (post_llm_call Hook uebernimmt)
- Kein SubagentTracker
+ bind_loop() direkt auf PresenceEngine
__init__.py: 8 Hooks via ctx.register_hook() registriert
- pre_gateway_dispatch, post_llm_call
- subagent_start, subagent_stop
- on_session_start, on_session_end
- pre_tool_call, post_tool_call (O-1: terminal bg=true Filter)
subagent_tracker.py: GELOESCHT (durch subagent_start/stop Hooks ersetzt)
Tests: 36 neue V9-Tests PASSED, 99 V8.x-Tests SKIPPED
- 6 Hook-Trigger-Tests
- 4 Counter-Tests
- 3 Race-Tests
- Zusatz: Telemetrie, BusyMessage, EnableDisable, Shutdown
Pitfalls eliminiert: P-006, P-007 (register/complete-Race),
P-010 (DDP 429 — REST-only, keine Pulse mehr)
Architektur: docs/architecture/2026-08-03-presence-engine-schachuhr.md
This commit is contained in:
+68
-223
@@ -1219,57 +1219,31 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self._inline_commands = InlineCommandRegistry()
|
||||
self._register_inline_commands()
|
||||
|
||||
# V8.6: PresenceEngine — Aktivitäts-Indikator
|
||||
# V9: PresenceEngine — Schachuhr-Architektur (Hook-basiert)
|
||||
try:
|
||||
from archivar.presence_engine import PresenceEngine
|
||||
_presence_enabled = os.getenv("ROCKETCHAT_PRESENCE_ENABLED", "true").strip().lower() not in ("false", "0", "no", "off")
|
||||
_coalesce_ms = int(os.getenv("ROCKETCHAT_PRESENCE_COALESCE_MS", "2000"))
|
||||
_pulse_interval = float(os.getenv("ROCKETCHAT_PRESENCE_PULSE_INTERVAL", "1.5"))
|
||||
_away_grace_s = float(os.getenv("ROCKETCHAT_PRESENCE_AWAY_GRACE_S", "2.0"))
|
||||
self._presence_engine = PresenceEngine(
|
||||
rest=self.rest,
|
||||
enabled=_presence_enabled,
|
||||
coalesce_ms=_coalesce_ms,
|
||||
pulse_interval=_pulse_interval,
|
||||
away_grace_s=_away_grace_s,
|
||||
)
|
||||
# P0-1: PulseController mit REST und DDP verdrahten
|
||||
self._presence_engine._pulse_controller.bind_rest(self.rest)
|
||||
if self.ddp:
|
||||
self._presence_engine._pulse_controller.bind_ddp(self.ddp)
|
||||
# P2-2: PresenceEngine an ArchivarMessageHandler weiterreichen
|
||||
# V9: Kein PulseController, kein DDP, kein DetectionTimer mehr.
|
||||
# Hook-Registrierung erfolgt in plugin/__init__.py via ctx.register_hook().
|
||||
if self.archivar is not None:
|
||||
self.archivar.set_presence_engine(self._presence_engine)
|
||||
logger.info(
|
||||
"[rocketchat] V8.6: PresenceEngine initialisiert (enabled=%s, coalesce_ms=%s, pulse_interval=%.1fs)",
|
||||
"[rocketchat] V9: PresenceEngine initialisiert (enabled=%s, away_grace=%.1fs)",
|
||||
_presence_enabled,
|
||||
_coalesce_ms,
|
||||
_pulse_interval,
|
||||
_away_grace_s,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"[rocketchat] V8.6: PresenceEngine-Initialisierung FEHLGESCHLAGEN: %s",
|
||||
"[rocketchat] V9: PresenceEngine-Initialisierung FEHLGESCHLAGEN: %s",
|
||||
e,
|
||||
)
|
||||
self._presence_engine = None # Graceful degradation -> alter Idle-Timer greift
|
||||
|
||||
# V8.9 P1: Busy-Done-Debounce — verhindert dass mark_busy_done feuert
|
||||
# während der Agent noch arbeitet. Der finally-Block von _process_incoming
|
||||
# startet einen 10s-Timer; jeder send()-Call resettet ihn. Erst wenn 10s
|
||||
# lang keine Nachricht mehr gesendet wurde, ist der Agent wirklich fertig.
|
||||
self._agent_dispatched_this_turn: bool = False
|
||||
self._busy_done_debounce_task: Optional[asyncio.Task] = None
|
||||
self._busy_done_debounce_lock = asyncio.Lock()
|
||||
|
||||
# Phase 5: SubagentTracker — Subagent-Status für PresenceEngine
|
||||
try:
|
||||
from archivar.subagent_tracker import get_tracker
|
||||
self._subagent_tracker = get_tracker()
|
||||
logger.info("[rocketchat] Phase 5: SubagentTracker initialisiert")
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"[rocketchat] Phase 5: SubagentTracker-Initialisierung FEHLGESCHLAGEN: %s",
|
||||
e,
|
||||
)
|
||||
self._subagent_tracker = None # Graceful degradation
|
||||
self._presence_engine = None # Graceful degradation
|
||||
|
||||
def _build_room_map_summary(self) -> str:
|
||||
"""Baut eine menschenlesbare Raum-Map-Übersicht für den System-Prompt.
|
||||
@@ -1307,31 +1281,14 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
def _on_ddp_connected(self) -> None:
|
||||
"""Callback when DDP connection is established.
|
||||
|
||||
Sets initial online status and binds DDP to PulseController
|
||||
if PresenceEngine is active (EC-1: on_connected_cb race).
|
||||
|
||||
P1b: Starts DetectionTimer after DDP connection is established
|
||||
to prevent race condition with gateway_state.json.
|
||||
Sets initial online status via DDP.
|
||||
V9: Kein PulseController, kein DetectionTimer mehr.
|
||||
"""
|
||||
if self.ddp:
|
||||
# B3: Bewusst sync — first status after connect does not need
|
||||
# await-confirmation. PulseController takes over with
|
||||
# set_status_async on the next tick (1.5s). This avoids a
|
||||
# 2s-await-wait during the critical connect path.
|
||||
# await-confirmation.
|
||||
self.ddp.set_status("online")
|
||||
# V8.6: PulseController DDP-Bindung nach Connect (EC-1)
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
|
||||
try:
|
||||
self._presence_engine._pulse_controller.bind_ddp(self.ddp)
|
||||
logger.debug("[rocketchat] V8.6: PulseController DDP gebunden (on_connected_cb)")
|
||||
except Exception as e:
|
||||
logger.debug("[rocketchat] V8.6: PulseController bind_ddp failed: %s", e)
|
||||
# P1b: DetectionTimer erst nach DDP-Connect starten
|
||||
try:
|
||||
self._presence_engine.start_detection()
|
||||
logger.debug("[rocketchat] P1b: DetectionTimer gestartet (on_connected_cb)")
|
||||
except Exception as e:
|
||||
logger.debug("[rocketchat] P1b: DetectionTimer start failed: %s", e)
|
||||
# V9: PresenceEngine braucht keine DDP-Bindung mehr (REST-only).
|
||||
|
||||
def _on_ddp_room_event(self, event: dict) -> None:
|
||||
"""A1b: Callback für DDP rooms-changed Events.
|
||||
@@ -1734,21 +1691,20 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self._rooms = self.rest.get_rooms()
|
||||
logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms))
|
||||
|
||||
# P1-2 O-2: Bind asyncio loop to DDPClient and PulseController
|
||||
# V9: Bind asyncio loop to PresenceEngine
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
self.ddp.bind_loop(loop)
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
|
||||
self._presence_engine._pulse_controller.bind_loop(loop)
|
||||
self._presence_engine.bind_loop(loop)
|
||||
logger.info(
|
||||
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: yes "
|
||||
"(loop=%s)",
|
||||
"[rocketchat] V9: PresenceEngine loop-bound: yes (loop=%s)",
|
||||
id(loop),
|
||||
)
|
||||
except RuntimeError:
|
||||
# No running event loop (e.g., in tests) — graceful degradation
|
||||
logger.info(
|
||||
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: no "
|
||||
"[rocketchat] V9: PresenceEngine loop-bound: no "
|
||||
"(no running event loop)"
|
||||
)
|
||||
|
||||
@@ -2020,20 +1976,20 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self.user = resolved.lower()
|
||||
logger.info("[rocketchat] Resolved self.user from login (reconnect): %s", self.user)
|
||||
|
||||
# P1-2 O-2: Re-bind asyncio loop to new DDPClient and PulseController
|
||||
# V9: Re-bind asyncio loop to PresenceEngine
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
self.ddp.bind_loop(loop)
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
|
||||
self._presence_engine._pulse_controller.bind_loop(loop)
|
||||
self._presence_engine.bind_loop(loop)
|
||||
logger.info(
|
||||
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: yes "
|
||||
"[rocketchat] V9: PresenceEngine loop-bound: yes "
|
||||
"(reconnect, loop=%s)",
|
||||
id(loop),
|
||||
)
|
||||
except RuntimeError:
|
||||
logger.info(
|
||||
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: no "
|
||||
"[rocketchat] V9: PresenceEngine loop-bound: no "
|
||||
"(reconnect, no running event loop)"
|
||||
)
|
||||
|
||||
@@ -2089,12 +2045,11 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
def _schedule_idle_timer(self) -> None:
|
||||
"""Schedule idle timer to mark bot as away when inactive.
|
||||
|
||||
V8.6: Deaktiviert wenn PresenceEngine aktiv ist (ROCKETCHAT_PRESENCE_ENABLED=true).
|
||||
Der alte _set_away-Timer kann eine DDP-Subscription-Endlosschleife auslösen
|
||||
(Rainer-Warnung). Die PresenceEngine übernimmt das Status-Management.
|
||||
V9: Deaktiviert wenn PresenceEngine aktiv ist.
|
||||
Die PresenceEngine übernimmt das Status-Management via Hooks.
|
||||
"""
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None and self._presence_engine.is_enabled():
|
||||
logger.debug("[rocketchat] V8.6: _schedule_idle_timer skipped — PresenceEngine active")
|
||||
logger.debug("[rocketchat] V9: _schedule_idle_timer skipped — PresenceEngine active")
|
||||
return
|
||||
if self._status_timer:
|
||||
self._status_timer.cancel()
|
||||
@@ -2234,17 +2189,12 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
virtual_chat_id = f"user:{username}"
|
||||
_set_room_context_origin(virtual_chat_id, room_id)
|
||||
|
||||
# ── V8.6 P1a: PresenceEngine — mark_busy_started (Honeymoon-Timer) ──
|
||||
# Graceful degradation: wenn _presence_engine nicht existiert
|
||||
# (z.B. in Tests die __new__ statt __init__ verwenden), skip.
|
||||
# ── V9: PresenceEngine — Hooks übernehmen das Status-Management ──
|
||||
# Kein mark_busy_started(), kein increment_background_tasks() mehr.
|
||||
# pre_gateway_dispatch/post_llm_call Hooks steuern die Schachuhr.
|
||||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||
if _has_presence:
|
||||
self._presence_engine.mark_busy_started(room_name=room_name)
|
||||
# B12: Background-Tasks zählen — Heartbeat-Message aktivieren
|
||||
self._presence_engine.increment_background_tasks()
|
||||
logger.info("[presence] mark_busy_started (room=%s)", room_name)
|
||||
# V8.9 P1: Reset dispatch flag — wird in _dispatch_agent auf True gesetzt
|
||||
self._agent_dispatched_this_turn = False
|
||||
logger.debug("[presence-v9] Dispatch beginnt — Hooks steuern Counter")
|
||||
|
||||
try:
|
||||
# ── R5: Inline-Command-Erkennung (VOR Onboarding + Hermes-Dispatch) ──
|
||||
@@ -2523,9 +2473,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# als thematische Frage klassifiziert und ins Catch-All kopiert.
|
||||
if room_id in self._pending_move_requests:
|
||||
move_req = self._pending_move_requests.pop(room_id)
|
||||
# ── V8.6: PresenceEngine — Move-Request beantwortet → clear ──
|
||||
if _has_presence:
|
||||
self._presence_engine.clear_move_request(room_id)
|
||||
# ── V9: PresenceEngine — Move-Request beantwortet ──
|
||||
# V9: Kein clear_move_request mehr (Hooks steuern Status).
|
||||
choice = text.strip()
|
||||
|
||||
# Neues Format: MOVE_REQ:<room_id>::<choice> (native Buttons)
|
||||
@@ -3274,11 +3223,9 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
'username': username,
|
||||
'message_id': msg_id,
|
||||
}
|
||||
# ── V8.6: PresenceEngine — Move-Request pending → away ──
|
||||
# ── V9: PresenceEngine — Move-Request pending ──
|
||||
# V9: Hooks steuern Status, kein manuelles update_presence mehr.
|
||||
target_name = getattr(decision, 'move_request_target_name', 'Zielraum')
|
||||
if _has_presence:
|
||||
self._presence_engine.set_move_request_pending(room_id, target_name)
|
||||
self._presence_engine.update_presence()
|
||||
# Lernsystem: Keywords für Feedback-Loop speichern
|
||||
if hasattr(decision, 'matched_keywords') and decision.matched_keywords:
|
||||
self.archivar._routed_messages[msg_id] = {
|
||||
@@ -3537,7 +3484,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# P0-3: Agent-Dispatch-Task speichern für Cancel bei ::onboarding abort.
|
||||
# handle_message() erzeugt intern asyncio.create_task (Drain-Task).
|
||||
# Ohne Referenz kann ::onboarding abort den laufenden Agent-Task nicht killen.
|
||||
# V8.9 P1: Flag setzen — der Agent wurde dispatched
|
||||
# V9: Agent wurde dispatched (für OutboundGate-Tracking)
|
||||
self._agent_dispatched_this_turn = True
|
||||
self._agent_dispatch_task = asyncio.create_task(
|
||||
ctx.run(self.handle_message, event)
|
||||
@@ -3579,24 +3526,13 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
except Exception as e2:
|
||||
logger.error("[rocketchat] COMMAND text fallback also failed: %s", e2)
|
||||
finally:
|
||||
# ── V8.9 P1: PresenceEngine — Busy-Done-Debounce statt sofortigem mark_busy_done ──
|
||||
# Der finally-Block von _process_incoming feuert, sobald handle_message()
|
||||
# zurückkehrt — aber handle_message() dispatched den Agent nur asynchron
|
||||
# und kehrt sofort zurück. Der Agent arbeitet dann noch 30-90s weiter.
|
||||
# Statt sofort mark_busy_done zu rufen, starten wir einen 10s-Debounce-Timer.
|
||||
# Jeder send()-Call resettet den Timer. Erst wenn 10s lang keine Nachricht
|
||||
# mehr gesendet wurde, ist der Agent wirklich fertig.
|
||||
# ── V9: PresenceEngine — Hooks steuern das Status-Management ──
|
||||
# Kein Busy-Done-Debounce mehr. post_llm_call Hook dekrementiert
|
||||
# den main_agent-Counter automatisch wenn der LLM-Call endet.
|
||||
if _has_presence:
|
||||
# _start_busy_done_debounce() ruft decrement_background_tasks +
|
||||
# mark_busy_done entweder sofort (kein Agent dispatched) oder
|
||||
# nach 10s Debounce (Agent wurde dispatched und ist jetzt still).
|
||||
asyncio.create_task(self._start_busy_done_debounce())
|
||||
logger.info("[presence] Busy-Done-Debounce gestartet (turn complete)")
|
||||
logger.debug("[presence-v9] Turn complete — Hooks steuern Counter")
|
||||
|
||||
# Phase 5: SubagentTracker — complete() NICHT im finally!
|
||||
# Der Background-Prozess läuft noch wenn der Turn endet.
|
||||
# Stale-Recovery im DetectionTimer räumt tote Einträge auf.
|
||||
# ── P5 V9.x: OutboundGate — release (symmetrisch zu mark_busy_done) ──
|
||||
# ── P5 V9.x: OutboundGate — release ──
|
||||
# W2: release in try/except BaseException im finally-Block.
|
||||
try:
|
||||
_gate_room_id = f"user:{username}"
|
||||
@@ -3898,13 +3834,13 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"""::hilfe — Zeigt die Hilfeseite mit allen Befehlen."""
|
||||
from archivar.inline_commands import build_help_text
|
||||
|
||||
# P1-4: PresenceEngine-Werte lesen (mit _has_presence-Guard)
|
||||
# V9: PresenceEngine-Werte lesen (mit _has_presence-Guard)
|
||||
presence_enabled = None
|
||||
current_status = "online"
|
||||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||
if _has_presence:
|
||||
presence_enabled = self._presence_engine.is_enabled()
|
||||
current_status = getattr(self._presence_engine, '_last_sent_status', 'online') or 'online'
|
||||
current_status = self._presence_engine.get_status()
|
||||
|
||||
return build_help_text(
|
||||
self._inline_commands,
|
||||
@@ -3930,15 +3866,13 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
butler_mode = getattr(room_map, 'butler_mode', 'unknown')
|
||||
onboarding_active = self.archivar._stats.get("onboarding_active", False)
|
||||
|
||||
# P1-4: PresenceEngine-Werte lesen (mit _has_presence-Guard)
|
||||
# V9: PresenceEngine-Werte lesen (mit _has_presence-Guard)
|
||||
presence_enabled = None
|
||||
current_status = "online"
|
||||
pulse_active = False
|
||||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||
if _has_presence:
|
||||
presence_enabled = self._presence_engine.is_enabled()
|
||||
current_status = getattr(self._presence_engine, '_last_sent_status', 'online') or 'online'
|
||||
pulse_active = self._presence_engine._pulse_controller.is_running()
|
||||
current_status = self._presence_engine.get_status()
|
||||
|
||||
return build_status_text(
|
||||
room_count=room_count,
|
||||
@@ -3948,7 +3882,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
room_map_summary=self._room_map_summary,
|
||||
presence_enabled=presence_enabled,
|
||||
current_status=current_status,
|
||||
pulse_active=pulse_active,
|
||||
pulse_active=False, # V9: Kein PulseController mehr
|
||||
)
|
||||
|
||||
async def _cmd_reset(self, room_id: str, args: str) -> str:
|
||||
@@ -4308,46 +4242,33 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
if subcmd in ("on", "an", "ein", "enable", "start"):
|
||||
self._presence_engine.enable()
|
||||
# P0-3: ::setstatus on → PulseController aktivieren
|
||||
if hasattr(self._presence_engine, '_pulse_controller'):
|
||||
self._presence_engine._pulse_controller.bind_rest(self.rest)
|
||||
if self.ddp:
|
||||
self._presence_engine._pulse_controller.bind_ddp(self.ddp)
|
||||
# B1: PulseController sofort starten — kein Warten auf DetectionTimer (10s)
|
||||
try:
|
||||
self._presence_engine._pulse_controller.start()
|
||||
except Exception as e:
|
||||
logger.warning("[rocketchat] ::setstatus on: PulseController.start() failed: %s", e)
|
||||
logger.info("[rocketchat] V8.6: ::setstatus on — PresenceEngine aktiviert")
|
||||
return "🟢 **Aktivitäts-Indikator: AN**\n\nDer Bot zeigt jetzt seinen Status automatisch an (online/busy/away)."
|
||||
# V9: Kein PulseController mehr — enable() reicht
|
||||
logger.info("[rocketchat] V9: ::setstatus on — PresenceEngine aktiviert")
|
||||
return "🟢 **Aktivitäts-Indikator: AN**\n\nDer Bot zeigt jetzt seinen Status automatisch an (online/busy)."
|
||||
|
||||
elif subcmd in ("off", "aus", "disable", "stop"):
|
||||
self._presence_engine.disable()
|
||||
# P0-3: ::setstatus off → PulseController stoppen
|
||||
if hasattr(self._presence_engine, '_pulse_controller'):
|
||||
self._presence_engine._pulse_controller.stop()
|
||||
logger.info("[rocketchat] V8.6: ::setstatus off — PresenceEngine deaktiviert")
|
||||
# V9: Kein PulseController mehr — disable() reicht
|
||||
logger.info("[rocketchat] V9: ::setstatus off — PresenceEngine deaktiviert")
|
||||
return "🔴 **Aktivitäts-Indikator: AUS**\n\nDer Bot-Status bleibt auf 'online'. Keine automatischen Status-Wechsel."
|
||||
|
||||
else:
|
||||
# status
|
||||
enabled = self._presence_engine.is_enabled()
|
||||
active = self._presence_engine._active_tasks
|
||||
bg = self._presence_engine._background_tasks
|
||||
onboarding = self._presence_engine._onboarding_active
|
||||
error = self._presence_engine._error_state
|
||||
counters = self._presence_engine.get_counters()
|
||||
telemetry = self._presence_engine.get_telemetry()
|
||||
|
||||
lines = [
|
||||
"📊 **Aktivitäts-Indikator Status**",
|
||||
"",
|
||||
f"Status: {'🟢 Aktiviert' if enabled else '🔴 Deaktiviert'}",
|
||||
f"Aktive Tasks: {active}",
|
||||
f"Background Tasks: {bg}",
|
||||
f"Counter: {counters}",
|
||||
f"State: {self._presence_engine.get_status()}",
|
||||
f"REST-Calls: {telemetry['rest_calls']} "
|
||||
f"(Erfolg: {telemetry['rest_success']}, "
|
||||
f"429: {telemetry['rest_429']}, "
|
||||
f"Fehler: {telemetry['rest_errors']})",
|
||||
]
|
||||
if onboarding:
|
||||
lines.append("Onboarding: 🔄 Läuft")
|
||||
if error:
|
||||
lines.append(f"Fehler: ⚠️ {error}")
|
||||
if not enabled:
|
||||
lines.append("", "💡 `::setstatus on` zum Aktivieren")
|
||||
|
||||
@@ -4673,74 +4594,9 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"""
|
||||
return MessageType.COMMAND if is_button_response else MessageType.TEXT
|
||||
|
||||
# ── V8.9 P1: Busy-Done-Debounce ─────────────────────────────────────
|
||||
|
||||
async def _start_busy_done_debounce(self) -> None:
|
||||
"""Start a 10s debounce timer that calls mark_busy_done when it fires.
|
||||
|
||||
Called from _process_incoming's finally block. If the agent was
|
||||
dispatched this turn, we start a debounce instead of calling
|
||||
mark_busy_done immediately. Every send() call resets the timer.
|
||||
When the timer fires (10s of silence), the agent is truly done.
|
||||
"""
|
||||
async with self._busy_done_debounce_lock:
|
||||
# Cancel any existing debounce
|
||||
if self._busy_done_debounce_task is not None:
|
||||
self._busy_done_debounce_task.cancel()
|
||||
self._busy_done_debounce_task = None
|
||||
|
||||
if not self._agent_dispatched_this_turn:
|
||||
# No agent was dispatched — mark done immediately
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
|
||||
self._presence_engine.decrement_background_tasks()
|
||||
self._presence_engine.mark_busy_done()
|
||||
self._presence_engine.set_current_room("")
|
||||
logger.info("[presence] mark_busy_done (no agent dispatched)")
|
||||
return
|
||||
|
||||
# Agent was dispatched — start debounce
|
||||
self._busy_done_debounce_task = asyncio.create_task(
|
||||
self._busy_done_debounce_timer()
|
||||
)
|
||||
logger.debug("[presence] Busy-Done-Debounce gestartet (10s)")
|
||||
|
||||
async def _busy_done_debounce_timer(self) -> None:
|
||||
"""Wait 10s, then call mark_busy_done if not reset."""
|
||||
try:
|
||||
await asyncio.sleep(10.0)
|
||||
async with self._busy_done_debounce_lock:
|
||||
if self._busy_done_debounce_task is not None:
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
|
||||
self._presence_engine.decrement_background_tasks()
|
||||
self._presence_engine.mark_busy_done()
|
||||
self._presence_engine.set_current_room("")
|
||||
logger.info("[presence] mark_busy_done (debounce fired — agent silent 10s)")
|
||||
self._busy_done_debounce_task = None
|
||||
except asyncio.CancelledError:
|
||||
logger.debug("[presence] Busy-Done-Debounce gecancelled (send() reset)")
|
||||
raise
|
||||
|
||||
async def _reset_busy_done_debounce(self) -> None:
|
||||
"""Reset the debounce timer — called from send() when agent sends a message.
|
||||
|
||||
If no debounce is running, this is a no-op (agent wasn't dispatched
|
||||
this turn, or mark_busy_done already fired).
|
||||
"""
|
||||
async with self._busy_done_debounce_lock:
|
||||
if self._busy_done_debounce_task is not None:
|
||||
self._busy_done_debounce_task.cancel()
|
||||
self._busy_done_debounce_task = asyncio.create_task(
|
||||
self._busy_done_debounce_timer()
|
||||
)
|
||||
logger.debug("[presence] Busy-Done-Debounce reset (agent sent message)")
|
||||
|
||||
async def _cancel_busy_done_debounce(self) -> None:
|
||||
"""Cancel the debounce timer — called from disconnect()."""
|
||||
async with self._busy_done_debounce_lock:
|
||||
if self._busy_done_debounce_task is not None:
|
||||
self._busy_done_debounce_task.cancel()
|
||||
self._busy_done_debounce_task = None
|
||||
logger.debug("[presence] Busy-Done-Debounce gecancelled (disconnect)")
|
||||
# ── V9: Busy-Done-Debounce ENTFERNT ─────────────────────────────────
|
||||
# V9: Hooks (post_llm_call) steuern den main_agent-Counter automatisch.
|
||||
# Kein manuelles mark_busy_done(), kein Debounce-Timer mehr.
|
||||
|
||||
async def _dispatch_agent(
|
||||
self,
|
||||
@@ -4831,8 +4687,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
_target[:8] if _target else "",
|
||||
)
|
||||
# P0-3: Agent-Dispatch-Task speichern für Cancel bei ::onboarding abort.
|
||||
# V8.9 P1: Flag setzen — der Agent wurde dispatched, Busy-Done-Debounce
|
||||
# wird im finally-Block von _process_incoming gestartet.
|
||||
# V9: Agent wurde dispatched (für OutboundGate-Tracking)
|
||||
self._agent_dispatched_this_turn = True
|
||||
self._agent_dispatch_task = asyncio.create_task(
|
||||
ctx.run(self.handle_message, event)
|
||||
@@ -5161,11 +5016,9 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||||
if _MULTIROOM() and self.archivar is not None:
|
||||
self.archivar._stats["onboarding_active"] = True
|
||||
# ── V8.6: PresenceEngine — Onboarding start → away ──
|
||||
# ── V9: PresenceEngine — Onboarding start ──
|
||||
# V9: Hooks steuern Status, kein manuelles set_onboarding_active mehr.
|
||||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||
if _has_presence:
|
||||
self._presence_engine.set_onboarding_active(True)
|
||||
self._presence_engine.update_presence()
|
||||
|
||||
# Bug 3 fix: Robuster Zugriff auf _build_custom_buttons
|
||||
_build = self._get_build_custom_buttons()
|
||||
@@ -5780,7 +5633,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||
if _has_presence:
|
||||
presence_enabled = self._presence_engine.is_enabled()
|
||||
current_status = getattr(self._presence_engine, '_last_sent_status', 'online') or 'online'
|
||||
current_status = self._presence_engine.get_status()
|
||||
help_text = build_help_text(self._inline_commands, room_map_summary=self._room_map_summary,
|
||||
presence_enabled=presence_enabled, current_status=current_status)
|
||||
await self._post_message_with_retry(operator_room_id, help_text)
|
||||
@@ -6484,11 +6337,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self.archivar._stats["onboarding_active"] = False
|
||||
self.archivar._state.clear_onboarding_state()
|
||||
self._onboarding_state = {}
|
||||
# ── V8.6: PresenceEngine — Onboarding end → online ──
|
||||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||
if _has_presence:
|
||||
self._presence_engine.set_onboarding_active(False)
|
||||
self._presence_engine.update_presence()
|
||||
# ── V9: PresenceEngine — Onboarding end ──
|
||||
# V9: Hooks steuern Status, kein manuelles update_presence mehr.
|
||||
# F8: State Machine — AWAITING_TEST → ACTIVE
|
||||
if hasattr(self, '_onboarding_sm'):
|
||||
self._onboarding_sm.advance_test()
|
||||
@@ -6634,8 +6484,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
return text
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
# ── V8.9 P1: Busy-Done-Debounce canceln ──
|
||||
await self._cancel_busy_done_debounce()
|
||||
# ── V9: Kein Busy-Done-Debounce mehr ──
|
||||
# ── P1b: Gate-Sweep-Task sauber beenden ──
|
||||
if hasattr(self, '_gate_sweep_task') and self._gate_sweep_task is not None:
|
||||
self._gate_sweep_task.cancel()
|
||||
@@ -7052,10 +6901,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# dekrementiert (line 2794). send() kann mehrfach pro Turn
|
||||
# aufgerufen werden (Multi-Message, Split) — ein decrement hier
|
||||
# würde den Agenten vorzeitig auf "online" setzen.
|
||||
# ── V8.9 P1: Busy-Done-Debounce reset — Agent sendet noch ──
|
||||
# Jeder erfolgreiche send()-Call resettet den 10s-Debounce-Timer.
|
||||
# Solange der Agent Nachrichten sendet, bleibt der Status busy.
|
||||
asyncio.create_task(self._reset_busy_done_debounce())
|
||||
# V9: Kein Busy-Done-Debounce mehr — Hooks steuern Status
|
||||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||||
|
||||
finally:
|
||||
@@ -7128,8 +6974,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
success = await self._post_message_with_retry(room_id, chunk_text)
|
||||
if success:
|
||||
last_msg_id = str(int(time.time() * 1000))
|
||||
# V8.9 P1: Busy-Done-Debounce reset pro Chunk
|
||||
asyncio.create_task(self._reset_busy_done_debounce())
|
||||
# V9: Kein Busy-Done-Debounce mehr — Hooks steuern Status
|
||||
# Small delay between chunks to preserve order
|
||||
if i < total:
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
Reference in New Issue
Block a user