Solicitud de Función: Gancho de Evento sessions_send para Visibilidad de Transferencia Garantizada - Feature Request: sessions_send Event Hook for Guaranteed Handoff Visibility
Implementar un gancho de evento determinista para sessions_send para garantizar la entrega visible de mensajes y la confirmación de entrega entre agentes.
🔍 Síntomas
Manifestaciones de limitaciones actuales
Cuando los agentes realizan transferencias entre sesiones usando sessions_send, se observan comúnmente los siguientes modos de falla:
Procesamiento silencioso sin confirmación
# 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
Aplicación frágil a nivel de prompt
La mitigación actual depende de instrucciones de prompt que frecuentemente fallan:
# 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
Sin confirmación de entrega al remitente
# 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
Síntomas visibles para el usuario
- Los usuarios no pueden determinar si las transferencias entre sesiones tuvieron éxito
- No hay registro de auditoría de la distribución de trabajo entre agentes
- Los flujos de trabajo multiagente parecen opacos y no confiables
- La depuración de fallas de transferencia requiere inspección manual de registros
🧠 Causa raíz
Análisis de brecha arquitectónica
La implementación actual de sessions_send tiene una limitación de diseño fundamental:
1. Entrega de mensajes de tipo “disparar y olvidar”
# Current implementation (conceptual)
def sessions_send(target_session, payload, ...):
queue_message(target_session, payload)
return {"status": "queued"} # No hook, no side effects
La función entrega el contenido pero no proporciona ningún punto de extensibilidad para:
- Efectos secundarios tras la entrega
- Notificaciones entre sesiones
- Registro de auditoría
2. Separación del transporte y la presentación
La capa de transporte de sessions_send está desacoplada de la capa de presentación de Telegram:
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ Agent A │ │ Gateway │ │ Agent B │ │ sessions_send │─────▶│ (transport) │─────▶│ (processing) │ └─────────────────┘ └─────────────────┘ └─────────────────┘ │ │ │ │ │ ▼ ▼ ▼ ┌─────────────────┐ (no receipt) (no hook point) │ Telegram Bot │ │ (presentation) │ └─────────────────┘
3. La aplicación a nivel de prompt es inherentemente no confiable
La mitigación actual depende del comportamiento del LLM, lo cual no puede garantizarse:
- La presión sobre la ventana de contexto causa pérdida de instrucciones
- La compactación puede eliminar prompts de comportamiento críticos
- La autonomía del agente significa que los prompts son sugerencias, no restricciones
- No hay atomicidad entre sessions_send y la publicación de mensajes
4. Ausencia de sistema de eventos para coordinación entre sesiones
La ausencia de un gancho de eventos significa que:
- El gateway no puede activar efectos secundarios tras la entrega
- No hay oportunidad para confirmación de entrega al remitente
- El auto-reconocimiento requiere implementación manual del agente
- No hay ruta de configuración declarativa
🛠️ Solución paso a paso
Implementación propuesta: Gancho de eventos sessionReceive
Paso 1: Configurar el gancho en la configuración del Gateway
Agregue lo siguiente a su configuración del gateway OpenClaw:
{
"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}"
}
}
}
}
Paso 2: Comprender los parámetros de configuración
- `enabled`: Booleano para activar el gancho
- `message`: Cadena de plantilla con marcadores de posición:
- `{sender}` — Nombre del agente/sesión remitente
- `{sender_session}` — ID de sesión del remitente
- `{target_session}` — ID de esta sesión
- `{incoming_topic}` — ID del tema de Telegram donde llegó el mensaje
- `{timestamp}` — Marca de tiempo de entrega ISO 8601
- `channel`: Destino para el reconocimiento ("last", ID de tema específico, o null)
- `confirm_to_session`: ID de sesión para enviar el recibo de entrega
- `confirm_message`: Plantilla del mensaje de recibo
Paso 3: Implementación de solución alternativa (Script Python actual)
Hasta que se implemente el soporte nativo del gancho, despliegue el script handoff.py proporcionado:
# 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']}"}
)
Paso 4: Integración con el Agente OpenClaw
# 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
🧪 Verificación
Pasos de verificación para la implementación de la solución alternativa
Paso 1: Probar visibilidad de una sola transferencia
# 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\"]}')
"
Salida esperada:
Status: completed
Visible Posted: True
Payload Delivered: True
Payload Confirmation: True
Paso 2: Verificar que aparece el mensaje de Telegram
Verifique el tema de Telegram objetivo para el mensaje de confirmación visible:
# Expected message in target topic:
📨 Handoff incoming from TestHarness
Paso 3: Verificar confirmación de entrega en el tema del remitente
Verifique la sesión/tema del remitente para el recibo de entrega:
# Expected message in sender topic:
✅ Delivered to test-agent-01 at 2024-01-15T10:30:00+00:00
Paso 4: Verificar el registro de entrega del Gateway
# 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")'
Esperado:
{
"type": "handoff_confirmation",
"target": "test-agent-01",
"timestamp": "2024-01-15T10:30:00+00:00",
"status": "delivered"
}
Paso 5: Prueba de flujo multiagente de extremo a extremo
# 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')
"
⚠️ Errores comunes
Errores de entorno y configuración
1. Variables de entorno faltantes
# 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. Discrepancia en el ID del tema
# 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. La sesión del Gateway no existe
# 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. Condición de carrera en la entrega de confirmación
# 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
Errores de comportamiento del agente
5. Doble transferencia (Original + Gancho)
Si el gancho nativo se implementa junto con las instrucciones del prompt del agente, ambos pueden activarse:
# 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. ID del tema no propagado a través de la compactación
# 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. Tiempo de espera del Gateway en mensaje visible
# 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")
Errores de diseño multiagente
8. Detección de transferencia circular
# 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. Confusión de identidad de sesión
# 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
🔗 Errores relacionados
Problemas conectados contextualmente
Tabla de referencias cruzadas
| Código de error | Descripción | Relación |
|---|---|---|
SESS_001 | Sesión no encontrada al momento de entrega | Directa — la transferencia no puede completarse sin la sesión objetivo |
SESS_002 | Capacidad de sesión excedida | Relacionada — limita el escalamiento multiagente |
HOOK_001 | Error de análisis de configuración del gancho | Directa — los ganchos mal configurados previenen la implementación de la funcionalidad |
HOOK_002 | Tiempo de espera en ejecución del gancho | Relacionada — la confirmación de entrega puede agotar el tiempo |
TG_400 | ID de tema/chat inválido | Directa — falla de entrega de Telegram |
TG_429 | Límite de tasa de Telegram excedido | Relacionada — limitación de tasa del mensaje visible |
AUTH_401 | Autenticación del Gateway fallida | Directa — todas las operaciones de transferencia requieren autenticación |
AUTH_403 | Acceso a sesión denegado | Relacionada — permisos de transferencia entre sesiones |
COMP_001 | La compactación de contexto elimina el estado de transferencia | Relacionada — instrucciones de visibilidad perdidas durante la compactación |
Issues de GitHub relacionados
- [FEATURE] sessions_send return receipt — Solicitud anterior para confirmación del lado del remitente (cerrada, no implementada)
- [BUG] sessions_send silently fails when target session offline — Modo de falla silenciosa habilitó la discusión actual de solución alternativa frágil
- [FEATURE] Event hook system for gateway lifecycle — Arquitectura de ganchos genéricos propuesta que podría subsumir esta funcionalidad
- [DOCS] Multi-agent handoff patterns documentation — Guía faltante fuerza a cada equipo a redescubrir patrones
- [PERF] sessions_send latency under high load — La sobrecarga del gancho debe considerarse en el diseño de rendimiento
Opciones de configuración relacionadas
# 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
}
}
Dependencias externas
- API del Bot de Telegram — Usada para publicación de mensajes visibles; sujeta a límites de tasa y disponibilidad
- API de Sesiones del Gateway — Debe soportar endpoint de confirmación de entrega
- Cola de mensajes — Si se implementa, debe garantizar el orden de entrega