April 21, 2026

[Funktionsanfrage für Event-Hook sessions_send zur garantierten Übergabesichtbarkeit] - Feature Request: sessions_send Event Hook for Guaranteed Handoff Visibility

Implementieren Sie einen deterministischen Event-Hook für sessions_send, um eine sichtbare Nachrichtenzustellung und Zustellungsbestätigung zwischen Agents zu gewährleisten.

🔍 Symptome

Aktuelle Einschränkungsmanifestationen

Wenn Agenten inter-session-Übergaben mit sessions_send durchführen, werden häufig folgende Fehlermodi beobachtet:

Stille Verarbeitung ohne Bestätigung


# Agent A initiates handoff
sessions_send(
    target_session="project-alpha",
    payload={"task": "review_pr_442", "priority": "high"}
)
# Agent B processes silently — no visible message in target topic
# User sees no indication that handoff occurred

Brüchige Prompt-Level-Durchsetzung

Die aktuelle Minderung basiert auf Prompt-Anweisungen, die häufig fehlschlagen:


# In Agent A's prompt (often ignored during compaction or high load):
# "After calling sessions_send, ALWAYS post a visible message to the target topic."

# Reality: Agent may compact context, lose this instruction, or:
# 1. Call sessions_send ✓
# 2. Forget to post visible message ✗
# 3. User has no visibility into handoff status

Keine Zustellbestätigung an den Absender


# Agent A sends handoff
result = sessions_send(...)

# result provides no confirmation that:
# - Message was queued
# - Target session exists
# - Delivery was attempted
# Agent A operates in uncertainty

Benutzerseitige Symptome

  • Benutzer können nicht feststellen, ob inter-session-Übergaben erfolgreich waren
  • Kein Prüfpfad für die Arbeitsverteilung zwischen Agenten
  • Multi-Agent-Workflows erscheinen undurchsichtig und nicht vertrauenswürdig
  • Das Debugging von Übergabefehlern erfordert manuelle Protokollinspektion

🧠 Ursache

Analyse der architektonischen Lücke

Die aktuelle sessions_send-Implementierung hat eine fundamentale Designbeschränkung:

1. Fire-and-Forget-Nachrichtenzustellung


# Current implementation (conceptual)
def sessions_send(target_session, payload, ...):
    queue_message(target_session, payload)
    return {"status": "queued"}  # No hook, no side effects

Die Funktion liefert die Nutzlast aus, bietet aber keinen Erweiterungspunkt für:

  • Nebenwirkungen bei der Zustellung
  • Cross-Session-Benachrichtigungen
  • Audit-Protokollierung

2. Trennung von Transport und Präsentation

Die sessions_send-Transportschicht ist von der Telegram-Präsentationsschicht entkoppelt:

┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ Agent A │ │ Gateway │ │ Agent B │ │ sessions_send │─────▶│ (transport) │─────▶│ (processing) │ └─────────────────┘ └─────────────────┘ └─────────────────┘ │ │ │ │ │ ▼ ▼ ▼ ┌─────────────────┐ (no receipt) (no hook point) │ Telegram Bot │ │ (presentation) │ └─────────────────┘

3. Prompt-Level-Durchsetzung ist inhärent unzuverlässig

Die aktuelle Minderung basiert auf LLM-Verhalten, das nicht garantiert werden kann:

  • Kontextfensterdruck führt zu Anweisungsverlust
  • Komprimierung kann kritische Verhaltensprompts entfernen
  • Agentenautonomie bedeutet, dass Prompts Vorschläge sind, keine Einschränkungen
  • Keine Atomarität zwischen sessions_send und Nachrichtenposting

4. Kein Ereignissystem für Cross-Session-Koordination

Das Fehlen eines Ereignis-Hooks bedeutet:

  • Gateway kann keine Nebenwirkungen bei der Zustellung auslösen
  • Keine Gelegenheit für Zustellbestätigung zurück zum Absender
  • Auto-Acknowledgment erfordert manuelle Agentenimplementierung
  • Kein deklarativer Konfigurationspfad

