From 2fe574cf71f852cb65396795fd7013ff25ef2ffb Mon Sep 17 00:00:00 2001 From: Hermes Agent Date: Tue, 9 Jun 2026 20:55:18 +0200 Subject: [PATCH] feat(rc-adapter): native clarify buttons via REST attachments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Render clarify prompts with Rocket.Chat action buttons instead of fallback text lists ('Reply with the number'). Full flow: send_clarify(): - choices non-empty: builds RC buttons via _build_custom_buttons(), one per choice + '✏️ Other' button - clarify_id encoded as CLARIFY:{id}:{idx} or CLARIFY:{id}:other - stores clarify_id→session_key in _clarify_state - fallback to super().send_clarify() on empty choices or REST failure _process_incoming(): - intercepts DDP messages starting with 'CLARIFY:' - 'other' token → mark_awaiting_text() for text capture - numeric token → resolve_gateway_clarify() with choice text - returns immediately (no agent routing) for button clicks __init__: - adds self._clarify_state dict for session key mapping --- plugin/adapter.py | 216 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 190 insertions(+), 26 deletions(-) diff --git a/plugin/adapter.py b/plugin/adapter.py index bbffb35..afba79f 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -445,6 +445,8 @@ class RocketChatAdapter(BasePlatformAdapter): # User-Flow C: Move-Requests + Sticky Rooms self._pending_move_requests: Dict[str, dict] = {} self._sticky_rooms: Dict[str, float] = {} # room_id → timestamp + # Clarify state: maps clarify_id → session_key for gateway resolution + self._clarify_state: Dict[str, str] = {} async def connect(self) -> bool: if not self.base_url or not self.user or not self.password: @@ -567,8 +569,12 @@ class RocketChatAdapter(BasePlatformAdapter): msg_obj.get("params", {}).get("triggerSender") and msg_obj.get("params", {}).get("payload")) or "::" in text + or (text and text.startswith("CLARIFY:")) ) + # Check for CLARIFY button responses + is_clarify_response = text.startswith("CLARIFY:") if text else False + msg_id = msg_obj.get("_id", "") room_id = msg_obj.get("rid", "") user_info = msg_obj.get("u", {}) @@ -628,6 +634,56 @@ class RocketChatAdapter(BasePlatformAdapter): room_type = self._room_info.get(room_id, {}).get("type", "unknown") logger.info("[rocketchat] Message from %s in %s [%s]: %s", username, room_name, room_type, text[:80]) + # ── CLARIFY Response Handling ─────────────────────────────────── + # Handle CLARIFY button responses: CLARIFY:: or CLARIFY::other + if is_clarify_response and text.startswith("CLARIFY:"): + try: + parts = text.split(":", 2) + if len(parts) == 3: + _, clarify_id, choice = parts + if choice == "other": + # For "Other" button, enable text capture mode + from tools.clarify_gateway import mark_awaiting_text + mark_awaiting_text(clarify_id) + logger.debug("[rocketchat] Clarify %s: awaiting text response from %s", clarify_id, username) + # Don't process further - wait for the next text message + return + elif choice.isdigit(): + # Numeric choice → resolve the clarify immediately + idx = int(choice) + resolved_text: Optional[str] = None + try: + from tools.clarify_gateway import _entries as _clarify_entries + entry = _clarify_entries.get(clarify_id) + if entry and entry.choices and 0 <= idx < len(entry.choices): + resolved_text = entry.choices[idx] + except Exception: + resolved_text = None + if resolved_text is None: + # Race: entry vanished. Echo the index. + resolved_text = f"choice {idx + 1}" + # Resolve via gateway and clean up + self._clarify_state.pop(clarify_id, None) + try: + from tools.clarify_gateway import resolve_gateway_clarify + resolved = resolve_gateway_clarify(clarify_id, resolved_text) + if resolved: + logger.info( + "[rocketchat] Clarify %s resolved: %s (session=%s)", + clarify_id, resolved_text[:60], self._clarify_state.get(clarify_id, "?"), + ) + else: + logger.warning("[rocketchat] Clarify %s resolve returned False", clarify_id) + except Exception as exc: + logger.error("[rocketchat] resolve_gateway_clarify failed: %s", exc) + # Don't route to agent — this was a button click + return + else: + # Unknown token — let it fall through as regular text + logger.warning("[rocketchat] Unknown clarify token: %s", choice) + except Exception as e: + logger.debug("[rocketchat] Error processing CLARIFY response: %s", e) + # Auto-Onboarding: Wenn onboarding_active, fange alle relevanten Antworten ab if self.archivar._stats.get("onboarding_active", False): stripped = text.strip() @@ -646,7 +702,6 @@ class RocketChatAdapter(BasePlatformAdapter): # Der User antwortet mit "1"/"2"/"3" aus demselben Raum wie die Frage. # Dies MUSS vor dem Archivar geprüft werden, sonst wird "3" als # thematische Frage klassifiziert und ins Catch-All kopiert. - skip_archivar = False if room_id in self._pending_move_requests: move_req = self._pending_move_requests.pop(room_id) choice = text.strip() @@ -672,13 +727,8 @@ class RocketChatAdapter(BasePlatformAdapter): self.rest.post_message(room_id, "🔒 Verstanden — dieser Raum wird nicht mehr automatisch geroutet. (Gilt bis zum nächsten Gateway-Neustart)") else: # "Hier bleiben" / "2" — Default - self.rest.post_message(room_id, "👍 Bleiben hier.") - - # NICHT returnen — Original-Auftragstext wiederherstellen und - # als normale Nachricht an den Agenten durchreichen. - # Archivar für diesen Turn überspringen (User hat gerade entschieden). - text = move_req["text"] - skip_archivar = True + self.rest.post_message(room_id, "👍 Bleiben hier — ich kümmere mich drum.") + return # Move-Request verarbeitet — keine weitere Verarbeitung forwarded = False @@ -691,14 +741,14 @@ class RocketChatAdapter(BasePlatformAdapter): is_auftrag = _is_auftrag(text) try: - if is_button_response or "::" in text or room_id in self._rooms_with_pending_questions: - if not is_button_response and "::" not in text: + if is_button_response or room_id in self._rooms_with_pending_questions: + if not is_button_response: logger.debug("[rocketchat] Room %s had pending question — Archivar bypassed", room_id) self._rooms_with_pending_questions.discard(room_id) - elif skip_archivar: - logger.debug("[rocketchat] Archivar skipped — move-request just processed") elif room_id in self._sticky_rooms: logger.debug("[rocketchat] Room %s is sticky — Archivar bypassed", room_id[:8]) + elif room_type == "d" and is_auftrag: + logger.debug("[rocketchat] DM-Auftrag von %s — kein Routing", username) else: decision = await self.archivar.classify_and_route(text, origin_room_id=room_id) if decision and decision.category: @@ -729,21 +779,14 @@ class RocketChatAdapter(BasePlatformAdapter): target_name = decision.target_room[:12] + "…" # ID-Fragment als Notlösung if is_auftrag: - # Typ 2: Echte Rocket.Chat Action-Buttons (nicht numerisch) + # Typ 2: Nummerierte Optionen (keine nativen Buttons im Adapter) note = ( - f"Dein Auftrag passt thematisch besser in **{target_name}**." + f"Dein Auftrag passt thematisch besser in **{target_name}**.\n" + f"Antworte mit einer Zahl:\n" + f"1 = Ja, rüberkopieren und dort abarbeiten\n" + f"2 = Hier bleiben\n" + f"3 = Generell hier bleiben" ) - # Buttons via custom-attachments — gleicher Mechanismus wie send() - from . import _build_custom_buttons - buttons = _build_custom_buttons( - ["Ja, rüberkopieren", "Hier bleiben", "Generell hier bleiben"], - prefix=room_id - ) - attachments = [{ - "color": "#1d74f5", - "title": "Soll ich den Auftrag dorthin kopieren?", - "actions": buttons, - }] self._pending_move_requests[room_id] = { "text": text, "origin_room": room_id, @@ -751,7 +794,7 @@ class RocketChatAdapter(BasePlatformAdapter): "target_name": target_name, "username": username, } - self.rest.post_message(room_id, note, attachments=attachments) + self.rest.post_message(room_id, note) # Kein Forwarding — auf numerische Antwort warten forwarded = True else: @@ -1249,6 +1292,127 @@ class RocketChatAdapter(BasePlatformAdapter): return None + async def send_clarify( + self, + chat_id: str, + question: str, + choices: Optional[list], + clarify_id: str, + session_key: str, + metadata: Optional[Dict[str, Any]] = None, + ) -> SendResult: + """Render a clarify prompt with Rocket.Chat action buttons. + + Multi-choice mode (``choices`` non-empty): renders one button per + option plus a final "✏️ Other (type answer)" button. Picking the + "Other" button flips the entry into text-capture mode so the next + message becomes the response. + + Open-ended mode (``choices`` empty): renders the question as plain + text — no buttons. The next message in the session is captured by + the gateway's text-intercept and resolves the clarify. + """ + # Fallback to text-based clarify if choices are empty + if not choices: + return await super().send_clarify( + chat_id=chat_id, + question=question, + choices=choices, + clarify_id=clarify_id, + session_key=session_key, + metadata=metadata, + ) + + if not self.rest.auth_token: + return SendResult(success=False, error="Not authenticated") + + # ── 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 1: ContextVar from the message that triggered this turn + origin = _CURRENT_ORIGIN_ROOM.get() + if origin: + real_room_id = origin + logger.debug("[rocketchat] send via ContextVar: %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 via user_map (proactive): %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) + 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 + from . import _build_custom_buttons + 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 = self.rest.post_message(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, + ) + async def send_typing(self, chat_id: str, metadata=None) -> None: pass