# llms.txt — Iaqui Gateway IA Integration ## Ficha de Descubrimiento de Habilidades del Gateway (IaaS) Iaqui Gateway es un broker e infraestructura middleware (IaaS) multitenant de mensajería para brokers oficiales de Meta (**WhatsApp Business Cloud API**, **Instagram Graph API**, **Facebook Messenger API**) y canales no-oficiales. Esta ficha de descubrimiento está diseñada para que agentes autónomos de IA y LLMs entiendan, consuman y operen Iaqui de forma nativa sin fricción de lectura. --- ## 🏛️ 1. Arquitectura y Autenticación ### Autenticación Todas las peticiones HTTP seguras requieren la clave API del Tenant en la cabecera `Authorization`: ```http Authorization: Bearer iq_live_... Content-Type: application/json ``` ### Formato de Canal ID Los canales se aprovisionan de forma multitenant y se identifican mediante un `channelId` (ej: `iq_chan_wa_soporte`). --- ## 📤 2. Enviar Mensajes (`POST /v1/messages`) Envía mensajes unificados. El Gateway encola y gestiona los límites de Meta de forma interna. ### A. Texto Simple ```json { "channelId": "iq_chan_wa_soporte", "channelType": "WHATSAPP", // "WHATSAPP" | "INSTAGRAM" | "FACEBOOK" "to": "5215512345678", "type": "text", "text": "Mensaje en texto plano. 🚀" } ``` ### B. Botones Interactivos (Quick Replies) ```json { "channelId": "iq_chan_wa_soporte", "channelType": "WHATSAPP", "to": "5215512345678", "type": "interactive", "interactive": { "type": "button", "header": { "type": "text", "text": "Título" }, "body": { "text": "¿Activar suscripción?" }, "footer": { "text": "Iaqui CRM" }, "action": { "buttons": [ { "type": "reply", "reply": { "id": "btn_yes", "title": "Sí" } }, { "type": "reply", "reply": { "id": "btn_no", "title": "No" } } ] } } } ``` ### C. Listas Interactivas (Menú de hasta 10 opciones) ```json { "channelId": "iq_chan_wa_soporte", "channelType": "WHATSAPP", "to": "5215512345678", "type": "interactive", "interactive": { "type": "list", "header": { "type": "text", "text": "Menú principal" }, "body": { "text": "Selecciona un área:" }, "action": { "button": "Ver Opciones", "sections": [ { "title": "Soporte", "rows": [ { "id": "row_ventas", "title": "Ventas", "description": "Planes y precios" }, { "id": "row_tech", "title": "Soporte Técnico", "description": "Líneas de ayuda" } ] } ] } } } ``` ### D. Enviar Flujos Conversacionales (WhatsApp Flows) Abre formularios nativos e interactivos en el chat. ```json { "channelId": "iq_chan_wa_soporte", "channelType": "WHATSAPP", "to": "5215512345678", "type": "interactive", "interactive": { "type": "flow", "header": { "type": "text", "text": "Formulario" }, "body": { "text": "Ingresa tus datos comercializadores" }, "action": { "name": "flow", "parameters": { "flow_message_version": "3", "flow_token": "iq_flow_tok_123", "flow_id": "7823984029472", "flow_cta": "Abrir", "flow_action": "navigate", "flow_action_payload": { "screen": "START", "data": { "prefilled_email": "dev@Iaqui.com" } } } } } } ``` ### E. Mensajes de Plantillas Oficiales (Templates) ```json { "channelId": "iq_chan_wa_soporte", "channelType": "WHATSAPP", "to": "5215512345678", "type": "template", "template": { "name": "factura_disponible", "language": { "code": "es" }, "components": [ { "type": "body", "parameters": [ { "type": "text", "text": "Cliente" }, { "type": "text", "text": "Mayo 2026" } ] } ] } } ``` --- ## 📥 3. Recibir Mensajes y Estados (Webhook Normalizado) El Gateway normaliza los webhooks de Meta y los despacha al webhook de tu CRM en un formato unificado. ### Mensaje de Texto Entrante (`message.received`) ```json { "event": "message.received", "channel": { "id": "iq_chan_wa_soporte", "type": "WHATSAPP" }, "contact": { "id": "5215512345678", "name": "Luis Gomez" }, "message": { "id": "wamid...", "type": "text", "text": "Hola, necesito soporte 🛠️", "timestamp": 1782398402 } } ``` ### Actualización de Estado (`message.sent` | `message.delivered` | `message.read` | `message.failed`) ```json { "event": "message.status", "channel": { "id": "iq_chan_wa_soporte", "type": "WHATSAPP" }, "message": { "id": "msg_iq_chan_...", "status": "read", "recipient": "5215512345678", "timestamp": 1782398412, "error": null } } ``` --- ## 👥 4. Gestión SaaS y Multi-Tenant (Embedded Signup) Para plataformas SaaS (como CRM o Whatsaky), el flujo oficial de onboarding permite conectar números de WhatsApp Business App sin fricciones: ### A. Crear Cliente (`POST /v1/customers`) ```json { "name": "Clínica DentalCare", "email": "contacto@dentalcare.com", "externalId": "client_crm_98234" } ``` *Respuesta: `201 Created` con el `customerId` (ej: `cust-uuid-12345`).* ### B. Generar Setup Link (`POST /v1/setup-links`) ```json { "customerId": "cust-uuid-12345", "redirectUrl": "https://my-saas.com/onboard/callback", "expiresInHours": 24 } ``` *Respuesta: Genera una URL de redirección a la que se envía al cliente final para iniciar el pop-up de Facebook Login / Meta Embedded Signup.* --- ## 📋 5. Gestión de Plantillas (Templates API) Permite administrar y consultar plantillas registradas oficialmente en Meta. ### A. Crear Plantilla (`POST /v1/templates`) ```json { "channelId": "iq_chan_wa_soporte", "name": "factura_disponible_cta", "language": "es", "category": "UTILITY", "components": [ { "type": "BODY", "text": "Hola {{1}}, tu factura de {{2}} ya está lista." } ] } ``` ### B. Listar/Sincronizar Plantillas (`GET /v1/templates?sync=true`) Obtiene la lista de plantillas aprobadas. `sync=true` fuerza la sincronización en tiempo real desde la API de Meta. ### C. Eliminar Plantilla (`DELETE /v1/templates/:name?channelId=iq_chan_wa_soporte`) Remueve la plantilla de la base de datos local y de los servidores de Meta. --- ## ⚙️ 6. Presets de Webhooks y Automatización Para evitar configurar decenas de checkboxes de eventos de forma manual, Iaqui Gateway admite **Presets** durante la creación del Webhook (`POST /v1/webhooks`): * **`CRM_STANDARD`**: Suscribe automáticamente a `message.received`, `message.sent`, `message.delivered`, `message.read`, `message.failed` y `template.status_changed`. * **`LOG_ONLY`**: Suscribe a todos los eventos (`*`). * **`MINIMAL`**: Suscribe únicamente a `message.received`. ### Ejemplo de Creación con Preset: ```json { "url": "https://agenda.iaqui.com/api/iaqui/webhook", "secret": "firma_secreta_opcional", "preset": "CRM_STANDARD" } ``` --- ## ⚡ 7. Límites de Velocidad, Colas y Reintentos - **Encolamiento**: El Gateway almacena las peticiones salientes en Redis usando BullMQ. Esto previene rebasar los límites oficiales de velocidad de Meta. - **Reintentos**: El sistema realiza hasta 5 reintentos automáticos con retroceso exponencial en caso de errores transitorios de la API de Meta (ej: código 131301 - Límite de cuota alcanzado). --- ## 🧠 8. Soporte MCP (Model Context Protocol) NATIVO Iaqui Gateway incorpora endpoints de control MCP para que agentes de IA locales (como Claude Desktop o Cursor) operen el sistema de forma directa. ### A. Listar Herramientas del Gateway (`POST /mcp/list`) Devuelve la lista de herramientas disponibles para el LLM. ### B. Ejecutar una Herramienta (`POST /mcp/call`) Ejecuta acciones (enviar mensajes, verificar WABA, leer logs) directamente en la pasarela en representación de la IA.