P5 V9.x: P1a/P1b/P1c — Gate-Release-Symmetrie, Sweep-Cancel, Re-create-Guard
P1a: try/finally in send() und send_clarify() für symmetrisches Gate-Release - _gate_acquired Flag trackt ob try_acquire den Eintrag erstellt hat - finally-Block released nur wenn _gate_acquired=True und task_token gesetzt - Verhindert hängende Gate-Einträge bei Exceptions in send()/send_clarify() P1b: _gate_sweep_task.cancel() in disconnect() - Sweep-Loop wird vor _mark_disconnected() gecancelled - self._running = False gesetzt (Sweep-Loop prüft _running Flag) - Verhindert dass Sweep-Task nach disconnect() weiterläuft P1c: Sweep-Task-Check vor Re-create in connect() - Prüft ob _gate_sweep_task existiert und nicht done() ist - Cancelled alten Task vor create_task() des neuen - Verhindert doppelte Sweep-Tasks bei Reconnect
This commit is contained in:
+365
-325
@@ -1932,6 +1932,9 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self._running = True
|
||||
self._listen_task = asyncio.create_task(self._listen_loop())
|
||||
# P5 V9.x W2: OutboundGate Sweep-Loop (asyncio.create_task, nicht threading.Timer)
|
||||
# ── P1c: Sweep-Task-Check vor Re-create ──
|
||||
if self._gate_sweep_task is not None and not self._gate_sweep_task.done():
|
||||
self._gate_sweep_task.cancel()
|
||||
self._gate_sweep_task = asyncio.create_task(self._gate_sweep_loop())
|
||||
self._last_activity = time.time()
|
||||
logger.info("[rocketchat] Listen loop started, _running=%s", self._running)
|
||||
@@ -6512,6 +6515,12 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
return text
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
# ── 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()
|
||||
self._gate_sweep_task = None
|
||||
self._running = False # P1b: Sweep-Loop nutzt _running Flag
|
||||
|
||||
self._mark_disconnected()
|
||||
self._shutdown_event.set()
|
||||
if self._status_timer:
|
||||
@@ -6599,6 +6608,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if origin:
|
||||
_gate_room_id = origin
|
||||
task_token = _CURRENT_TASK_TOKEN.get()
|
||||
_gate_acquired = False # P1a: track whether WE created the gate entry
|
||||
if task_token and hasattr(self, '_outbound_gate') and self._outbound_gate is not None:
|
||||
from archivar.outbound_gate import GateDecision
|
||||
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
|
||||
@@ -6635,225 +6645,239 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
_gate_room_id[:8], active_name,
|
||||
)
|
||||
return SendResult(success=True, message_id="quick_reply")
|
||||
# Fell through: decision.allow is True — track if WE created the entry
|
||||
# (gate_clear = we own it; same_room_same_token = someone else owns it)
|
||||
_gate_acquired = (decision.reason == "gate_clear")
|
||||
|
||||
# ── P1-6: ::-Prefix für Dangerous-Command-Meldungen ──────────
|
||||
# Hermes Core sendet Meldungen mit /approve, /deny etc.
|
||||
# Rocket.Chat unterstützt keine /-Befehle → :: Varianten einsetzen.
|
||||
content = self._replace_slash_with_double_colon(content)
|
||||
# ── P1a: try/finally für symmetrisches Gate-Release ─────────
|
||||
# Bei Exception in send() hängt sonst der Gate-Eintrag.
|
||||
try:
|
||||
# ── P1-6: ::-Prefix für Dangerous-Command-Meldungen ──────────
|
||||
# Hermes Core sendet Meldungen mit /approve, /deny etc.
|
||||
# Rocket.Chat unterstützt keine /-Befehle → :: Varianten einsetzen.
|
||||
content = self._replace_slash_with_double_colon(content)
|
||||
|
||||
# ── Virtual → Real Room Translation ─────────────────────────
|
||||
# chat_id from Hermes session is virtual (e.g. "user:alice").
|
||||
# We must resolve it to a real Rocket.Chat room_id for REST API.
|
||||
real_room_id = chat_id
|
||||
if chat_id.startswith("user:"):
|
||||
# Priority 0: _CURRENT_ORIGIN_ROOM — Antwort geht IMMER dorthin,
|
||||
# wo die Frage gestellt wurde.
|
||||
# P1 Cross-Contamination-Fix: Task-Token-Validierung VOR Verwendung.
|
||||
# _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen stale Wert
|
||||
# vom Parent-Task erben. Wir validieren gegen _room_context task_token,
|
||||
# um Cross-Contamination (Auto-Route → Widerspruch → falscher Raum) zu
|
||||
# verhindern.
|
||||
origin = _CURRENT_ORIGIN_ROOM.get()
|
||||
if origin:
|
||||
# Pre-Read-Validierung: Task-Token-Match prüfen
|
||||
current_token = _CURRENT_TASK_TOKEN.get()
|
||||
ctx_entry = _room_context.get(chat_id, {})
|
||||
stored_token = ctx_entry.get("task_token", "")
|
||||
# Token-Mismatch: _CURRENT_ORIGIN_ROOM ist stale → skippen,
|
||||
# normale ContextVar-Logik weiterlaufen lassen
|
||||
if current_token and stored_token and current_token != stored_token:
|
||||
routing_counter.increment('priority0_token_mismatch_skip')
|
||||
logger.info(
|
||||
"[rocketchat] send Priority 0 token mismatch for %s — "
|
||||
"skipping stale ContextVar, falling through to _room_context",
|
||||
chat_id,
|
||||
)
|
||||
origin = "" # Force fallthrough
|
||||
if origin:
|
||||
real_room_id = origin
|
||||
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||
# ContextVars sind asyncio-task-lokal — bei Stream-Retries in neuem Task
|
||||
# ist _CURRENT_ORIGIN_ROOM leer. _room_context (global dict) überlebt.
|
||||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||||
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
||||
fallback_origin = _get_room_context_origin(chat_id)
|
||||
if fallback_origin:
|
||||
real_room_id = fallback_origin
|
||||
routing_counter.increment('contextvar_reset_fallback')
|
||||
logger.info("[rocketchat] send via _room_context fallback: %s → %s", chat_id, real_room_id)
|
||||
# ── Virtual → Real Room Translation ─────────────────────────
|
||||
# chat_id from Hermes session is virtual (e.g. "user:alice").
|
||||
# We must resolve it to a real Rocket.Chat room_id for REST API.
|
||||
real_room_id = chat_id
|
||||
if chat_id.startswith("user:"):
|
||||
# Priority 0: _CURRENT_ORIGIN_ROOM — Antwort geht IMMER dorthin,
|
||||
# wo die Frage gestellt wurde.
|
||||
# P1 Cross-Contamination-Fix: Task-Token-Validierung VOR Verwendung.
|
||||
# _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen stale Wert
|
||||
# vom Parent-Task erben. Wir validieren gegen _room_context task_token,
|
||||
# um Cross-Contamination (Auto-Route → Widerspruch → falscher Raum) zu
|
||||
# verhindern.
|
||||
origin = _CURRENT_ORIGIN_ROOM.get()
|
||||
if origin:
|
||||
# Pre-Read-Validierung: Task-Token-Match prüfen
|
||||
current_token = _CURRENT_TASK_TOKEN.get()
|
||||
ctx_entry = _room_context.get(chat_id, {})
|
||||
stored_token = ctx_entry.get("task_token", "")
|
||||
# Token-Mismatch: _CURRENT_ORIGIN_ROOM ist stale → skippen,
|
||||
# normale ContextVar-Logik weiterlaufen lassen
|
||||
if current_token and stored_token and current_token != stored_token:
|
||||
routing_counter.increment('priority0_token_mismatch_skip')
|
||||
logger.info(
|
||||
"[rocketchat] send Priority 0 token mismatch for %s — "
|
||||
"skipping stale ContextVar, falling through to _room_context",
|
||||
chat_id,
|
||||
)
|
||||
origin = "" # Force fallthrough
|
||||
if origin:
|
||||
real_room_id = origin
|
||||
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
||||
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||
if thematic_target:
|
||||
real_room_id = thematic_target
|
||||
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||
# ContextVars sind asyncio-task-lokal — bei Stream-Retries in neuem Task
|
||||
# ist _CURRENT_ORIGIN_ROOM leer. _room_context (global dict) überlebt.
|
||||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||||
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
||||
fallback_origin = _get_room_context_origin(chat_id)
|
||||
if fallback_origin:
|
||||
real_room_id = fallback_origin
|
||||
routing_counter.increment('contextvar_reset_fallback')
|
||||
logger.info("[rocketchat] send via _room_context fallback: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# Priority 2: proaktive Nachricht — use most recent room for this user
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
real_room_id = rooms[-1] # last room user was active in
|
||||
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||||
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
||||
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||
if thematic_target:
|
||||
real_room_id = thematic_target
|
||||
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# Fallback: try to find any room with recent activity involving this user
|
||||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
||||
fallback_room = self._find_fallback_room_for_user(chat_id)
|
||||
if fallback_room:
|
||||
real_room_id = fallback_room
|
||||
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
||||
# Priority 2: proaktive Nachricht — use most recent room for this user
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
real_room_id = rooms[-1] # last room user was active in
|
||||
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
||||
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
||||
# Fallback: try to find any room with recent activity involving this user
|
||||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
||||
fallback_room = self._find_fallback_room_for_user(chat_id)
|
||||
if fallback_room:
|
||||
real_room_id = fallback_room
|
||||
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
||||
else:
|
||||
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
||||
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
||||
|
||||
# ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ──
|
||||
# This allows the agent to request buttons by embedding markup in its
|
||||
# response text, without requiring the gateway to pass metadata.
|
||||
# Syntax: [[BUTTONS:yes_no]]Your question here[[/BUTTONS]]
|
||||
# [[BUTTONS:custom]]Option A|Option B|Option C[[/BUTTONS]]
|
||||
_btn_re = re.compile(
|
||||
r'\[\[BUTTONS:(?P<template>[a-zA-Z0-9_]+)\]\]'
|
||||
r'(?P<text>.*?)'
|
||||
r'\[\[/BUTTONS\]\]',
|
||||
re.DOTALL | re.IGNORECASE,
|
||||
)
|
||||
_match = _btn_re.search(content or "")
|
||||
if _match:
|
||||
_template_name = _match.group("template").lower()
|
||||
_inner_text = _match.group("text").strip()
|
||||
# Strip the markup from content, keep the inner text
|
||||
content = _btn_re.sub(_inner_text, content).strip()
|
||||
# Build synthetic metadata so the existing template path below handles it
|
||||
_valid_templates = {"yes_no", "confirm_cancel", "ok", "multi_choice_3"}
|
||||
if _template_name == "custom" or "|" in _inner_text:
|
||||
# Custom buttons: labels separated by pipe
|
||||
_labels = [l.strip() for l in _inner_text.split("|") if l.strip()]
|
||||
metadata = dict(metadata or {})
|
||||
metadata["template"] = "custom"
|
||||
metadata["custom_buttons"] = _labels
|
||||
metadata["question_id"] = metadata.get("question_id", "custom_btn")
|
||||
metadata.setdefault("button_title", "Wähle eine Option:")
|
||||
elif _template_name in _valid_templates:
|
||||
metadata = dict(metadata or {})
|
||||
metadata["template"] = _template_name
|
||||
metadata["question_id"] = metadata.get("question_id", f"btn_{_template_name}")
|
||||
|
||||
# Handle interaction templates via metadata
|
||||
attachments = None
|
||||
if metadata and metadata.get("template"):
|
||||
# Use sys.modules to access __init__ symbols (plugin loaded as flat module)
|
||||
import sys as _sys
|
||||
_init = _sys.modules.get(__name__.rsplit('.', 1)[0] if '.' in __name__ else __name__)
|
||||
if _init is None:
|
||||
_init = _sys.modules.get('rocketchat')
|
||||
_TEMPLATE_MAP = getattr(_init, '_TEMPLATE_MAP', {})
|
||||
_build_custom_buttons = getattr(_init, '_build_custom_buttons', lambda labels, prefix='', style='default': [])
|
||||
template_name = metadata.get("template")
|
||||
question_id = metadata.get("question_id", "")
|
||||
if template_name == "custom" and metadata.get("custom_buttons"):
|
||||
buttons = _build_custom_buttons(metadata["custom_buttons"], prefix=question_id)
|
||||
if buttons:
|
||||
attachments = [{
|
||||
"color": "#1d74f5",
|
||||
"title": metadata.get("button_title", "Wähle eine Option:"),
|
||||
"actions": buttons,
|
||||
}]
|
||||
elif template_name in _TEMPLATE_MAP:
|
||||
tmpl = _TEMPLATE_MAP[template_name]
|
||||
attachment = dict(tmpl.get("attachment", {}))
|
||||
raw_buttons = tmpl.get("buttons", [])
|
||||
buttons = []
|
||||
for btn in raw_buttons:
|
||||
msg_payload = btn.get("msg", "")
|
||||
if question_id:
|
||||
msg_payload = f"{question_id}::{msg_payload}"
|
||||
buttons.append({
|
||||
"type": "button",
|
||||
"text": btn.get("text", "?"),
|
||||
"msg": msg_payload,
|
||||
"msg_in_chat_window": True,
|
||||
"style": btn.get("style", "default"),
|
||||
})
|
||||
attachment["actions"] = buttons
|
||||
attachments = [attachment]
|
||||
|
||||
# Bug 3 fix: Fallback wenn button_template nicht gerendert werden kann.
|
||||
# Falls metadata ein Template anfordert, aber attachments None bleibt
|
||||
# (z.B. _TEMPLATE_MAP leer, _build_custom_buttons nicht verfügbar),
|
||||
# hänge Text-Fallback an, damit der User weiß, wie er antworten soll.
|
||||
if attachments is None:
|
||||
fallback_lines = []
|
||||
if template_name == "custom" and metadata.get("custom_buttons"):
|
||||
opts = metadata["custom_buttons"]
|
||||
fallback_lines.append("Bitte antworte mit einer der folgenden Optionen:")
|
||||
for i, opt in enumerate(opts, 1):
|
||||
fallback_lines.append(f" {i}. {opt}")
|
||||
elif template_name == "yes_no":
|
||||
fallback_lines.append("Antworte mit 1 (Ja) oder 2 (Nein)")
|
||||
elif template_name == "confirm_cancel":
|
||||
fallback_lines.append("Antworte mit 1 (Bestätigen) oder 2 (Abbrechen)")
|
||||
elif template_name == "ok":
|
||||
fallback_lines.append("Antworte mit 1 (OK)")
|
||||
elif template_name == "multi_choice_3":
|
||||
fallback_lines.append("Antworte mit 1, 2 oder 3")
|
||||
if fallback_lines:
|
||||
content = content + "\n\n" + "\n".join(fallback_lines)
|
||||
logger.debug("[rocketchat] Button template '%s' could not be rendered — using text fallback", template_name)
|
||||
|
||||
# ── Clarify-Queue: remember pending button question ──
|
||||
if metadata and metadata.get("template") and attachments:
|
||||
_tmpl = metadata.get("template")
|
||||
_qid = metadata.get("question_id", "")
|
||||
_expected = []
|
||||
if _tmpl == "yes_no":
|
||||
_expected = ["ja", "nein", "yes", "no"]
|
||||
elif _tmpl == "confirm_cancel":
|
||||
_expected = ["bestätigen", "confirm", "abbrechen", "cancel"]
|
||||
elif _tmpl == "ok":
|
||||
_expected = ["ok", "okay", "verstanden", "alles klar"]
|
||||
elif _tmpl == "custom" and metadata.get("custom_buttons"):
|
||||
_expected = [b.lower() for b in metadata["custom_buttons"]]
|
||||
self._pending_clarifies[real_room_id] = {
|
||||
"question_id": _qid,
|
||||
"template": _tmpl,
|
||||
"expected": _expected,
|
||||
"timestamp": time.time(),
|
||||
"original_text": content,
|
||||
}
|
||||
|
||||
# ── P1-7: Proactive message splitting ────────────────────────
|
||||
# Rocket.Chat REST-API hat ein Message-Limit (~4000 Zeichen).
|
||||
# Lange Antworten (Tabellen, Listen) werden abgeschnitten mit
|
||||
# "(Response formatting failed, plain text:)" — aber die API
|
||||
# meldet trotzdem success. Daher MÜSSEN wir VOR dem Senden
|
||||
# splitten, nicht erst nach einem Fehlschlag.
|
||||
if len(content) > 3000 and attachments is None:
|
||||
logger.info(
|
||||
"[rocketchat] P1-7: Message too long (%d chars) — proactive split",
|
||||
len(content),
|
||||
# ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ──
|
||||
# This allows the agent to request buttons by embedding markup in its
|
||||
# response text, without requiring the gateway to pass metadata.
|
||||
# Syntax: [[BUTTONS:yes_no]]Your question here[[/BUTTONS]]
|
||||
# [[BUTTONS:custom]]Option A|Option B|Option C[[/BUTTONS]]
|
||||
_btn_re = re.compile(
|
||||
r'\[\[BUTTONS:(?P<template>[a-zA-Z0-9_]+)\]\]'
|
||||
r'(?P<text>.*?)'
|
||||
r'\[\[/BUTTONS\]\]',
|
||||
re.DOTALL | re.IGNORECASE,
|
||||
)
|
||||
return await self._send_split(real_room_id, content)
|
||||
_match = _btn_re.search(content or "")
|
||||
if _match:
|
||||
_template_name = _match.group("template").lower()
|
||||
_inner_text = _match.group("text").strip()
|
||||
# Strip the markup from content, keep the inner text
|
||||
content = _btn_re.sub(_inner_text, content).strip()
|
||||
# Build synthetic metadata so the existing template path below handles it
|
||||
_valid_templates = {"yes_no", "confirm_cancel", "ok", "multi_choice_3"}
|
||||
if _template_name == "custom" or "|" in _inner_text:
|
||||
# Custom buttons: labels separated by pipe
|
||||
_labels = [l.strip() for l in _inner_text.split("|") if l.strip()]
|
||||
metadata = dict(metadata or {})
|
||||
metadata["template"] = "custom"
|
||||
metadata["custom_buttons"] = _labels
|
||||
metadata["question_id"] = metadata.get("question_id", "custom_btn")
|
||||
metadata.setdefault("button_title", "Wähle eine Option:")
|
||||
elif _template_name in _valid_templates:
|
||||
metadata = dict(metadata or {})
|
||||
metadata["template"] = _template_name
|
||||
metadata["question_id"] = metadata.get("question_id", f"btn_{_template_name}")
|
||||
|
||||
success = await self._post_message_with_retry(real_room_id, content, attachments=attachments)
|
||||
if success:
|
||||
# If this message has buttons, mark the room so the next user
|
||||
# message from here stays put (no Archivar routing). Button
|
||||
# responses must be answered in the same room the question was
|
||||
# asked, otherwise the user sees "Ich antworte im Zielraum"
|
||||
# and the agent loses context.
|
||||
if attachments:
|
||||
self._rooms_with_pending_questions.add(real_room_id)
|
||||
logger.debug("[rocketchat] Room %s marked for button response", real_room_id)
|
||||
# ── B5v6.5: Conversation History — Agent-Antwort aufzeichnen ──
|
||||
if _MULTIROOM() and self._conversation_history is not None:
|
||||
await self._conversation_history.add(real_room_id, "agent", content)
|
||||
# ── V8.6 P1-3: PresenceEngine — KEIN decrement in send()! ──
|
||||
# Der Counter wird NUR im finally-Block von _process_incoming
|
||||
# dekrementiert (line 2794). send() kann mehrfach pro Turn
|
||||
# aufgerufen werden (Multi-Message, Split) — ein decrement hier
|
||||
# würde den Agenten vorzeitig auf "online" setzen.
|
||||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||||
# Handle interaction templates via metadata
|
||||
attachments = None
|
||||
if metadata and metadata.get("template"):
|
||||
# Use sys.modules to access __init__ symbols (plugin loaded as flat module)
|
||||
import sys as _sys
|
||||
_init = _sys.modules.get(__name__.rsplit('.', 1)[0] if '.' in __name__ else __name__)
|
||||
if _init is None:
|
||||
_init = _sys.modules.get('rocketchat')
|
||||
_TEMPLATE_MAP = getattr(_init, '_TEMPLATE_MAP', {})
|
||||
_build_custom_buttons = getattr(_init, '_build_custom_buttons', lambda labels, prefix='', style='default': [])
|
||||
template_name = metadata.get("template")
|
||||
question_id = metadata.get("question_id", "")
|
||||
if template_name == "custom" and metadata.get("custom_buttons"):
|
||||
buttons = _build_custom_buttons(metadata["custom_buttons"], prefix=question_id)
|
||||
if buttons:
|
||||
attachments = [{
|
||||
"color": "#1d74f5",
|
||||
"title": metadata.get("button_title", "Wähle eine Option:"),
|
||||
"actions": buttons,
|
||||
}]
|
||||
elif template_name in _TEMPLATE_MAP:
|
||||
tmpl = _TEMPLATE_MAP[template_name]
|
||||
attachment = dict(tmpl.get("attachment", {}))
|
||||
raw_buttons = tmpl.get("buttons", [])
|
||||
buttons = []
|
||||
for btn in raw_buttons:
|
||||
msg_payload = btn.get("msg", "")
|
||||
if question_id:
|
||||
msg_payload = f"{question_id}::{msg_payload}"
|
||||
buttons.append({
|
||||
"type": "button",
|
||||
"text": btn.get("text", "?"),
|
||||
"msg": msg_payload,
|
||||
"msg_in_chat_window": True,
|
||||
"style": btn.get("style", "default"),
|
||||
})
|
||||
attachment["actions"] = buttons
|
||||
attachments = [attachment]
|
||||
|
||||
# Bug 3 fix: Fallback wenn button_template nicht gerendert werden kann.
|
||||
# Falls metadata ein Template anfordert, aber attachments None bleibt
|
||||
# (z.B. _TEMPLATE_MAP leer, _build_custom_buttons nicht verfügbar),
|
||||
# hänge Text-Fallback an, damit der User weiß, wie er antworten soll.
|
||||
if attachments is None:
|
||||
fallback_lines = []
|
||||
if template_name == "custom" and metadata.get("custom_buttons"):
|
||||
opts = metadata["custom_buttons"]
|
||||
fallback_lines.append("Bitte antworte mit einer der folgenden Optionen:")
|
||||
for i, opt in enumerate(opts, 1):
|
||||
fallback_lines.append(f" {i}. {opt}")
|
||||
elif template_name == "yes_no":
|
||||
fallback_lines.append("Antworte mit 1 (Ja) oder 2 (Nein)")
|
||||
elif template_name == "confirm_cancel":
|
||||
fallback_lines.append("Antworte mit 1 (Bestätigen) oder 2 (Abbrechen)")
|
||||
elif template_name == "ok":
|
||||
fallback_lines.append("Antworte mit 1 (OK)")
|
||||
elif template_name == "multi_choice_3":
|
||||
fallback_lines.append("Antworte mit 1, 2 oder 3")
|
||||
if fallback_lines:
|
||||
content = content + "\n\n" + "\n".join(fallback_lines)
|
||||
logger.debug("[rocketchat] Button template '%s' could not be rendered — using text fallback", template_name)
|
||||
|
||||
# ── Clarify-Queue: remember pending button question ──
|
||||
if metadata and metadata.get("template") and attachments:
|
||||
_tmpl = metadata.get("template")
|
||||
_qid = metadata.get("question_id", "")
|
||||
_expected = []
|
||||
if _tmpl == "yes_no":
|
||||
_expected = ["ja", "nein", "yes", "no"]
|
||||
elif _tmpl == "confirm_cancel":
|
||||
_expected = ["bestätigen", "confirm", "abbrechen", "cancel"]
|
||||
elif _tmpl == "ok":
|
||||
_expected = ["ok", "okay", "verstanden", "alles klar"]
|
||||
elif _tmpl == "custom" and metadata.get("custom_buttons"):
|
||||
_expected = [b.lower() for b in metadata["custom_buttons"]]
|
||||
self._pending_clarifies[real_room_id] = {
|
||||
"question_id": _qid,
|
||||
"template": _tmpl,
|
||||
"expected": _expected,
|
||||
"timestamp": time.time(),
|
||||
"original_text": content,
|
||||
}
|
||||
|
||||
# ── P1-7: Proactive message splitting ────────────────────────
|
||||
# Rocket.Chat REST-API hat ein Message-Limit (~4000 Zeichen).
|
||||
# Lange Antworten (Tabellen, Listen) werden abgeschnitten mit
|
||||
# "(Response formatting failed, plain text:)" — aber die API
|
||||
# meldet trotzdem success. Daher MÜSSEN wir VOR dem Senden
|
||||
# splitten, nicht erst nach einem Fehlschlag.
|
||||
if len(content) > 3000 and attachments is None:
|
||||
logger.info(
|
||||
"[rocketchat] P1-7: Message too long (%d chars) — proactive split",
|
||||
len(content),
|
||||
)
|
||||
return await self._send_split(real_room_id, content)
|
||||
|
||||
success = await self._post_message_with_retry(real_room_id, content, attachments=attachments)
|
||||
if success:
|
||||
# If this message has buttons, mark the room so the next user
|
||||
# message from here stays put (no Archivar routing). Button
|
||||
# responses must be answered in the same room the question was
|
||||
# asked, otherwise the user sees "Ich antworte im Zielraum"
|
||||
# and the agent loses context.
|
||||
if attachments:
|
||||
self._rooms_with_pending_questions.add(real_room_id)
|
||||
logger.debug("[rocketchat] Room %s marked for button response", real_room_id)
|
||||
# ── B5v6.5: Conversation History — Agent-Antwort aufzeichnen ──
|
||||
if _MULTIROOM() and self._conversation_history is not None:
|
||||
await self._conversation_history.add(real_room_id, "agent", content)
|
||||
# ── V8.6 P1-3: PresenceEngine — KEIN decrement in send()! ──
|
||||
# Der Counter wird NUR im finally-Block von _process_incoming
|
||||
# dekrementiert (line 2794). send() kann mehrfach pro Turn
|
||||
# aufgerufen werden (Multi-Message, Split) — ein decrement hier
|
||||
# würde den Agenten vorzeitig auf "online" setzen.
|
||||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||||
|
||||
finally:
|
||||
# ── P1a: Symmetrisches Gate-Release ──
|
||||
if _gate_acquired and task_token:
|
||||
try:
|
||||
self._outbound_gate.release(_gate_room_id, task_token)
|
||||
except BaseException:
|
||||
logger.debug("[rocketchat] P5 V9.x: Gate release in send() finally failed (non-critical)")
|
||||
return SendResult(success=False, error="chat.postMessage failed")
|
||||
|
||||
# ── P1-4: Message Splitting ─────────────────────────────────────────
|
||||
@@ -7043,6 +7067,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if origin:
|
||||
_gate_room_id = origin
|
||||
task_token = _CURRENT_TASK_TOKEN.get()
|
||||
_gate_acquired = False # P1a: track whether WE created the gate entry
|
||||
if task_token and hasattr(self, '_outbound_gate') and self._outbound_gate is not None:
|
||||
from archivar.outbound_gate import GateDecision
|
||||
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
|
||||
@@ -7071,128 +7096,143 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
await self._post_message_unlocked(_gate_room_id, quick_reply_text)
|
||||
self._outbound_gate.stats.quick_reply += 1
|
||||
return SendResult(success=True, message_id="quick_reply")
|
||||
# Fell through: decision.allow is True — track if WE created the entry
|
||||
# (gate_clear = we own it; same_room_same_token = someone else owns it)
|
||||
_gate_acquired = (decision.reason == "gate_clear")
|
||||
|
||||
# ── Virtual → Real Room Translation ─────────────────────────
|
||||
# chat_id from Hermes session is virtual (e.g. "user:alice").
|
||||
# We must resolve it to a real Rocket.Chat room_id for REST API.
|
||||
real_room_id = chat_id
|
||||
if chat_id.startswith("user:"):
|
||||
# Priority 0: ContextVar from the message that triggered this turn
|
||||
# P1 Cross-Contamination-Fix: Task-Token-Validierung VOR Verwendung.
|
||||
# _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen stale Wert
|
||||
# vom Parent-Task erben. Wir validieren gegen _room_context task_token,
|
||||
# um Cross-Contamination (Auto-Route → Widerspruch → falscher Raum) zu
|
||||
# verhindern.
|
||||
origin = _CURRENT_ORIGIN_ROOM.get()
|
||||
if origin:
|
||||
# Pre-Read-Validierung: Task-Token-Match prüfen
|
||||
current_token = _CURRENT_TASK_TOKEN.get()
|
||||
ctx_entry = _room_context.get(chat_id, {})
|
||||
stored_token = ctx_entry.get("task_token", "")
|
||||
# Token-Mismatch: _CURRENT_ORIGIN_ROOM ist stale → skippen,
|
||||
# normale ContextVar-Logik weiterlaufen lassen
|
||||
if current_token and stored_token and current_token != stored_token:
|
||||
routing_counter.increment('priority0_token_mismatch_skip')
|
||||
logger.info(
|
||||
"[rocketchat] send_clarify Priority 0 token mismatch for %s — "
|
||||
"skipping stale ContextVar, falling through to _room_context",
|
||||
chat_id,
|
||||
)
|
||||
origin = "" # Force fallthrough
|
||||
if origin:
|
||||
real_room_id = origin
|
||||
logger.debug("[rocketchat] send_clarify via ContextVar: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||||
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
||||
fallback_origin = _get_room_context_origin(chat_id)
|
||||
if fallback_origin:
|
||||
real_room_id = fallback_origin
|
||||
routing_counter.increment('contextvar_reset_fallback')
|
||||
logger.info("[rocketchat] send_clarify via _room_context fallback: %s → %s", chat_id, real_room_id)
|
||||
|
||||
# ── P1a: try/finally für symmetrisches Gate-Release ─────────
|
||||
# Bei Exception in send_clarify() hängt sonst der Gate-Eintrag.
|
||||
try:
|
||||
# ── Virtual → Real Room Translation ─────────────────────────
|
||||
# chat_id from Hermes session is virtual (e.g. "user:alice").
|
||||
# We must resolve it to a real Rocket.Chat room_id for REST API.
|
||||
real_room_id = chat_id
|
||||
if chat_id.startswith("user:"):
|
||||
# Priority 0: ContextVar from the message that triggered this turn
|
||||
# P1 Cross-Contamination-Fix: Task-Token-Validierung VOR Verwendung.
|
||||
# _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen stale Wert
|
||||
# vom Parent-Task erben. Wir validieren gegen _room_context task_token,
|
||||
# um Cross-Contamination (Auto-Route → Widerspruch → falscher Raum) zu
|
||||
# verhindern.
|
||||
origin = _CURRENT_ORIGIN_ROOM.get()
|
||||
if origin:
|
||||
# Pre-Read-Validierung: Task-Token-Match prüfen
|
||||
current_token = _CURRENT_TASK_TOKEN.get()
|
||||
ctx_entry = _room_context.get(chat_id, {})
|
||||
stored_token = ctx_entry.get("task_token", "")
|
||||
# Token-Mismatch: _CURRENT_ORIGIN_ROOM ist stale → skippen,
|
||||
# normale ContextVar-Logik weiterlaufen lassen
|
||||
if current_token and stored_token and current_token != stored_token:
|
||||
routing_counter.increment('priority0_token_mismatch_skip')
|
||||
logger.info(
|
||||
"[rocketchat] send_clarify Priority 0 token mismatch for %s — "
|
||||
"skipping stale ContextVar, falling through to _room_context",
|
||||
chat_id,
|
||||
)
|
||||
origin = "" # Force fallthrough
|
||||
if origin:
|
||||
real_room_id = origin
|
||||
logger.debug("[rocketchat] send_clarify via ContextVar: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
||||
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||
if thematic_target:
|
||||
real_room_id = thematic_target
|
||||
logger.debug("[rocketchat] send_clarify via Archivar target: %s → %s", chat_id, real_room_id)
|
||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||||
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
||||
fallback_origin = _get_room_context_origin(chat_id)
|
||||
if fallback_origin:
|
||||
real_room_id = fallback_origin
|
||||
routing_counter.increment('contextvar_reset_fallback')
|
||||
logger.info("[rocketchat] send_clarify via _room_context fallback: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# Priority 2: proactive message — use most recent room for this user
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
real_room_id = rooms[-1] # last room user was active in
|
||||
logger.debug("[rocketchat] send_clarify via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||||
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
||||
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||
if thematic_target:
|
||||
real_room_id = thematic_target
|
||||
logger.debug("[rocketchat] send_clarify via Archivar target: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# Fallback: try to find any room with recent activity involving this user
|
||||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
||||
fallback_room = self._find_fallback_room_for_user(chat_id)
|
||||
if fallback_room:
|
||||
real_room_id = fallback_room
|
||||
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
||||
# Priority 2: proactive message — use most recent room for this user
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
real_room_id = rooms[-1] # last room user was active in
|
||||
logger.debug("[rocketchat] send_clarify via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
||||
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
||||
# Fallback: try to find any room with recent activity involving this user
|
||||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
||||
fallback_room = self._find_fallback_room_for_user(chat_id)
|
||||
if fallback_room:
|
||||
real_room_id = fallback_room
|
||||
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
||||
else:
|
||||
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
||||
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
||||
|
||||
# Render full option text in the message body so users
|
||||
# can read long choices that would be truncated in buttons.
|
||||
# Buttons keep short numeric labels (1, 2, …, Other).
|
||||
text = f"❓ {question}"
|
||||
option_lines = "\n".join(
|
||||
f"{i + 1}. {choice}"
|
||||
for i, choice in enumerate(choices)
|
||||
)
|
||||
text += f"\n\n{option_lines}"
|
||||
|
||||
# Build buttons with short labels to avoid truncation
|
||||
button_labels = [str(i + 1) for i in range(len(choices))]
|
||||
buttons = _build_custom_buttons(button_labels, prefix=f"CLARIFY:{clarify_id}")
|
||||
|
||||
# Add "Other" button with special handling
|
||||
buttons.append({
|
||||
"type": "button",
|
||||
"text": "✏️ Other",
|
||||
"msg": f"CLARIFY:{clarify_id}:other",
|
||||
"msg_in_chat_window": True,
|
||||
"style": "default",
|
||||
})
|
||||
|
||||
# Create attachment with buttons
|
||||
attachments = [{
|
||||
"color": "#1d74f5",
|
||||
"title": "Please choose an option:",
|
||||
"actions": buttons,
|
||||
}]
|
||||
|
||||
# Send message with buttons
|
||||
success = await self._post_message_with_retry(real_room_id, text, attachments=attachments)
|
||||
|
||||
if success:
|
||||
# Store clarify state for gateway identification
|
||||
self._clarify_state = getattr(self, '_clarify_state', {})
|
||||
self._clarify_state[clarify_id] = session_key
|
||||
|
||||
# For "Other" button, we need to enable text capture mode
|
||||
# This is done by calling mark_awaiting_text when the user clicks "Other"
|
||||
# The actual implementation will be in the message handling logic
|
||||
|
||||
# Mark room for button response handling (no Archivar routing)
|
||||
self._rooms_with_pending_questions.add(real_room_id)
|
||||
logger.debug("[rocketchat] Room %s marked for button response", real_room_id)
|
||||
|
||||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||||
else:
|
||||
# Fallback to text-based clarify if REST call fails
|
||||
logger.warning("[rocketchat] Failed to send clarify with buttons, falling back to text")
|
||||
return await super().send_clarify(
|
||||
chat_id=chat_id,
|
||||
question=question,
|
||||
choices=choices,
|
||||
clarify_id=clarify_id,
|
||||
session_key=session_key,
|
||||
metadata=metadata,
|
||||
# Render full option text in the message body so users
|
||||
# can read long choices that would be truncated in buttons.
|
||||
# Buttons keep short numeric labels (1, 2, …, Other).
|
||||
text = f"❓ {question}"
|
||||
option_lines = "\n".join(
|
||||
f"{i + 1}. {choice}"
|
||||
for i, choice in enumerate(choices)
|
||||
)
|
||||
text += f"\n\n{option_lines}"
|
||||
|
||||
# Build buttons with short labels to avoid truncation
|
||||
button_labels = [str(i + 1) for i in range(len(choices))]
|
||||
buttons = _build_custom_buttons(button_labels, prefix=f"CLARIFY:{clarify_id}")
|
||||
|
||||
# Add "Other" button with special handling
|
||||
buttons.append({
|
||||
"type": "button",
|
||||
"text": "✏️ Other",
|
||||
"msg": f"CLARIFY:{clarify_id}:other",
|
||||
"msg_in_chat_window": True,
|
||||
"style": "default",
|
||||
})
|
||||
|
||||
# Create attachment with buttons
|
||||
attachments = [{
|
||||
"color": "#1d74f5",
|
||||
"title": "Please choose an option:",
|
||||
"actions": buttons,
|
||||
}]
|
||||
|
||||
# Send message with buttons
|
||||
success = await self._post_message_with_retry(real_room_id, text, attachments=attachments)
|
||||
|
||||
if success:
|
||||
# Store clarify state for gateway identification
|
||||
self._clarify_state = getattr(self, '_clarify_state', {})
|
||||
self._clarify_state[clarify_id] = session_key
|
||||
|
||||
# For "Other" button, we need to enable text capture mode
|
||||
# This is done by calling mark_awaiting_text when the user clicks "Other"
|
||||
# The actual implementation will be in the message handling logic
|
||||
|
||||
# Mark room for button response handling (no Archivar routing)
|
||||
self._rooms_with_pending_questions.add(real_room_id)
|
||||
logger.debug("[rocketchat] Room %s marked for button response", real_room_id)
|
||||
|
||||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||||
else:
|
||||
# Fallback to text-based clarify if REST call fails
|
||||
logger.warning("[rocketchat] Failed to send clarify with buttons, falling back to text")
|
||||
|
||||
finally:
|
||||
# ── P1a: Symmetrisches Gate-Release ──
|
||||
if _gate_acquired and task_token:
|
||||
try:
|
||||
self._outbound_gate.release(_gate_room_id, task_token)
|
||||
except BaseException:
|
||||
logger.debug("[rocketchat] P5 V9.x: Gate release in send_clarify() finally failed (non-critical)")
|
||||
return await super().send_clarify(
|
||||
chat_id=chat_id,
|
||||
question=question,
|
||||
choices=choices,
|
||||
clarify_id=clarify_id,
|
||||
session_key=session_key,
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
async def send_typing(self, chat_id: str, metadata=None) -> None:
|
||||
pass
|
||||
|
||||
Reference in New Issue
Block a user