🛠️ Schritt-für-Schritt-Lösung

Vorgeschlagene Implementierung: sessionReceive-Ereignis-Hook

Schritt 1: Konfigurieren Sie den Hook in den Gateway-Einstellungen

Fügen Sie Folgendes zu Ihrer OpenClaw-Gateway-Konfiguration hinzu:

{
  "hooks": {
    "sessionReceive": {
      "autoAcknowledge": {
        "enabled": true,
        "message": "📨 Handoff received from {sender} — processing now.",
        "channel": "last",
        "topic_id": "{incoming_topic}"
      },
      "deliveryConfirmation": {
        "enabled": true,
        "confirm_to_session": "{sender_session}",
        "confirm_message": "✅ Delivered to {target_session} at {timestamp}"
      }
    }
  }
}

Schritt 2: Verstehen der Konfigurationsparameter

  • `enabled`: Boolean zur Aktivierung des Hooks
  • `message`: Vorlagenzeichenfolge mit Platzhaltern:
    • `{sender}` — Name des sendenden Agenten/der Sitzung
    • `{sender_session}` — Sitzungs-ID des Absenders
    • `{target_session}` — Sitzungs-ID dieses Sitzung
    • `{incoming_topic}` — Telegram-Themen-ID, wo die Nachricht angekommen ist
    • `{timestamp}` — ISO 8601-Zustellzeitstempel
  • `channel`: Ziel für Acknowledgment ("last", spezifische Themen-ID oder null)
  • `confirm_to_session`: Sitzungs-ID für Zustellquittung
  • `confirm_message`: Vorlagennachricht für Quittung

Schritt 3: Workaround-Implementierung (Aktuelles Python-Skript)

Bis die native Hook-Unterstützung implementiert ist, stellen Sie das bereitgestellte handoff.py-Skript bereit:

# handoff.py — Guaranteed Handoff Visibility Script

import os
import requests
from datetime import datetime

class HandoffManager:
    def __init__(self, bot_token: str, gateway_url: str):
        self.bot_token = bot_token
        self.gateway_url = gateway_url
        self.telegram_api = f"https://api.telegram.org/bot{bot_token}"
    
    def send_with_guaranteed_visibility(
        self,
        target_session: str,
        target_topic_id: int,
        payload: dict,
        sender_name: str = "System"
    ) -> dict:
        """
        Executes handoff with guaranteed visible acknowledgment.
        """
        # Step 1: Post visible message to target topic FIRST
        confirmation_msg = f"📨 Handoff incoming from {sender_name}"
        self._post_telegram_message(target_topic_id, confirmation_msg)
        
        # Step 2: Deliver payload to target session
        delivery_result = self._deliver_to_session(target_session, payload)
        
        # Step 3: Confirm delivery back to sender (if session provided)
        if sender_session := payload.get("_sender_session"):
            self._send_confirmation(sender_session, target_session)
        
        return {
            "status": "completed",
            "visible_posted": True,
            "payload_delivered": True,
            "confirmation_sent": bool(payload.get("_sender_session"))
        }
    
    def _post_telegram_message(self, topic_id: int, text: str) -> dict:
        """Post message to specific Telegram topic."""
        return requests.post(
            f"{self.telegram_api}/sendMessage",
            json={
                "chat_id": os.environ["TARGET_CHAT_ID"],
                "message_thread_id": topic_id,
                "text": text
            }
        ).json()
    
    def _deliver_to_session(self, session_id: str, payload: dict) -> dict:
        """Deliver payload via gateway sessions_send."""
        return requests.post(
            f"{self.gateway_url}/sessions/{session_id}/receive",
            json=payload,
            headers={"Authorization": f"Bearer {os.environ['GATEWAY_TOKEN']}"}
        ).json()
    
    def _send_confirmation(self, sender_session: str, target_session: str):
        """Send delivery receipt back to sender session."""
        confirmation = {
            "type": "handoff_confirmation",
            "target": target_session,
            "timestamp": datetime.utcnow().isoformat(),
            "status": "delivered"
        }
        requests.post(
            f"{self.gateway_url}/sessions/{sender_session}/receive",
            json=confirmation,
            headers={"Authorization": f"Bearer {os.environ['GATEWAY_TOKEN']}"}
        )

Schritt 4: Integration mit OpenClaw-Agent


# In your agent's tool implementation or middleware

from handoff import HandoffManager

# Initialize manager (from environment or config)
hm = HandoffManager(
    bot_token=os.environ["TELEGRAM_BOT_TOKEN"],
    gateway_url=os.environ["GATEWAY_URL"]
)

def safe_sessions_send(target_session: str, target_topic: int, payload: dict):
    """
    Drop-in replacement for sessions_send with guaranteed visibility.
    """
    enriched_payload = {
        **payload,
        "_sender_session": current_session_id,  # Enable confirmation
        "_handoff_type": "cross_agent"
    }
    
    result = hm.send_with_guaranteed_visibility(
        target_session=target_session,
        target_topic_id=target_topic,
        payload=enriched_payload,
        sender_name=current_agent_name
    )
    
    if not result["status"] == "completed":
        raise HandoffError(f"Delivery failed: {result}")
    
    return result

🧪 Verifizierung

Verifizierungsschritte für Workaround-Implementierung

Schritt 1: Einzelne Übergabe-Sichtbarkeit testen


# Execute handoff test
python -c "
from handoff import HandoffManager
import os

hm = HandoffManager(
    bot_token=os.environ['TELEGRAM_BOT_TOKEN'],
    gateway_url=os.environ['GATEWAY_URL']
)

result = hm.send_with_guaranteed_visibility(
    target_session='test-agent-01',
    target_topic_id=42,
    payload={'task': 'verify_handoff', 'test': True},
    sender_name='TestHarness'
)

print(f'Status: {result[\"status\"]}')
print(f'Visible Posted: {result[\"visible_posted\"]}')
print(f'Payload Delivered: {result[\"payload_delivered\"]}')
"

Erwartete Ausgabe:

Status: completed
Visible Posted: True
Payload Delivered: True
Payload Confirmation: True

Schritt 2: Telegram-Nachricht erscheint überprüfen

Überprüfen Sie das Ziel-Telegram-Thema auf die sichtbare Bestätigungsnachricht:


# Expected message in target topic:
📨 Handoff incoming from TestHarness

Schritt 3: Zustellbestätigung im Absender-Thema überprüfen

Überprüfen Sie die Sitzung/das Thema des Absenders auf die Zustellquittung:


# Expected message in sender topic:
✅ Delivered to test-agent-01 at 2024-01-15T10:30:00+00:00

Schritt 4: Gateway-Zustellprotokoll überprüfen


# Check gateway logs for delivery confirmation
curl -s -H "Authorization: Bearer $GATEWAY_TOKEN" \
  "$GATEWAY_URL/sessions/test-agent-01/history?limit=5" | jq '.[] | select(.type=="handoff_confirmation")'

Erwartet:

{
  "type": "handoff_confirmation",
  "target": "test-agent-01",
  "timestamp": "2024-01-15T10:30:00+00:00",
  "status": "delivered"
}

Schritt 5: End-to-End Multi-Agent-Flow-Test


# Simulate complete multi-agent workflow
python -c "
from handoff import HandoffManager
import os

hm = HandoffManager(
    bot_token=os.environ['TELEGRAM_BOT_TOKEN'],
    gateway_url=os.environ['GATEWAY_URL']
)

# Agent A → Agent B → Agent C chain
sessions = ['agent-a', 'agent-b', 'agent-c']
topics = [10, 20, 30]

for i in range(len(sessions) - 1):
    result = hm.send_with_guaranteed_visibility(
        target_session=sessions[i + 1],
        target_topic_id=topics[i + 1],
        payload={
            'task': f'handoff_{i}',
            '_sender_session': sessions[i],
            '_chain_position': i + 1
        },
        sender_name=f'Agent-{chr(65+i)}'
    )
    assert result['status'] == 'completed', f'Handoff {i} failed'

print('Chain verification: ALL PASSED')
"

⚠️ Häufige Fehler

Umgebungs- und Konfigurationsfallen

1. Fehlende Umgebungsvariablen


# Required but often missing:
# TELEGRAM_BOT_TOKEN      - Bot API token
# GATEWAY_URL             - Gateway base URL
# GATEWAY_TOKEN           - Gateway authentication
# TARGET_CHAT_ID          - Default Telegram chat

# Symptom:
# KeyError: 'TELEGRAM_BOT_TOKEN'

# Fix: Ensure all env vars are set in deployment
export TELEGRAM_BOT_TOKEN="123456:ABC-..."
export GATEWAY_URL="https://gateway.example.com"
export GATEWAY_TOKEN="gw_..."
export TARGET_CHAT_ID="-1001234567890"

2. Themen-ID-Abweichung


# Symptom:
# {'ok': False, 'error_code': 400, 'description': 'Bad Request: chat not found'}

# Cause: message_thread_id (topic) doesn't exist or forum not enabled

# Fix: Verify target chat has topics enabled:
# /setname Your Forum Name → Enable Forum
# Then use numeric topic IDs from:
curl -s "https://api.telegram.org/bot$TOKEN/getForumTopicByChat" \
  -d "chat_id=$CHAT_ID" -d "title=Target Topic"

3. Gateway-Sitzung existiert nicht


# Symptom:
# {'ok': False, 'error_code': 404, 'description': 'Session not found'}

# Fix: Verify session exists before handoff:
curl -s -H "Authorization: Bearer $GATEWAY_TOKEN" \
  "$GATEWAY_URL/sessions" | jq '.[] | select(.id=="agent-b")'

# Or create session proactively:
curl -s -X POST -H "Authorization: Bearer $GATEWAY_TOKEN" \
  "$GATEWAY_URL/sessions/agent-b" \
  -d '{"config": {"topic_id": 20}}'

4. Race Condition bei Bestätigungszustellung


# Symptom: Confirmation arrives AFTER sender processes next message
# (visual glitch where message appears out of order)

# Cause: Async delivery without ordering guarantee

# Fix: Use sequential delivery with acknowledgment:
result = send_visible_message(topic_id, message)
if result['ok']:
    deliver_payload(session_id, payload)  # Only after visible confirmed
    send_confirmation(sender_session, receipt)  # Only after payload delivered

Agentenverhaltensfallen

5. Doppelte Übergabe (Original + Hook)

Wenn nativer Hook zusammen mit Agent-Prompt-Anweisungen implementiert wird, können beide ausgelöst werden:


# Scenario: Native hook + old prompt instruction both fire

# User sees:
# 📨 Handoff received from Agent A — processing now.  (hook fires)
# 📨 Handoff received from Agent A — processing now.  (agent also fires)

# Fix: Remove prompt-level handoff instructions once native hook is enabled
# Or set agent to only handoff, never post

6. Themen-ID wird nicht durch Komprimierung weitergegeben


# Symptom: After context compaction, topic_id for handoff is lost

# Scenario:
# Agent has: sessions_to_topic = {'agent-b': 20}
# After compaction: sessions_to_topic = {}  (lost)

# Fix: Store mapping in persistent config, not context:
# config.yaml:
# handoff_mappings:
#   agent-b:
#     topic_id: 20
#     last_handoff: "2024-01-15T..."

7. Gateway-Timeout bei sichtbarer Nachricht


# Symptom:
# Handoff timeout after 30 seconds
# Telegram API responded slowly
# Visible message never posted
# Payload still delivered (inconsistent state)

# Fix: Implement timeout with retry:
def post_with_retry(topic_id, message, max_retries=3):
    for attempt in range(max_retries):
        try:
            return requests.post(
                TELEGRAM_API,
                json={...},
                timeout=10  # Hard timeout
            ).json()
        except requests.Timeout:
            if attempt == max_retries - 1:
                raise HandoffDeliveryError(f"Failed after {max_retries} attempts")

Multi-Agent-Design-Fallen

8. Erkennung zirkulärer Übergabe


# Symptom: Infinite loop of handoffs between agents

# Agent A → Agent B → Agent A → Agent B → ...

# Fix: Implement handoff depth tracking:
payload = {
    **payload,
    '_handoff_depth': payload.get('_handoff_depth', 0) + 1,
    '_handoff_chain': [...payload.get('_handoff_chain', []), current_session]
}

if payload['_handoff_depth'] > MAX_HANDOFF_DEPTH:
    raise CircularHandoffError(f"Max depth exceeded: {payload['_handoff_chain']}")

9. Sitzungsidentitätsverwirrung


# Symptom: Delivery confirmation goes to wrong session
# (user sees confirmation meant for another user)

# Cause: sender_session from shared/impersonated context

# Fix: Always resolve sender_session from authenticated context:
sender_session = authenticated_user.session_id  # Not from payload

🔗 Zugehörige Fehler

Kontextuell verbundene Probleme

Kreuzreferenztabelle

FehlercodeBeschreibungBeziehung
SESS_001Sitzung bei Zustellung nicht gefundenDirekt — Übergabe kann ohne Zielsitzung nicht abgeschlossen werden
SESS_002Sitzungskapazität überschrittenZugehörig — begrenzt Multi-Agent-Skalierung
HOOK_001Hook-KonfigurationsanalysefehlerDirekt — fehlkonfigurierte Hooks verhindern Feature-Implementierung
HOOK_002Hook-Ausführungs-TimeoutZugehörig — Zustellbestätigung kann Timeout haben
TG_400Ungültige Themen-/Chat-IDDirekt — Telegram-Zustellfehler
TG_429Telegram-Ratenlimit überschrittenZugehörig — Sichtbarkeitsnachricht-Ratenbegrenzung
AUTH_401Gateway-Authentifizierung fehlgeschlagenDirekt — alle Übergabeoperationen erfordern Auth
AUTH_403Sitzungszugriff verweigertZugehörig — Cross-Session-Übergabe-Berechtigungen
COMP_001Kontextkomprimierung entfernt ÜbergabestatusZugehörig — Sichtbarkeitsanweisungen während Komprimierung verloren

Zugehörige GitHub-Issues

  • [FEATURE] sessions_send return receipt — Frühere Anfrage nach Absender-seitiger Bestätigung (geschlossen, nicht implementiert)
  • [BUG] sessions_send silently fails when target session offline — Stiller Fehlermodus ermöglicht aktuelle fragile Workaround-Diskussion
  • [FEATURE] Event hook system for gateway lifecycle — Vorgeschlagene generische Hook-Architektur, die dieses Feature subsumieren könnte
  • [DOCS] Multi-agent handoff patterns documentation — Fehlende Anleitung zwingt jedes Team, Muster neu zu entdecken
  • [PERF] sessions_send latency under high load — Hook-Overhead muss bei Performance-Design berücksichtigt werden

Zugehörige Konfigurationsoptionen


# Related OpenClaw config options that may interact with this feature:

{
  "sessions": {
    "handoff_timeout": 30000,        // Timeout for handoff delivery
    "require_acknowledgment": false,  // Future: block until ack
    "max_handoff_depth": 5            // Prevent circular handoffs
  },
  "telegram": {
    "topic_mode": "required",         // Ensure topics exist
    "rate_limit_per_second": 30       // Affects auto-acknowledge rate
  },
  "hooks": {
    "sessionSend": { },                // Future: sender-side hook
    "sessionReceive": { }              // This feature
  }
}

Externe Abhängigkeiten

  • Telegram Bot API — Wird für sichtbares Nachrichtenposting verwendet; unterliegt Ratenlimits und Verfügbarkeit
  • Gateway Sessions API — Muss Zustellbestätigungs-Endpunkt unterstützen
  • Message Queue — Falls implementiert, muss Zustellreihenfolge garantiert werden

Belege & Quellen

Diese Troubleshooting-Anleitung wurde automatisch von der FixClaw Intelligence Pipeline aus Community-Diskussionen synthetisiert.