diff --git a/README-IMPROVED.md b/README-IMPROVED.md new file mode 100644 index 000000000..cc75642ba --- /dev/null +++ b/README-IMPROVED.md @@ -0,0 +1,806 @@ +# πŸ€– Jarvis β€” Personal AI Assistant + +

+ Your Personal AI Assistant Running on Your Own Devices +

+ +

+ CI status + GitHub release + MIT License +

+ +## πŸ“‹ Tabla de Contenidos + +- [ΒΏQuΓ© es Jarvis?](#quΓ©-es-jarvis) +- [CaracterΓ­sticas Principales](#caracterΓ­sticas-principales) +- [Arquitectura del Sistema](#arquitectura-del-sistema) +- [Diagrama de Uso](#diagrama-de-uso) +- [InstalaciΓ³n RΓ‘pida](#instalaciΓ³n-rΓ‘pida) +- [ConfiguraciΓ³n](#configuraciΓ³n) +- [Uso BΓ‘sico](#uso-bΓ‘sico) +- [Canales Soportados](#canales-soportados) +- [DocumentaciΓ³n Completa](#documentaciΓ³n-completa) +- [Desarrollo](#desarrollo) +- [Contribuir](#contribuir) + +--- + +## ΒΏQuΓ© es Jarvis? + +**Jarvis** es un **asistente personal de IA** que se ejecuta en tus propios dispositivos. Es una plataforma local-first, auto-hospedada y diseΓ±ada para control de usuario ΓΊnico. + +### Beneficios Clave + +βœ… **Privacidad Total** β€” Todo se ejecuta localmente, tus datos nunca salen de tu control +βœ… **Multi-Canal** β€” Conecta con WhatsApp, Telegram, Slack, Discord, Signal, iMessage, Teams y mΓ‘s +βœ… **Multi-Plataforma** β€” Funciona en macOS, iOS, Android, Linux y Windows (WSL2) +βœ… **Extensible** β€” Sistema robusto de plugins para aΓ±adir funcionalidad +βœ… **Siempre Activo** β€” Daemon persistente vΓ­a systemd/launchd +βœ… **Capacidades de Voz** β€” Voice Wake y Talk Mode en macOS/iOS/Android +βœ… **Canvas Visual** β€” Espacio de trabajo visual controlado por el agente + +--- + +## CaracterΓ­sticas Principales + +### πŸ” Seguridad y Privacidad +- **Local-First**: Todos tus datos permanecen en tu dispositivo +- **Sin Servidor Central**: No hay dependencia de servicios de terceros +- **Emparejamiento Seguro**: Sistema de cΓ³digos para autorizaciΓ³n DM +- **Lista de Permitidos**: Control granular de quiΓ©n puede interactuar + +### πŸ’¬ Multi-Canal +- **MensajerΓ­a Unificada**: Una interfaz para todos tus canales de chat +- **13+ Canales Integrados**: WhatsApp, Telegram, Discord, Slack, Signal, y mΓ‘s +- **Enrutamiento Inteligente**: Mensajes dirigidos al agente correcto +- **Respuestas Contextuales**: Mantiene contexto en conversaciones grupales + +### πŸ› οΈ Herramientas Poderosas +- **Browser Tool**: AutomatizaciΓ³n web con Playwright +- **Canvas Tool**: Espacio de trabajo visual con A2UI +- **Image Tool**: AnΓ‘lisis y generaciΓ³n de imΓ‘genes +- **Bash Tool**: EjecuciΓ³n de comandos del sistema +- **Cron Tool**: Tareas programadas +- **Memory Tool**: Almacenamiento y recuperaciΓ³n de contexto + +### πŸ€– IA Avanzada +- **MΓΊltiples Modelos**: Claude, GPT, Gemini, Bedrock, Ollama (local) +- **Failover AutomΓ‘tico**: RotaciΓ³n automΓ‘tica si un modelo falla +- **Streaming de Herramientas**: EjecuciΓ³n de herramientas en tiempo real +- **Multi-Agente**: Agentes aislados por workspace/canal + +--- + +## Arquitectura del Sistema + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Interfaces de Usuario β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ macOS β”‚ β”‚ iOS β”‚ β”‚ Android β”‚ β”‚ CLI / Web UI β”‚ β”‚ +β”‚ β”‚ App β”‚ β”‚ App β”‚ β”‚ App β”‚ β”‚ β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ WebSocket / HTTP + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Gateway (Servidor) β”‚ +β”‚ β€’ GestiΓ³n de sesiones y enrutamiento de mensajes β”‚ +β”‚ β€’ CatΓ‘logo de modelos IA y autenticaciΓ³n β”‚ +β”‚ β€’ Trabajos programados (cron) y webhooks β”‚ +β”‚ β€’ Herramienta de navegador compartida β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Runtime de Agente (Pi Agent) β”‚ +β”‚ β€’ EjecuciΓ³n de modelos IA (Claude, GPT, etc.) β”‚ +β”‚ β€’ Streaming de herramientas en tiempo real β”‚ +β”‚ β€’ GestiΓ³n de contexto de sesiΓ³n β”‚ +β”‚ β€’ Failover automΓ‘tico de modelos β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Capa Multi-Canal β”‚ +β”‚ WhatsApp β”‚ Telegram β”‚ Signal β”‚ Discord β”‚ Slack β”‚ iMessage β”‚ +β”‚ Teams β”‚ Matrix β”‚ Zalo β”‚ BlueBubbles β”‚ LINE β”‚ Voice Call β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Servicios Externos (IA) β”‚ +β”‚ Anthropic Claude β”‚ OpenAI GPT β”‚ Google Gemini β”‚ AWS Bedrock β”‚ +β”‚ Ollama (Local) β”‚ Otros proveedores β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +πŸ“– **Profundizar**: Ver [ARCHITECTURE.md](docs/ARCHITECTURE.md) para detalles completos de arquitectura + +--- + +## Diagrama de Uso + +### Flujo de Mensaje Completo + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ 1. Usuario envΓ­a mensaje desde canal (WhatsApp, Telegram, etc.)β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ 2. Canal recibe mensaje y lo normaliza β”‚ +β”‚ β€’ Extrae texto, medios, contexto de respuesta β”‚ +β”‚ β€’ AΓ±ade metadata del canal β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ 3. VerificaciΓ³n de seguridad β”‚ +β”‚ β€’ Verifica lista de permitidos β”‚ +β”‚ β€’ Valida emparejamiento para DMs β”‚ +β”‚ β€’ Comprueba permisos de grupo β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ 4. Gateway enruta mensaje β”‚ +β”‚ β€’ Determina sesiΓ³n apropiada β”‚ +β”‚ β€’ Verifica modo de activaciΓ³n (mention/reply/always) β”‚ +β”‚ β€’ Encola o ejecuta inmediatamente β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ 5. Agente procesa mensaje β”‚ +β”‚ β€’ Carga contexto de sesiΓ³n β”‚ +β”‚ β€’ Ejecuta modelo IA con herramientas β”‚ +β”‚ β€’ Stream de llamadas y resultados de herramientas β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ 6. EjecuciΓ³n de herramientas (si es necesario) β”‚ +β”‚ β€’ Browser (automatizaciΓ³n web) β”‚ +β”‚ β€’ Bash (ejecutar comandos) β”‚ +β”‚ β€’ Canvas (workspace visual) β”‚ +β”‚ β€’ Memory (recuperar contexto) β”‚ +β”‚ β€’ Otras herramientas personalizadas β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ 7. Agente genera respuesta β”‚ +β”‚ β€’ Basada en resultados de herramientas β”‚ +β”‚ β€’ Aplica modo de thinking (low/high/always) β”‚ +β”‚ β€’ Formatea para canal destino β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ 8. Respuesta enviada de vuelta β”‚ +β”‚ β€’ Formatea para protocolo especΓ­fico del canal β”‚ +β”‚ β€’ Fragmenta mensajes largos si es necesario β”‚ +β”‚ β€’ AΓ±ade indicadores de escritura/reacciones β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ 9. Usuario recibe respuesta en su canal β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +πŸ“– **Profundizar**: Ver [Flujo de Datos](docs/ARCHITECTURE.md#data-flow) en documentaciΓ³n de arquitectura + +--- + +## InstalaciΓ³n RΓ‘pida + +### Requisitos Previos + +- **Node.js β‰₯ 22.12.0** +- **npm, pnpm o bun** +- **macOS, Linux o Windows (WSL2)** + +### InstalaciΓ³n con npm + +```bash +# Instalar globalmente +npm install -g moltbot@latest + +# Ejecutar asistente de configuraciΓ³n +moltbot onboard --install-daemon +``` + +### InstalaciΓ³n desde CΓ³digo Fuente + +```bash +# Clonar repositorio +git clone https://github.com/jeturing/Jarvis.git +cd Jarvis + +# Instalar dependencias +pnpm install + +# Construir proyecto +pnpm ui:build +pnpm build + +# Ejecutar asistente de configuraciΓ³n +pnpm moltbot onboard --install-daemon +``` + +### InstalaciΓ³n con Docker + +```bash +# Usando Docker Compose +docker-compose up -d +``` + +πŸ“– **Profundizar**: Ver [GuΓ­a de InstalaciΓ³n Completa](docs/README-ES.md#configuraciΓ³n-y-despliegue) + +--- + +## ConfiguraciΓ³n + +### Estructura de ConfiguraciΓ³n + +``` +~/.clawdbot/ +β”œβ”€β”€ config/ +β”‚ β”œβ”€β”€ .moltbot.yaml # ConfiguraciΓ³n principal +β”‚ β”œβ”€β”€ models.json # Perfiles de modelos IA +β”‚ └── skills/ # Configuraciones de skills +β”œβ”€β”€ credentials/ +β”‚ β”œβ”€β”€ anthropic.json # Tokens OAuth +β”‚ β”œβ”€β”€ openai.json +β”‚ └── channels/ # Credenciales de canales +β”œβ”€β”€ sessions/ +β”‚ β”œβ”€β”€ main/ # Datos de sesiΓ³n principal +β”‚ └── groups/ # Sesiones de grupos +└── logs/ + β”œβ”€β”€ gateway.log # Logs del gateway + └── agent.log # Logs del agente +``` + +### Archivo de ConfiguraciΓ³n Principal + +Edita `~/.clawdbot/config/.moltbot.yaml`: + +```yaml +# ======================================== +# ConfiguraciΓ³n del Gateway +# ======================================== +gateway: + mode: local # 'local' o 'remote' + port: 18789 # Puerto del servidor + bind: loopback # 'loopback' o 'all' + verbose: true # Logging detallado + +# ======================================== +# ConfiguraciΓ³n de Agentes +# ======================================== +agents: + default: + model: claude-4.5-sonnet # Modelo IA por defecto + thinking: high # Nivel de thinking (low/high/always) + temperature: 0.7 # Temperatura del modelo + max_tokens: 8192 # Tokens mΓ‘ximos + +# ======================================== +# ConfiguraciΓ³n de Canales +# ======================================== +channels: + # WhatsApp + whatsapp: + enabled: true + pairing: code # MΓ©todo de emparejamiento + allowlist: + - "+1234567890" # NΓΊmeros permitidos + + # Telegram + telegram: + enabled: true + bot_token: "${TELEGRAM_BOT_TOKEN}" + + # Discord + discord: + enabled: true + bot_token: "${DISCORD_BOT_TOKEN}" + + # Signal + signal: + enabled: true + phone: "+1234567890" + + # Slack + slack: + enabled: true + bot_token: "${SLACK_BOT_TOKEN}" + +# ======================================== +# ConfiguraciΓ³n de Herramientas +# ======================================== +tools: + browser: + enabled: true + headless: true # Navegador sin interfaz + timeout: 30000 # Timeout en ms + + canvas: + enabled: true + port: 8080 # Puerto Canvas + + bash: + enabled: true + timeout: 60000 # Timeout comandos + + memory: + enabled: true + max_size: 1000 # Entradas mΓ‘ximas + +# ======================================== +# ConfiguraciΓ³n de Sandbox (Opcional) +# ======================================== +sandbox: + enabled: false + docker_image: "jarvis/sandbox" + +# ======================================== +# ConfiguraciΓ³n de Plugins +# ======================================== +plugins: + - name: matrix + enabled: true + config: + homeserver: "https://matrix.org" + + - name: voice-call + enabled: false + config: + provider: "twilio" + +# ======================================== +# ConfiguraciΓ³n de Skills +# ======================================== +skills: + - workspace1 + - workspace2 +``` + +### Variables de Entorno + +Crea un archivo `.env` en la raΓ­z del proyecto: + +```bash +# ======================================== +# Tokens de API de IA +# ======================================== +ANTHROPIC_API_KEY=sk-ant-api03-... +OPENAI_API_KEY=sk-... + +# ======================================== +# Tokens de Canales +# ======================================== +TELEGRAM_BOT_TOKEN=123456:ABC-DEF... +DISCORD_BOT_TOKEN=MTk4... +SLACK_BOT_TOKEN=xoxb-... + +# ======================================== +# ConfiguraciΓ³n del Gateway +# ======================================== +CLAWDBOT_GATEWAY_PORT=18789 +CLAWDBOT_GATEWAY_BIND=loopback + +# ======================================== +# ConfiguraciΓ³n de Modo +# ======================================== +CLAWDBOT_PROFILE=production # 'production' o 'dev' +CLAWDBOT_SKIP_CHANNELS=0 + +# ======================================== +# ConfiguraciΓ³n de DepuraciΓ³n +# ======================================== +CLAWDBOT_DEBUG=0 +CLAWDBOT_VERBOSE=0 +``` + +### Diagrama de ConfiguraciΓ³n + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Proceso de ConfiguraciΓ³n β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + +1. INSTALACIΓ“N + β”‚ + β”œβ”€β†’ Instalar paquete npm/pnpm + β”‚ + └─→ Ejecutar: moltbot onboard --install-daemon + +2. CONFIGURACIΓ“N INTERACTIVA + β”‚ + β”œβ”€β†’ Seleccionar modelos IA (Claude, GPT, etc.) + β”‚ └─→ AΓ±adir tokens API o OAuth + β”‚ + β”œβ”€β†’ Configurar canales + β”‚ β”œβ”€β†’ WhatsApp (emparejamiento QR) + β”‚ β”œβ”€β†’ Telegram (bot token) + β”‚ β”œβ”€β†’ Discord (bot token) + β”‚ β”œβ”€β†’ Signal (phone number) + β”‚ └─→ Otros canales + β”‚ + β”œβ”€β†’ Configurar herramientas + β”‚ β”œβ”€β†’ Browser (Playwright) + β”‚ β”œβ”€β†’ Canvas (A2UI) + β”‚ β”œβ”€β†’ Bash (comandos) + β”‚ └─→ Memory (almacenamiento) + β”‚ + └─→ Configurar seguridad + β”œβ”€β†’ Listas de permitidos + β”œβ”€β†’ PolΓ­ticas de emparejamiento DM + └─→ Permisos de grupo + +3. VERIFICACIΓ“N + β”‚ + β”œβ”€β†’ Ejecutar: moltbot doctor + β”‚ └─→ Verifica configuraciΓ³n y detecta problemas + β”‚ + └─→ Ejecutar: moltbot channels status + └─→ Verifica estado de canales + +4. INICIO DEL GATEWAY + β”‚ + β”œβ”€β†’ Modo Daemon: moltbot daemon start + β”‚ └─→ Gateway se ejecuta en segundo plano + β”‚ + └─→ Modo Manual: moltbot gateway --port 18789 + └─→ Gateway se ejecuta en primer plano + +5. EMPAREJAMIENTO DE CANALES + β”‚ + β”œβ”€β†’ WhatsApp: Escanear cΓ³digo QR + β”‚ + β”œβ”€β†’ Otros canales: Aprobar cΓ³digos de emparejamiento + β”‚ └─→ Ejecutar: moltbot pairing approve + β”‚ + └─→ Verificar conexiones + └─→ Ejecutar: moltbot channels status --probe + +6. Β‘LISTO! + └─→ Enviar mensaje de prueba + └─→ Ejecutar: moltbot agent --message "Hola Jarvis" +``` + +πŸ“– **Profundizar**: Ver [GuΓ­a de ConfiguraciΓ³n Completa](docs/README-ES.md#configuraciΓ³n-y-despliegue) + +--- + +## Uso BΓ‘sico + +### Iniciar el Gateway + +```bash +# Modo daemon (recomendado) +moltbot daemon install +moltbot daemon start +moltbot daemon status + +# Modo manual (desarrollo) +moltbot gateway --port 18789 --verbose +``` + +### Enviar Mensajes + +```bash +# Enviar mensaje a un contacto +moltbot message send --to +1234567890 --message "Hola desde Jarvis" + +# Enviar mensaje a un grupo +moltbot message send --to group_id --message "Hola grupo" +``` + +### Interactuar con el Agente + +```bash +# Modo interactivo +moltbot agent --message "ΒΏCuΓ‘l es el clima hoy?" + +# Con modo de thinking alto +moltbot agent --message "Analiza este documento" --thinking high + +# Ejecutar comando y devolver resultado al canal +moltbot agent --message "Lista archivos en /home" --reply-back telegram +``` + +### Gestionar Canales + +```bash +# Ver estado de todos los canales +moltbot channels status + +# Ver estado con verificaciΓ³n de conexiΓ³n +moltbot channels status --probe + +# Ver estado de un canal especΓ­fico +moltbot channels status whatsapp + +# Reiniciar un canal +moltbot channels restart telegram +``` + +### Gestionar Emparejamiento + +```bash +# Listar solicitudes de emparejamiento pendientes +moltbot pairing list + +# Aprobar un emparejamiento +moltbot pairing approve telegram ABC123 + +# Rechazar un emparejamiento +moltbot pairing reject whatsapp XYZ789 + +# Ver lista de permitidos +moltbot pairing allowlist +``` + +### Gestionar Modelos + +```bash +# Listar modelos disponibles +moltbot models list + +# Ver configuraciΓ³n de modelos +moltbot models config + +# Probar un modelo +moltbot models test claude-4.5-sonnet + +# Cambiar modelo por defecto +moltbot config set agents.default.model claude-4.5-sonnet +``` + +### Gestionar Skills + +```bash +# Listar skills disponibles +moltbot skills list + +# Instalar un skill +moltbot skills install workspace1 + +# Actualizar skills +moltbot skills update + +# Ver configuraciΓ³n de skills +moltbot skills config +``` + +### DiagnΓ³stico + +```bash +# Ejecutar diagnΓ³stico completo +moltbot doctor + +# Ver logs del gateway +moltbot logs gateway + +# Ver logs del agente +moltbot logs agent + +# Ver logs de un canal +moltbot logs channel telegram +``` + +πŸ“– **Profundizar**: Ver [Comandos CLI](docs/README-ES.md#cli) + +--- + +## Canales Soportados + +### Canales Integrados + +| Canal | Biblioteca | Estado | DocumentaciΓ³n | +|-------|-----------|--------|---------------| +| **WhatsApp** | @whiskeysockets/baileys | βœ… Estable | [Ver docs](docs/channels/) | +| **Telegram** | grammy | βœ… Estable | [Ver docs](docs/channels/) | +| **Signal** | signal-cli | βœ… Estable | [Ver docs](docs/channels/) | +| **iMessage** | imsg | βœ… Estable | [Ver docs](docs/channels/) | +| **Discord** | discord.js | βœ… Estable | [Ver docs](docs/channels/) | +| **Slack** | @slack/bolt | βœ… Estable | [Ver docs](docs/channels/) | +| **Google Chat** | Chat API | βœ… Estable | [Ver docs](docs/channels/) | + +### Canales de ExtensiΓ³n + +| Canal | UbicaciΓ³n | Estado | DocumentaciΓ³n | +|-------|-----------|--------|---------------| +| **BlueBubbles** | extensions/bluebubbles | βœ… Estable | [Ver docs](docs/channels/) | +| **Microsoft Teams** | extensions/msteams | βœ… Estable | [Ver docs](docs/channels/) | +| **Matrix** | extensions/matrix | βœ… Estable | [Ver docs](docs/channels/) | +| **Zalo** | extensions/zalo | βœ… Estable | [Ver docs](docs/channels/) | +| **Zalo Personal** | extensions/zalouser | βœ… Estable | [Ver docs](docs/channels/) | +| **Twitch** | extensions/twitch | βœ… Estable | [Ver docs](docs/channels/) | +| **Mattermost** | extensions/mattermost | βœ… Estable | [Ver docs](docs/channels/) | +| **LINE** | extensions/line | βœ… Estable | [Ver docs](docs/channels/) | +| **Voice Call** | extensions/voice-call | πŸ”Ά Beta | [Ver docs](docs/channels/) | + +### CaracterΓ­sticas de Canal + +- βœ… **Emparejamiento DM**: Lista de permitidos basada en cΓ³digo +- βœ… **Enrutamiento de grupo**: Control de menciones +- βœ… **Etiquetas de respuesta**: Respuestas basadas en hilos +- βœ… **FragmentaciΓ³n de mensajes**: LΓ­mites especΓ­ficos por canal +- βœ… **Reacciones**: Reconocimientos +- βœ… **Indicadores de escritura**: Estado en tiempo real +- βœ… **RedacciΓ³n de medios**: Capacidades de privacidad + +πŸ“– **Profundizar**: Ver [DocumentaciΓ³n de Canales](docs/README-ES.md#canales-de-mensajerΓ­a) + +--- + +## DocumentaciΓ³n Completa + +### πŸ“š DocumentaciΓ³n Principal + +- **[README EspaΓ±ol (Completo)](docs/README-ES.md)** - DocumentaciΓ³n completa en espaΓ±ol +- **[Arquitectura](docs/ARCHITECTURE.md)** - Arquitectura tΓ©cnica detallada del sistema +- **[Componentes](docs/COMPONENTS.md)** - DescripciΓ³n de componentes individuales (prΓ³ximamente) +- **[Desarrollo](docs/DEVELOPMENT.md)** - GuΓ­a para desarrolladores (prΓ³ximamente) +- **[Plugin Development](docs/PLUGIN-DEVELOPMENT.md)** - Crear plugins personalizados (prΓ³ximamente) +- **[API Reference](docs/API-REFERENCE.md)** - Referencia completa de API (prΓ³ximamente) +- **[Deployment](docs/DEPLOYMENT.md)** - GuΓ­as de despliegue (prΓ³ximamente) + +### πŸ”§ ConfiguraciΓ³n y AdministraciΓ³n + +- **Gateway**: Ver [docs/gateway/](docs/gateway/) +- **Canales**: Ver [docs/channels/](docs/channels/) +- **Seguridad**: Ver [docs/security/](docs/security/) +- **CLI**: Ver [docs/cli/](docs/cli/) + +### πŸ’‘ Conceptos y GuΓ­as + +- **Modelos IA**: Ver [docs/concepts/](docs/concepts/) +- **Sesiones**: Ver [docs/concepts/](docs/concepts/) +- **Herramientas**: Ver [docs/tools/](docs/tools/) +- **Plugins**: Ver [docs/plugins/](docs/plugins/) + +### πŸš€ Inicio RΓ‘pido + +- **Getting Started**: Ver [docs/start/](docs/start/) +- **InstalaciΓ³n**: Ver [docs/install/](docs/install/) +- **Plataformas**: Ver [docs/platforms/](docs/platforms/) + +### πŸ“– Referencia + +- **Testing**: Ver [docs/testing.md](docs/testing.md) +- **Environment**: Ver [docs/environment.md](docs/environment.md) +- **Debugging**: Ver [docs/debugging.md](docs/debugging.md) + +--- + +## Desarrollo + +### ConfiguraciΓ³n del Entorno de Desarrollo + +```bash +# 1. Clonar repositorio +git clone https://github.com/jeturing/Jarvis.git +cd Jarvis + +# 2. Instalar dependencias +pnpm install + +# 3. Construir UI +pnpm ui:build + +# 4. Construir proyecto +pnpm build + +# 5. Ejecutar en modo desarrollo +pnpm gateway:watch # Auto-recarga en cambios +``` + +### Scripts de Desarrollo + +```bash +# Desarrollo +pnpm dev # Ejecutar CLI en modo dev +pnpm gateway:watch # Gateway con auto-recarga +pnpm gateway:dev # Gateway dev sin canales +pnpm tui:dev # UI de terminal dev + +# Build +pnpm build # Compilar TypeScript +pnpm ui:build # Construir UI web +pnpm canvas:a2ui:bundle # Empaquetar Canvas A2UI + +# Testing +pnpm test # Ejecutar todos los tests +pnpm test:watch # Tests en modo watch +pnpm test:coverage # Tests con cobertura +pnpm test:e2e # Tests end-to-end + +# Linting & Formatting +pnpm lint # Lint TypeScript +pnpm lint:fix # Fix problemas de lint +pnpm format # Verificar formato +pnpm format:fix # Fix formato + +# Plataformas +pnpm ios:build # Construir app iOS +pnpm android:run # Ejecutar app Android +pnpm mac:package # Empaquetar app macOS +``` + +### Estructura del Proyecto + +``` +/ +β”œβ”€β”€ src/ # CΓ³digo fuente TypeScript +β”œβ”€β”€ extensions/ # Plugins de canal y extensiones +β”œβ”€β”€ apps/ # Aplicaciones nativas (macOS, iOS, Android) +β”œβ”€β”€ docs/ # DocumentaciΓ³n +β”œβ”€β”€ skills/ # Paquetes de skills de workspace +β”œβ”€β”€ scripts/ # Scripts de utilidad +β”œβ”€β”€ test/ # Fixtures de test y helpers +└── ui/ # UI web (Control UI) +``` + +πŸ“– **Profundizar**: Ver [Estructura Completa](docs/README-ES.md#estructura-de-directorios) + +--- + +## Contribuir + +Β‘Las contribuciones son bienvenidas! Por favor lee [CONTRIBUTING.md](CONTRIBUTING.md) para detalles sobre nuestro cΓ³digo de conducta y el proceso para enviar pull requests. + +### CΓ³mo Contribuir + +1. **Fork el repositorio** +2. **Crea una rama** para tu feature (`git checkout -b feature/AmazingFeature`) +3. **Commit tus cambios** (`git commit -m 'Add some AmazingFeature'`) +4. **Push a la rama** (`git push origin feature/AmazingFeature`) +5. **Abre un Pull Request** + +### Áreas de ContribuciΓ³n + +- πŸ› **Bug fixes**: Reporta o arregla bugs +- ✨ **Nuevas caracterΓ­sticas**: PropΓ³n o implementa nuevas features +- πŸ“ **DocumentaciΓ³n**: Mejora la documentaciΓ³n +- πŸ”Œ **Plugins**: Crea nuevos plugins de canal o herramientas +- πŸ§ͺ **Tests**: AΓ±ade o mejora tests +- 🌐 **Traducciones**: Traduce documentaciΓ³n a otros idiomas + +--- + +## Licencia + +Este proyecto estΓ‘ licenciado bajo la Licencia MIT - ver el archivo [LICENSE](LICENSE) para detalles. + +--- + +## Soporte + +ΒΏNecesitas ayuda? AquΓ­ tienes algunas opciones: + +- πŸ“– **DocumentaciΓ³n**: Revisa la [documentaciΓ³n completa](docs/README-ES.md) +- πŸ› **Issues**: Reporta bugs en [GitHub Issues](https://github.com/jeturing/Jarvis/issues) +- πŸ’¬ **Discusiones**: Únete a [GitHub Discussions](https://github.com/jeturing/Jarvis/discussions) +- πŸ“§ **Email**: Contacta al equipo de desarrollo + +--- + +## Agradecimientos + +Gracias a todos los contribuidores que han ayudado a hacer este proyecto posible. + +--- + +## Seguridad + +Para reportar vulnerabilidades de seguridad, por favor lee [SECURITY.md](SECURITY.md). + +--- + +

+ Hecho con ❀️ por la comunidad +

+ +

+ Si encuentras útil este proyecto, considera darle una ⭐ en GitHub +

diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 000000000..236640a9b --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,814 @@ +# Moltbot Architecture Documentation + +## Table of Contents +1. [Overview](#overview) +2. [High-Level Architecture](#high-level-architecture) +3. [Core Components](#core-components) +4. [Data Flow](#data-flow) +5. [Message Routing](#message-routing) +6. [Agent Execution Model](#agent-execution-model) +7. [Plugin Architecture](#plugin-architecture) +8. [Security Model](#security-model) +9. [Storage & Persistence](#storage--persistence) +10. [Network Architecture](#network-architecture) + +--- + +## Overview + +Moltbot is designed as a **local-first, extensible AI assistant platform** with a microkernel-inspired architecture. The system consists of a central Gateway (control plane) and modular components (channels, tools, plugins) that communicate through well-defined interfaces. + +### Design Principles + +1. **Local-First**: Everything runs on user's devices; no central server dependency +2. **Privacy-Focused**: User data never leaves their control +3. **Extensible**: Plugin system for adding channels, tools, and functionality +4. **Multi-Platform**: Works on macOS, iOS, Android, Linux, Windows (WSL2) +5. **Resilient**: Graceful degradation; continues working when components fail +6. **Developer-Friendly**: Clear APIs, TypeScript types, comprehensive testing + +--- + +## High-Level Architecture + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ User Interfaces β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ macOS β”‚ β”‚ iOS β”‚ β”‚ Android β”‚ β”‚ CLI / Web UI β”‚ β”‚ +β”‚ β”‚ App β”‚ β”‚ App β”‚ β”‚ App β”‚ β”‚ β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + ↓ WebSocket / HTTP +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Gateway Server β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”‚ +β”‚ β”‚ WebSocket Control Plane β”‚β”‚ +β”‚ β”‚ β€’ Session Management β”‚β”‚ +β”‚ β”‚ β€’ Message Routing β”‚β”‚ +β”‚ β”‚ β€’ Model Catalog β”‚β”‚ +β”‚ β”‚ β€’ Discovery Service (mDNS) β”‚β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”‚ +β”‚ β”‚ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ +β”‚ β–Ό β–Ό β–Ό β–Ό β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Chat β”‚ β”‚ Model β”‚ β”‚ Browser β”‚ β”‚ Cron Scheduler β”‚ β”‚ +β”‚ β”‚Registryβ”‚ β”‚ Catalog β”‚ β”‚ Tool β”‚ β”‚ β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Agent Runtime Layer β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”‚ +β”‚ β”‚ Pi Agent (RPC Mode) β”‚β”‚ +β”‚ β”‚ β€’ Tool Streaming β”‚β”‚ +β”‚ β”‚ β€’ Block Streaming β”‚β”‚ +β”‚ β”‚ β€’ Model Failover β”‚β”‚ +β”‚ β”‚ β€’ Auth Profile Rotation β”‚β”‚ +β”‚ β”‚ β€’ Session Context Management β”‚β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β”‚ +β”‚ β”‚ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ +β”‚ β–Ό β–Ό β–Ό β–Ό β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Tool β”‚ β”‚ Session β”‚ β”‚ Memory β”‚ β”‚ Sandbox β”‚ β”‚ +β”‚ β”‚Registryβ”‚ β”‚ Manager β”‚ β”‚ Store β”‚ β”‚ (Optional) β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Channel Layer (Multi-Protocol) β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ WhatsApp β”‚ Telegram β”‚ Signal β”‚ Discord β”‚ Slack β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ iMessage β”‚ Teams β”‚ Matrix β”‚ Zalo β”‚ BlueBubbles β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Twitch β”‚Mattermostβ”‚ LINE β”‚ Nostr β”‚ Voice Call β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ External Services β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Anthropicβ”‚ OpenAI β”‚ AWS β”‚ Ollama β”‚ Google β”‚ β”‚ +β”‚ β”‚ Claude β”‚ GPT β”‚ Bedrock β”‚ (Local) β”‚ Gemini β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +--- + +## Core Components + +### 1. Gateway Server + +**Responsibility**: Central control plane for all communication and orchestration. + +**Key Modules**: +- `server.ts` - Main WebSocket server +- `chat-registry.ts` - Active chat session registry +- `model-catalog.ts` - Available AI models catalog +- `browser-tool.ts` - Shared browser automation tool +- `discovery.ts` - mDNS service discovery + +**APIs**: +```typescript +interface GatewayServer { + start(): Promise; + stop(): Promise; + registerChat(chat: ChatSession): void; + unregisterChat(chatId: string): void; + routeMessage(message: InboundMessage): Promise; + getModelCatalog(): ModelCatalog; + getBrowserTool(): BrowserTool; +} +``` + +**Communication**: +- WebSocket (ws://) for real-time bidirectional communication +- HTTP REST API for management operations +- mDNS for local network discovery + +### 2. Agent Runtime + +**Responsibility**: Execute AI models and manage agent sessions. + +**Key Modules**: +- `pi-embedded-runner.ts` - Pi Agent executor +- `session-manager.ts` - Session lifecycle management +- `tool-registry.ts` - Available tools catalog +- `model-auth.ts` - Model authentication and failover + +**Execution Flow**: +```typescript +interface AgentRuntime { + createSession(config: SessionConfig): AgentSession; + executeMessage(session: AgentSession, message: string): AsyncGenerator; + executeTools(session: AgentSession, tools: ToolCall[]): Promise; + streamResponse(session: AgentSession): AsyncGenerator; +} +``` + +**Session Management**: +- **Main Session**: Primary agent for user interactions +- **Group Sessions**: Isolated agents for group chats +- **Sub-Sessions**: Spawned agents for specific tasks +- **Queue Modes**: Serial (one at a time) vs Concurrent (parallel) + +### 3. Channel Layer + +**Responsibility**: Handle messaging protocol specifics and normalize messages. + +**Channel Interface**: +```typescript +interface Channel { + name: string; + type: ChannelType; + + // Lifecycle + init(config: ChannelConfig): Promise; + start(): Promise; + stop(): Promise; + + // Messaging + send(message: OutboundMessage): Promise; + receive(handler: MessageHandler): void; + + // Status + getStatus(): ChannelStatus; + getConnections(): Connection[]; +} +``` + +**Message Normalization**: +```typescript +interface NormalizedMessage { + id: string; + channel: string; + from: string; + to: string; + text: string; + media?: MediaAttachment[]; + replyTo?: string; + timestamp: number; + metadata: Record; +} +``` + +**Channel Types**: +- **Built-in**: WhatsApp, Telegram, Signal, Discord, Slack, iMessage +- **Extensions**: Teams, Matrix, Zalo, BlueBubbles, Twitch, etc. + +### 4. Tool System + +**Responsibility**: Provide capabilities to agents beyond text generation. + +**Tool Interface**: +```typescript +interface Tool { + name: string; + description: string; + schema: JSONSchema; + + execute(params: unknown, context: ToolContext): Promise; +} +``` + +**Built-in Tools**: +- **Browser Tool**: Web automation, screenshots, form filling +- **Canvas Tool**: Visual workspace with A2UI +- **Image Tool**: Image analysis and generation +- **Message Tool**: Send messages across channels +- **Session Tool**: Spawn sub-agents +- **Bash Tool**: Execute shell commands +- **Web Tool**: Fetch URLs, web search, readability +- **Memory Tool**: Store and retrieve context +- **Cron Tool**: Schedule tasks + +**Tool Execution Pipeline**: +``` +User Message β†’ Agent β†’ Tool Call β†’ Tool Execute β†’ Tool Result β†’ Agent β†’ Response +``` + +### 5. Plugin System + +**Responsibility**: Enable extensibility through modular plugins. + +**Plugin Types**: +1. **Channel Plugins**: Add new messaging integrations +2. **Tool Plugins**: Add custom agent tools +3. **Auth Plugins**: Add OAuth handlers +4. **Memory Plugins**: Add storage backends +5. **Hook Plugins**: Add global event handlers + +**Plugin Lifecycle**: +```typescript +interface Plugin { + manifest: PluginManifest; + + // Lifecycle + init(services: PluginServices): Promise; + start(): Promise; + stop(): Promise; + + // Hooks + hooks?: Record; +} +``` + +**Plugin Discovery**: +- Auto-detect from `extensions/` directory +- Auto-detect from `node_modules/@moltbot/` packages +- Validate manifest and config schema +- Load and initialize plugins + +--- + +## Data Flow + +### Inbound Message Flow + +``` +External Channel (WhatsApp, Telegram, etc.) + ↓ + Channel Handler + ↓ + Message Normalization + ↓ + Allowlist Check + ↓ + Gateway Router + ↓ + Session Selection + ↓ + Agent Execution + ↓ + Tool Streaming + ↓ + Response Generation + ↓ + Channel Formatting + ↓ + Outbound Message + ↓ +External Channel +``` + +### Detailed Flow Steps + +1. **Channel Receives Message** + - Raw message from external protocol + - Protocol-specific handling (e.g., Baileys for WhatsApp) + +2. **Message Normalization** + - Convert to `NormalizedMessage` format + - Extract text, media, reply context + - Add metadata + +3. **Allowlist Check** + - Verify sender is allowed + - Check pairing status for DMs + - Validate group membership + +4. **Gateway Routing** + - Determine target session + - Check activation mode (mention, reply, always-on) + - Queue or execute immediately + +5. **Agent Execution** + - Load session context + - Execute model with tools + - Stream tool calls and responses + +6. **Tool Execution** + - Execute tools as needed + - Stream tool results back to agent + - Handle tool errors gracefully + +7. **Response Generation** + - Agent generates response + - Apply thinking mode (low/high/always) + - Format for target channel + +8. **Channel Formatting** + - Convert to channel-specific format + - Chunk long messages if needed + - Add reactions/typing indicators + +9. **Outbound Message** + - Send via channel handler + - Track delivery status + - Handle errors and retries + +--- + +## Message Routing + +### Routing Rules + +```typescript +interface RoutingConfig { + // Main session routing + mainSession: { + activationMode: 'always' | 'mention' | 'reply' | 'dm-only'; + replyBack: boolean; + allowedChannels: string[]; + }; + + // Group session routing + groupSessions: { + enabled: boolean; + isolateByGroup: boolean; + activationMode: 'mention' | 'reply'; + }; + + // Cross-channel routing + crossChannel: { + enabled: boolean; + routes: ChannelRoute[]; + }; +} +``` + +### Activation Modes + +1. **Always-On**: Every message triggers agent +2. **Mention**: Only messages mentioning bot trigger agent +3. **Reply**: Only replies to bot messages trigger agent +4. **DM-Only**: Only direct messages trigger agent + +### Session Isolation + +- **Main Session**: Primary agent for user +- **Group Session**: Separate agent per group chat +- **Workspace Session**: Separate agent per workspace + +--- + +## Agent Execution Model + +### Session Context + +```typescript +interface SessionContext { + sessionId: string; + chatId: string; + channel: string; + + // Context window + messages: Message[]; + maxTokens: number; + + // Configuration + model: string; + temperature: number; + thinkingMode: 'low' | 'high' | 'always'; + + // Tools + availableTools: Tool[]; + toolResults: ToolResult[]; + + // Memory + memory: MemoryStore; + skills: Skill[]; +} +``` + +### Execution Pipeline + +``` +Message β†’ Load Context β†’ Execute Model β†’ Stream Tools β†’ Generate Response β†’ Save Context +``` + +### Tool Streaming + +```typescript +interface ToolStreamEvent { + type: 'tool_call' | 'tool_result' | 'text_chunk' | 'thinking'; + data: unknown; +} + +async function* streamAgentExecution( + session: SessionContext, + message: string +): AsyncGenerator { + // Stream tool calls and results in real-time + yield* piAgent.execute(session, message); +} +``` + +### Model Failover + +```typescript +interface ModelFailoverConfig { + primary: ModelConfig; + fallbacks: ModelConfig[]; + retryAttempts: number; + retryDelay: number; +} + +async function executeWithFailover( + config: ModelFailoverConfig, + request: ModelRequest +): Promise { + // Try primary model + try { + return await execute(config.primary, request); + } catch (error) { + // Try fallback models + for (const fallback of config.fallbacks) { + try { + return await execute(fallback, request); + } catch (fallbackError) { + continue; + } + } + throw error; + } +} +``` + +--- + +## Plugin Architecture + +### Plugin System Design + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Plugin Discovery β”‚ +β”‚ β€’ extensions/ β”‚ +β”‚ β€’ node_modules/@moltbot/ β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Plugin Loader β”‚ +β”‚ β€’ Validate manifest β”‚ +β”‚ β€’ Load config schema β”‚ +β”‚ β€’ Initialize plugin β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Plugin Runtime β”‚ +β”‚ β€’ Register hooks β”‚ +β”‚ β€’ Inject services β”‚ +β”‚ β€’ Execute plugin logic β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +### Plugin Manifest + +```json +{ + "name": "my-plugin", + "version": "1.0.0", + "type": "channel", + "exports": { + ".": "./dist/index.js", + "./config-schema": "./dist/config-schema.js" + }, + "hooks": ["channel", "message:received", "message:sent"], + "permissions": ["network", "fs", "env"], + "dependencies": { + "some-lib": "^1.0.0" + } +} +``` + +### Plugin Services + +```typescript +interface PluginServices { + gateway: GatewayClient; + config: ConfigProvider; + logger: Logger; + http: HttpClient; + storage: StorageProvider; +} +``` + +### Plugin Hooks + +```typescript +interface PluginHooks { + 'plugin:init': (plugin: Plugin) => Promise; + 'plugin:start': (plugin: Plugin) => Promise; + 'plugin:stop': (plugin: Plugin) => Promise; + + 'message:received': (message: NormalizedMessage) => Promise; + 'message:sent': (message: NormalizedMessage) => Promise; + + 'agent:before': (session: SessionContext) => Promise; + 'agent:after': (session: SessionContext, response: string) => Promise; + + 'tool:before': (tool: Tool, params: unknown) => Promise; + 'tool:after': (tool: Tool, result: ToolResult) => Promise; +} +``` + +--- + +## Security Model + +### Authentication + +1. **Pairing System** + - Code-based pairing for DMs + - One-time pairing codes + - Allowlist management + +2. **Channel Authentication** + - OAuth tokens (Discord, Slack, etc.) + - Bot tokens (Telegram) + - Session persistence (WhatsApp, Signal) + +3. **Model Authentication** + - API keys (Anthropic, OpenAI) + - OAuth (Google, AWS) + - Profile rotation on failure + +### Authorization + +1. **Allowlists** + - Per-channel allowlists + - Phone numbers for WhatsApp + - User IDs for Telegram + - Handle-based for Discord + +2. **Group Policies** + - Mention-only mode + - Reply-only mode + - Admin-only commands + +3. **Tool Permissions** + - Per-tool enable/disable + - Execution timeouts + - Resource limits + +### Privacy + +1. **Local-First** + - All data stored locally + - No external server dependency + - User controls all data + +2. **Session Isolation** + - Separate sessions per chat + - No cross-session data leaks + - Clear session boundaries + +3. **Media Handling** + - Temporary storage with lifecycle + - Automatic cleanup + - Optional media redaction + +--- + +## Storage & Persistence + +### File System Layout + +``` +~/.clawdbot/ +β”œβ”€β”€ config/ +β”‚ β”œβ”€β”€ .moltbot.yaml # Main config +β”‚ β”œβ”€β”€ models.json # Model profiles +β”‚ └── skills/ # Skill configs +β”œβ”€β”€ credentials/ +β”‚ β”œβ”€β”€ anthropic.json # OAuth tokens +β”‚ β”œβ”€β”€ openai.json +β”‚ └── channels/ # Channel credentials +β”œβ”€β”€ sessions/ +β”‚ β”œβ”€β”€ main/ # Main session data +β”‚ β”œβ”€β”€ groups/ # Group sessions +β”‚ └── agents/ # Agent-specific data +β”œβ”€β”€ media/ +β”‚ β”œβ”€β”€ audio/ # Audio files +β”‚ β”œβ”€β”€ images/ # Image files +β”‚ └── videos/ # Video files +β”œβ”€β”€ memory/ +β”‚ β”œβ”€β”€ vectors/ # Vector embeddings +β”‚ └── cache/ # Cached data +└── logs/ + β”œβ”€β”€ gateway.log # Gateway logs + β”œβ”€β”€ agent.log # Agent logs + └── channels/ # Per-channel logs +``` + +### Session Storage + +```typescript +interface SessionStore { + // Session CRUD + create(session: SessionContext): Promise; + read(sessionId: string): Promise; + update(session: SessionContext): Promise; + delete(sessionId: string): Promise; + + // Message history + addMessage(sessionId: string, message: Message): Promise; + getMessages(sessionId: string, limit: number): Promise; + + // Context management + getContext(sessionId: string): Promise; + saveContext(sessionId: string, context: SessionContext): Promise; +} +``` + +### Memory Store + +```typescript +interface MemoryStore { + // Vector storage + addEmbedding(key: string, embedding: number[]): Promise; + searchEmbeddings(query: number[], k: number): Promise; + + // Key-value storage + set(key: string, value: unknown): Promise; + get(key: string): Promise; + delete(key: string): Promise; + + // Context retrieval + recall(query: string): Promise; +} +``` + +--- + +## Network Architecture + +### Local Mode + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ User Device β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Gateway Server β”‚ β”‚ +β”‚ β”‚ (localhost) β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ ↓ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Agent Runtime β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ ↓ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Channels β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ + External Services + (Anthropic, OpenAI) +``` + +### Remote Gateway Mode + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Client Device β”‚ β”‚ Remote Server β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ WS β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Gateway Client │──┼────────┼──│ Gateway Server β”‚ β”‚ +β”‚ β”‚ (Control UI) β”‚ β”‚ β”‚ β”‚ (Headless) β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ ↓ β”‚ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ + β”‚ β”‚ Agent Runtime β”‚ β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ + β”‚ ↓ β”‚ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ + β”‚ β”‚ Channels β”‚ β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ + External Services +``` + +### Service Discovery + +```typescript +interface DiscoveryService { + // mDNS advertisement + advertise(service: ServiceInfo): Promise; + stopAdvertise(): Promise; + + // Discovery + discover(serviceType: string): Promise; + watch(serviceType: string, handler: ServiceHandler): void; +} +``` + +--- + +## Scalability Considerations + +### Vertical Scaling +- Single-user design (no multi-tenancy) +- Resource limits per tool +- Session cleanup policies +- Media file size limits + +### Horizontal Scaling +- Not applicable (personal assistant) +- Remote Gateway for headless servers +- Multiple client devices connecting to single gateway + +### Performance Optimizations +- Message chunking for large responses +- Lazy loading of plugins +- Caching of model responses +- Connection pooling for channels +- Parallel tool execution (where safe) + +--- + +## Reliability & Fault Tolerance + +### Error Handling +- Graceful degradation when components fail +- Model failover on API errors +- Channel reconnection on disconnect +- Tool timeout handling + +### Monitoring +- Gateway status endpoint +- Channel connection status +- Agent execution metrics +- Tool execution tracing + +### Logging +- Structured logging with tslog +- Per-component log levels +- Configurable log output (file, console) +- Log rotation and retention + +--- + +## Future Architecture Considerations + +### Planned Enhancements +- Distributed tracing +- Performance profiling +- Advanced memory systems (RAG, embeddings) +- Multi-agent coordination +- Enhanced sandbox isolation + +### Extensibility Points +- Custom model providers +- Custom channel protocols +- Custom tool implementations +- Custom memory backends +- Custom authentication providers + +--- + +**End of Architecture Documentation** diff --git a/docs/COMPONENTS.md b/docs/COMPONENTS.md new file mode 100644 index 000000000..98192156d --- /dev/null +++ b/docs/COMPONENTS.md @@ -0,0 +1,883 @@ +# Components Documentation + +## Table of Contents +1. [Overview](#overview) +2. [Gateway Components](#gateway-components) +3. [Agent Runtime Components](#agent-runtime-components) +4. [Channel Components](#channel-components) +5. [Tool Components](#tool-components) +6. [Plugin System Components](#plugin-system-components) +7. [Configuration Components](#configuration-components) +8. [Storage Components](#storage-components) +9. [Utility Components](#utility-components) + +--- + +## Overview + +This document provides detailed information about each component in the Jarvis system. Components are organized by layer and functionality. + +--- + +## Gateway Components + +### Server (`src/gateway/server.ts`) + +**Purpose**: Main WebSocket server that handles all client connections and orchestration. + +**Responsibilities**: +- Accept WebSocket connections from clients +- Route messages to appropriate handlers +- Manage active chat sessions +- Coordinate tool execution +- Handle cron jobs and webhooks + +**Key APIs**: +```typescript +class GatewayServer { + constructor(config: GatewayConfig); + + async start(): Promise; + async stop(): Promise; + + registerChat(chat: ChatSession): void; + unregisterChat(chatId: string): void; + + async routeMessage(message: InboundMessage): Promise; + + getModelCatalog(): ModelCatalog; + getBrowserTool(): BrowserTool; + getDiscoveryService(): DiscoveryService; +} +``` + +**Configuration**: +```yaml +gateway: + mode: local # 'local' or 'remote' + port: 18789 + bind: loopback # 'loopback' or 'all' + verbose: true +``` + +--- + +### Chat Registry (`src/gateway/chat-registry.ts`) + +**Purpose**: Maintains registry of all active chat sessions. + +**Responsibilities**: +- Register new chat sessions +- Track active sessions +- Clean up inactive sessions +- Provide session lookup + +**Key APIs**: +```typescript +class ChatRegistry { + register(chat: ChatSession): void; + unregister(chatId: string): void; + + get(chatId: string): ChatSession | undefined; + getAll(): ChatSession[]; + + findByChannel(channel: string): ChatSession[]; + findByUser(userId: string): ChatSession[]; + + cleanup(): void; +} +``` + +**Data Structure**: +```typescript +interface ChatSession { + id: string; + channel: string; + userId: string; + groupId?: string; + + agent: AgentSession; + context: SessionContext; + + createdAt: number; + lastActivityAt: number; + + metadata: Record; +} +``` + +--- + +### Model Catalog (`src/gateway/model-catalog.ts`) + +**Purpose**: Maintains catalog of available AI models and their configurations. + +**Responsibilities**: +- List available models +- Provide model configurations +- Handle model authentication +- Track model usage and costs + +**Key APIs**: +```typescript +class ModelCatalog { + getAvailableModels(): ModelInfo[]; + getModel(modelId: string): ModelInfo | undefined; + + getAuthProfile(modelId: string): AuthProfile; + setAuthProfile(modelId: string, profile: AuthProfile): void; + + getUsageStats(modelId: string): UsageStats; +} +``` + +**Model Info Structure**: +```typescript +interface ModelInfo { + id: string; + name: string; + provider: 'anthropic' | 'openai' | 'google' | 'bedrock' | 'ollama'; + + capabilities: { + vision: boolean; + tools: boolean; + streaming: boolean; + }; + + limits: { + maxTokens: number; + contextWindow: number; + rateLimit: RateLimit; + }; + + pricing: { + inputCostPer1k: number; + outputCostPer1k: number; + }; +} +``` + +--- + +### Browser Tool (`src/gateway/browser-tool.ts`) + +**Purpose**: Shared browser automation tool using Playwright. + +**Responsibilities**: +- Launch and manage browser instances +- Execute browser automation tasks +- Capture screenshots and PDFs +- Handle browser profiles and cookies + +**Key APIs**: +```typescript +class BrowserTool { + async launch(options: LaunchOptions): Promise; + async close(instanceId: string): Promise; + + async navigate(instanceId: string, url: string): Promise; + async screenshot(instanceId: string, options: ScreenshotOptions): Promise; + async pdf(instanceId: string, options: PDFOptions): Promise; + + async click(instanceId: string, selector: string): Promise; + async type(instanceId: string, selector: string, text: string): Promise; + async fill(instanceId: string, selector: string, value: string): Promise; + + async evaluate(instanceId: string, script: string): Promise; + async snapshot(instanceId: string): Promise; +} +``` + +**Configuration**: +```yaml +tools: + browser: + enabled: true + headless: true + timeout: 30000 + viewport: + width: 1280 + height: 720 + profiles: + - name: default + cookies: [] + localStorage: {} +``` + +--- + +### Discovery Service (`src/gateway/discovery.ts`) + +**Purpose**: Service discovery using mDNS for local network. + +**Responsibilities**: +- Advertise gateway service +- Discover other gateways +- Handle service announcements + +**Key APIs**: +```typescript +class DiscoveryService { + async advertise(service: ServiceInfo): Promise; + async stopAdvertise(): Promise; + + async discover(serviceType: string): Promise; + watch(serviceType: string, handler: ServiceHandler): void; +} +``` + +--- + +## Agent Runtime Components + +### Pi Agent Runner (`src/agents/pi-embedded-runner.ts`) + +**Purpose**: Execute AI models in RPC mode with tool streaming. + +**Responsibilities**: +- Execute model requests +- Stream tool calls and results +- Handle model authentication +- Manage failover on errors + +**Key APIs**: +```typescript +class PiAgentRunner { + constructor(config: AgentConfig); + + async* execute( + session: SessionContext, + message: string + ): AsyncGenerator; + + async executeTools( + session: SessionContext, + tools: ToolCall[] + ): Promise; + + async streamResponse( + session: SessionContext + ): AsyncGenerator; +} +``` + +**Event Types**: +```typescript +type AgentEvent = + | { type: 'tool_call', data: ToolCall } + | { type: 'tool_result', data: ToolResult } + | { type: 'text_chunk', data: string } + | { type: 'thinking', data: string } + | { type: 'error', data: Error }; +``` + +--- + +### Session Manager (`src/agents/session-manager.ts`) + +**Purpose**: Manage agent session lifecycle and context. + +**Responsibilities**: +- Create and destroy sessions +- Load and save session context +- Manage message history +- Handle session isolation + +**Key APIs**: +```typescript +class SessionManager { + createSession(config: SessionConfig): AgentSession; + destroySession(sessionId: string): void; + + getSession(sessionId: string): AgentSession | undefined; + getAllSessions(): AgentSession[]; + + async loadContext(sessionId: string): Promise; + async saveContext(sessionId: string, context: SessionContext): Promise; + + async addMessage(sessionId: string, message: Message): Promise; + async getMessages(sessionId: string, limit: number): Promise; +} +``` + +**Session Context**: +```typescript +interface SessionContext { + sessionId: string; + chatId: string; + channel: string; + + messages: Message[]; + maxTokens: number; + + model: string; + temperature: number; + thinkingMode: 'low' | 'high' | 'always'; + + availableTools: Tool[]; + toolResults: ToolResult[]; + + memory: MemoryStore; + skills: Skill[]; + + metadata: Record; +} +``` + +--- + +### Tool Registry (`src/agents/tool-registry.ts`) + +**Purpose**: Registry of available tools for agents. + +**Responsibilities**: +- Register tools +- Validate tool schemas +- Execute tool calls +- Track tool usage + +**Key APIs**: +```typescript +class ToolRegistry { + register(tool: Tool): void; + unregister(toolName: string): void; + + get(toolName: string): Tool | undefined; + getAll(): Tool[]; + + async execute( + toolName: string, + params: unknown, + context: ToolContext + ): Promise; + + validateParams(toolName: string, params: unknown): boolean; +} +``` + +**Tool Interface**: +```typescript +interface Tool { + name: string; + description: string; + schema: JSONSchema; + + execute(params: unknown, context: ToolContext): Promise; +} +``` + +--- + +### Model Auth (`src/agents/model-auth.ts`) + +**Purpose**: Handle model authentication and token management. + +**Responsibilities**: +- Store API keys and OAuth tokens +- Refresh expired tokens +- Rotate auth profiles on failure +- Secure credential storage + +**Key APIs**: +```typescript +class ModelAuth { + async getAuthProfile(modelId: string): Promise; + async setAuthProfile(modelId: string, profile: AuthProfile): Promise; + + async refreshToken(modelId: string): Promise; + async rotateProfile(modelId: string): Promise; + + async validateCredentials(modelId: string): Promise; +} +``` + +**Auth Profile**: +```typescript +interface AuthProfile { + type: 'api_key' | 'oauth'; + + // For API keys + apiKey?: string; + + // For OAuth + accessToken?: string; + refreshToken?: string; + expiresAt?: number; + + metadata: Record; +} +``` + +--- + +## Channel Components + +### Base Channel Interface (`src/channels/base.ts`) + +**Purpose**: Common interface for all channel implementations. + +**Responsibilities**: +- Define channel lifecycle +- Normalize messages +- Handle errors gracefully + +**Interface**: +```typescript +interface Channel { + name: string; + type: ChannelType; + + // Lifecycle + init(config: ChannelConfig): Promise; + start(): Promise; + stop(): Promise; + + // Messaging + send(message: OutboundMessage): Promise; + receive(handler: MessageHandler): void; + + // Status + getStatus(): ChannelStatus; + getConnections(): Connection[]; +} +``` + +--- + +### WhatsApp Channel (`src/whatsapp/`) + +**Purpose**: WhatsApp integration using Baileys library. + +**Key Files**: +- `bot.ts` - Main bot implementation +- `send.ts` - Message sending +- `markdown.ts` - Markdown to WhatsApp formatting +- `qr.ts` - QR code pairing + +**Configuration**: +```yaml +channels: + whatsapp: + enabled: true + pairing: code + allowlist: + - "+1234567890" + session: main +``` + +--- + +### Telegram Channel (`src/telegram/`) + +**Purpose**: Telegram integration using grammY library. + +**Key Files**: +- `bot.ts` - Main bot implementation +- `handlers.ts` - Message handlers +- `markdown.ts` - Markdown to Telegram formatting +- `keyboard.ts` - Inline keyboard support + +**Configuration**: +```yaml +channels: + telegram: + enabled: true + bot_token: "${TELEGRAM_BOT_TOKEN}" + allowlist: + - "username1" + - "username2" +``` + +--- + +### Signal Channel (`src/signal/`) + +**Purpose**: Signal integration using signal-cli. + +**Key Files**: +- `bot.ts` - Main bot implementation +- `cli.ts` - signal-cli wrapper +- `send.ts` - Message sending + +**Configuration**: +```yaml +channels: + signal: + enabled: true + phone: "+1234567890" + allowlist: + - "+0987654321" +``` + +--- + +### Discord Channel (`src/discord/`) + +**Purpose**: Discord integration using discord.js. + +**Key Files**: +- `bot.ts` - Main bot implementation +- `handlers.ts` - Event handlers +- `markdown.ts` - Markdown to Discord formatting +- `embeds.ts` - Rich embed support + +**Configuration**: +```yaml +channels: + discord: + enabled: true + bot_token: "${DISCORD_BOT_TOKEN}" + dm: + policy: pairing + allowFrom: [] + guilds: + - guild_id: "123456789" + channels: ["general", "bot-commands"] +``` + +--- + +### Slack Channel (`src/slack/`) + +**Purpose**: Slack integration using Bolt framework. + +**Key Files**: +- `bot.ts` - Main bot implementation +- `handlers.ts` - Event handlers +- `blocks.ts` - Block Kit formatting + +**Configuration**: +```yaml +channels: + slack: + enabled: true + bot_token: "${SLACK_BOT_TOKEN}" + signing_secret: "${SLACK_SIGNING_SECRET}" + dm: + policy: pairing +``` + +--- + +## Tool Components + +### Browser Tool (`src/browser/`) + +**Purpose**: Web automation using Playwright. + +**Key Files**: +- `browser-tool.ts` - Main tool implementation +- `playwright-bridge.ts` - Playwright wrapper +- `snapshot.ts` - Page snapshot generation +- `profiles.ts` - Browser profile management + +**Tool Schema**: +```typescript +{ + name: "browser", + description: "Automate web browsing", + schema: { + action: "navigate" | "click" | "type" | "screenshot", + url?: string, + selector?: string, + text?: string + } +} +``` + +--- + +### Canvas Tool (`src/canvas-host/`) + +**Purpose**: Visual workspace with A2UI framework. + +**Key Files**: +- `index.ts` - Main canvas implementation +- `a2ui/` - A2UI framework bundles +- `renderer.ts` - DOM rendering +- `websocket.ts` - Real-time updates + +**Tool Schema**: +```typescript +{ + name: "canvas", + description: "Create visual workspace", + schema: { + action: "create" | "update" | "render", + content?: string, + layout?: string + } +} +``` + +--- + +### Bash Tool (`src/process/`) + +**Purpose**: Execute shell commands safely. + +**Key Files**: +- `exec.ts` - Command execution +- `spawn-utils.ts` - Process spawning utilities +- `command-queue.ts` - Command queuing + +**Tool Schema**: +```typescript +{ + name: "bash", + description: "Execute shell commands", + schema: { + command: string, + timeout?: number, + cwd?: string, + env?: Record + } +} +``` + +--- + +### Memory Tool (`src/memory/`) + +**Purpose**: Store and retrieve contextual information. + +**Key Files**: +- `index.ts` - Main memory implementation +- `vector-store.ts` - Vector embeddings +- `cache.ts` - Caching layer + +**Tool Schema**: +```typescript +{ + name: "memory", + description: "Store and recall information", + schema: { + action: "store" | "recall" | "search", + key?: string, + value?: unknown, + query?: string + } +} +``` + +--- + +## Plugin System Components + +### Plugin Discovery (`src/plugins/discovery.ts`) + +**Purpose**: Auto-detect and validate plugins. + +**Responsibilities**: +- Scan plugin directories +- Validate manifests +- Check dependencies + +**Key APIs**: +```typescript +class PluginDiscovery { + async discoverPlugins(): Promise; + async validateManifest(manifest: PluginManifest): Promise; + async checkDependencies(manifest: PluginManifest): Promise; +} +``` + +--- + +### Plugin Loader (`src/plugins/loader.ts`) + +**Purpose**: Load and initialize plugins. + +**Responsibilities**: +- Load plugin modules +- Initialize plugins +- Register hooks +- Inject services + +**Key APIs**: +```typescript +class PluginLoader { + async load(manifest: PluginManifest): Promise; + async init(plugin: Plugin): Promise; + async start(plugin: Plugin): Promise; + async stop(plugin: Plugin): Promise; + + registerHooks(plugin: Plugin): void; + injectServices(plugin: Plugin, services: PluginServices): void; +} +``` + +--- + +### Plugin Services (`src/plugins/services.ts`) + +**Purpose**: Provide services to plugins. + +**Services**: +```typescript +interface PluginServices { + gateway: GatewayClient; + config: ConfigProvider; + logger: Logger; + http: HttpClient; + storage: StorageProvider; +} +``` + +--- + +## Configuration Components + +### Config Loader (`src/config/index.ts`) + +**Purpose**: Load and validate configuration. + +**Responsibilities**: +- Load YAML configuration +- Validate with Zod schemas +- Merge environment variables +- Handle migrations + +**Key APIs**: +```typescript +class ConfigLoader { + async load(path: string): Promise; + async validate(config: unknown): Promise; + async save(path: string, config: Config): Promise; + + merge(configs: Partial[]): Config; + migrate(oldConfig: unknown): Config; +} +``` + +--- + +### Config Schema (`src/config/schema.ts`) + +**Purpose**: Zod schemas for configuration validation. + +**Schemas**: +```typescript +const ConfigSchema = z.object({ + gateway: GatewayConfigSchema, + agents: AgentsConfigSchema, + channels: ChannelsConfigSchema, + tools: ToolsConfigSchema, + sandbox: SandboxConfigSchema, + plugins: PluginsConfigSchema, + skills: SkillsConfigSchema, +}); +``` + +--- + +### Path Manager (`src/config/paths.ts`) + +**Purpose**: Manage system paths. + +**Paths**: +```typescript +class PathManager { + getConfigDir(): string; + getCredentialsDir(): string; + getSessionsDir(): string; + getMediaDir(): string; + getMemoryDir(): string; + getLogsDir(): string; + + resolve(relativePath: string): string; +} +``` + +--- + +## Storage Components + +### Session Store (`src/sessions/`) + +**Purpose**: Persist session data. + +**Key APIs**: +```typescript +class SessionStore { + async create(session: SessionContext): Promise; + async read(sessionId: string): Promise; + async update(session: SessionContext): Promise; + async delete(sessionId: string): Promise; + + async addMessage(sessionId: string, message: Message): Promise; + async getMessages(sessionId: string, limit: number): Promise; +} +``` + +--- + +### Memory Store (`src/memory/`) + +**Purpose**: Vector storage for contextual memory. + +**Key APIs**: +```typescript +class MemoryStore { + async addEmbedding(key: string, embedding: number[]): Promise; + async searchEmbeddings(query: number[], k: number): Promise; + + async set(key: string, value: unknown): Promise; + async get(key: string): Promise; + async delete(key: string): Promise; + + async recall(query: string): Promise; +} +``` + +--- + +## Utility Components + +### Logger (`src/logger.ts`) + +**Purpose**: Structured logging with tslog. + +**Key APIs**: +```typescript +class Logger { + debug(message: string, ...args: unknown[]): void; + info(message: string, ...args: unknown[]): void; + warn(message: string, ...args: unknown[]): void; + error(message: string, ...args: unknown[]): void; + + child(name: string): Logger; +} +``` + +--- + +### Terminal Utils (`src/terminal/`) + +**Purpose**: Terminal UI utilities. + +**Key Files**: +- `palette.ts` - Color palette +- `table.ts` - Table formatting +- `progress.ts` - Progress bars + +--- + +### Markdown Utils (`src/markdown/`) + +**Purpose**: Markdown parsing and rendering. + +**Key APIs**: +```typescript +class MarkdownUtils { + parse(markdown: string): MarkdownNode[]; + render(nodes: MarkdownNode[]): string; + + toHTML(markdown: string): string; + toPlainText(markdown: string): string; +} +``` + +--- + +**End of Components Documentation** diff --git a/docs/INDEX.md b/docs/INDEX.md new file mode 100644 index 000000000..d468bc396 --- /dev/null +++ b/docs/INDEX.md @@ -0,0 +1,356 @@ +# Índice de DocumentaciΓ³n de Jarvis + +## πŸ“š DocumentaciΓ³n Completa del Proyecto + +Este directorio contiene toda la documentaciΓ³n del proyecto Jarvis, un asistente personal de IA que se ejecuta en tus propios dispositivos. + +--- + +## πŸš€ Documentos Principales + +### [README-ES.md](README-ES.md) +**DocumentaciΓ³n completa en espaΓ±ol** + +Incluye: +- VisiΓ³n general del proyecto +- ΒΏQuΓ© es Jarvis? +- Arquitectura del sistema +- Componentes principales +- Canales de mensajerΓ­a soportados +- TecnologΓ­as utilizadas +- Sistema de plugins +- ConfiguraciΓ³n y despliegue +- Desarrollo +- Estructura de directorios + +πŸ“– **Recomendado como punto de partida** para entender todo el proyecto. + +--- + +### [ARCHITECTURE.md](ARCHITECTURE.md) +**DocumentaciΓ³n tΓ©cnica de arquitectura** + +Incluye: +- Arquitectura de alto nivel +- Componentes del sistema +- Flujo de datos +- Enrutamiento de mensajes +- Modelo de ejecuciΓ³n de agentes +- Arquitectura de plugins +- Modelo de seguridad +- Almacenamiento y persistencia +- Arquitectura de red + +πŸ“– **Recomendado para desarrolladores** que necesitan entender la arquitectura tΓ©cnica. + +--- + +### [COMPONENTS.md](COMPONENTS.md) +**DocumentaciΓ³n de componentes individuales** + +Incluye: +- Componentes del Gateway +- Componentes del Runtime de Agente +- Componentes de Canales +- Componentes de Herramientas +- Componentes del Sistema de Plugins +- Componentes de ConfiguraciΓ³n +- Componentes de Almacenamiento +- Componentes de Utilidades + +πŸ“– **Recomendado para desarrolladores** que trabajan en componentes especΓ­ficos. + +--- + +## πŸ“– DocumentaciΓ³n por CategorΓ­a + +### 🎯 Inicio RΓ‘pido + +| Documento | DescripciΓ³n | +|-----------|-------------| +| [start/](start/) | GuΓ­as de inicio rΓ‘pido y tutoriales | +| [install/](install/) | GuΓ­as de instalaciΓ³n paso a paso | +| [Getting Started](start/) | GuΓ­a para principiantes | + +### βš™οΈ ConfiguraciΓ³n + +| Documento | DescripciΓ³n | +|-----------|-------------| +| [README-ES.md#configuraciΓ³n-y-despliegue](README-ES.md#configuraciΓ³n-y-despliegue) | GuΓ­a completa de configuraciΓ³n | +| [gateway/](gateway/) | ConfiguraciΓ³n del Gateway | +| [environment.md](environment.md) | Variables de entorno | + +### πŸ’¬ Canales + +| Documento | DescripciΓ³n | +|-----------|-------------| +| [channels/](channels/) | DocumentaciΓ³n de todos los canales | +| [README-ES.md#canales-de-mensajerΓ­a](README-ES.md#canales-de-mensajerΓ­a) | Lista de canales soportados | + +### πŸ” Seguridad + +| Documento | DescripciΓ³n | +|-----------|-------------| +| [security/](security/) | GuΓ­as de seguridad | +| [ARCHITECTURE.md#security-model](ARCHITECTURE.md#security-model) | Modelo de seguridad | + +### πŸ› οΈ Desarrollo + +| Documento | DescripciΓ³n | +|-----------|-------------| +| [README-ES.md#desarrollo](README-ES.md#desarrollo) | GuΓ­a de desarrollo | +| [testing.md](testing.md) | GuΓ­as de testing | +| [debugging.md](debugging.md) | GuΓ­as de depuraciΓ³n | + +### πŸ”Œ Plugins + +| Documento | DescripciΓ³n | +|-----------|-------------| +| [plugins/](plugins/) | DocumentaciΓ³n de plugins | +| [ARCHITECTURE.md#plugin-architecture](ARCHITECTURE.md#plugin-architecture) | Arquitectura de plugins | + +### πŸ€– Conceptos de IA + +| Documento | DescripciΓ³n | +|-----------|-------------| +| [concepts/](concepts/) | Conceptos fundamentales | +| [README-ES.md#tecnologΓ­as-utilizadas](README-ES.md#tecnologΓ­as-utilizadas) | Modelos IA soportados | + +### πŸ–₯️ Plataformas + +| Documento | DescripciΓ³n | +|-----------|-------------| +| [platforms/](platforms/) | GuΓ­as especΓ­ficas de plataforma | +| macOS | DocumentaciΓ³n de macOS | +| iOS | DocumentaciΓ³n de iOS | +| Android | DocumentaciΓ³n de Android | + +### πŸ“š Referencia + +| Documento | DescripciΓ³n | +|-----------|-------------| +| [reference/](reference/) | DocumentaciΓ³n de referencia | +| [cli/](cli/) | Referencia de comandos CLI | +| [tools/](tools/) | Referencia de herramientas | + +--- + +## πŸ—ΊοΈ Mapa de NavegaciΓ³n + +### Para Nuevos Usuarios + +1. **Empezar aquΓ­**: [README-ES.md](README-ES.md) - VisiΓ³n general completa +2. **Instalar**: [install/](install/) - GuΓ­as de instalaciΓ³n +3. **Configurar**: [README-ES.md#configuraciΓ³n-y-despliegue](README-ES.md#configuraciΓ³n-y-despliegue) +4. **Usar**: [start/](start/) - GuΓ­as de uso bΓ‘sico + +### Para Desarrolladores + +1. **Arquitectura**: [ARCHITECTURE.md](ARCHITECTURE.md) - Entender el sistema +2. **Componentes**: [COMPONENTS.md](COMPONENTS.md) - Componentes individuales +3. **Desarrollo**: [README-ES.md#desarrollo](README-ES.md#desarrollo) - Setup de desarrollo +4. **Testing**: [testing.md](testing.md) - GuΓ­as de testing + +### Para Crear Plugins + +1. **Sistema de Plugins**: [ARCHITECTURE.md#plugin-architecture](ARCHITECTURE.md#plugin-architecture) +2. **Ejemplos**: [extensions/](../extensions/) - Plugins existentes +3. **Plugin SDK**: Ver cΓ³digo en `src/plugin-sdk/` + +--- + +## πŸ“ Estructura de DocumentaciΓ³n + +``` +docs/ +β”œβ”€β”€ README-ES.md # πŸ“– DocumentaciΓ³n completa en espaΓ±ol +β”œβ”€β”€ ARCHITECTURE.md # πŸ—οΈ Arquitectura tΓ©cnica +β”œβ”€β”€ COMPONENTS.md # πŸ”§ Componentes individuales +β”œβ”€β”€ INDEX.md # πŸ“‹ Este archivo (Γ­ndice) +β”‚ +β”œβ”€β”€ start/ # πŸš€ Inicio rΓ‘pido +β”‚ β”œβ”€β”€ getting-started.md +β”‚ └── wizard.md +β”‚ +β”œβ”€β”€ install/ # πŸ“¦ InstalaciΓ³n +β”‚ β”œβ”€β”€ docker.md +β”‚ └── updating.md +β”‚ +β”œβ”€β”€ channels/ # πŸ’¬ Canales +β”‚ β”œβ”€β”€ whatsapp.md +β”‚ β”œβ”€β”€ telegram.md +β”‚ β”œβ”€β”€ discord.md +β”‚ └── ... +β”‚ +β”œβ”€β”€ gateway/ # 🌐 Gateway +β”‚ β”œβ”€β”€ configuration.md +β”‚ β”œβ”€β”€ security.md +β”‚ └── doctor.md +β”‚ +β”œβ”€β”€ concepts/ # πŸ’‘ Conceptos +β”‚ β”œβ”€β”€ models.md +β”‚ β”œβ”€β”€ session.md +β”‚ β”œβ”€β”€ groups.md +β”‚ └── agent.md +β”‚ +β”œβ”€β”€ cli/ # πŸ’» CLI +β”‚ └── commands.md +β”‚ +β”œβ”€β”€ tools/ # πŸ› οΈ Herramientas +β”‚ β”œβ”€β”€ browser.md +β”‚ β”œβ”€β”€ canvas.md +β”‚ └── skills.md +β”‚ +β”œβ”€β”€ plugins/ # πŸ”Œ Plugins +β”‚ └── development.md +β”‚ +β”œβ”€β”€ security/ # πŸ” Seguridad +β”‚ └── best-practices.md +β”‚ +β”œβ”€β”€ platforms/ # πŸ–₯️ Plataformas +β”‚ β”œβ”€β”€ macos/ +β”‚ β”œβ”€β”€ ios/ +β”‚ β”œβ”€β”€ android/ +β”‚ └── linux/ +β”‚ +β”œβ”€β”€ reference/ # πŸ“š Referencia +β”‚ └── RELEASING.md +β”‚ +β”œβ”€β”€ automation/ # πŸ€– AutomatizaciΓ³n +β”œβ”€β”€ debug/ # πŸ› DepuraciΓ³n +β”œβ”€β”€ diagnostics/ # πŸ” DiagnΓ³sticos +β”œβ”€β”€ nodes/ # πŸ“‘ Nodos +β”œβ”€β”€ providers/ # 🏒 Proveedores +β”œβ”€β”€ web/ # 🌐 Web UI +β”‚ +β”œβ”€β”€ assets/ # 🎨 Assets +β”œβ”€β”€ images/ # πŸ–ΌοΈ ImΓ‘genes +└── _layouts/ # πŸ“„ Layouts +``` + +--- + +## πŸ” BΓΊsqueda por Tema + +### InstalaciΓ³n y ConfiguraciΓ³n +- [InstalaciΓ³n](install/) +- [ConfiguraciΓ³n](README-ES.md#configuraciΓ³n-y-despliegue) +- [Variables de entorno](environment.md) +- [Docker](install/docker.md) + +### Canales de MensajerΓ­a +- [Todos los canales](channels/) +- [WhatsApp](channels/whatsapp.md) +- [Telegram](channels/telegram.md) +- [Discord](channels/discord.md) +- [Signal](channels/signal.md) +- [Slack](channels/slack.md) + +### Desarrollo +- [Setup de desarrollo](README-ES.md#desarrollo) +- [Arquitectura](ARCHITECTURE.md) +- [Componentes](COMPONENTS.md) +- [Testing](testing.md) +- [Debugging](debugging.md) + +### Plugins y Extensiones +- [Sistema de plugins](ARCHITECTURE.md#plugin-architecture) +- [Desarrollo de plugins](plugins/) +- [Plugins existentes](../extensions/) + +### Herramientas +- [Browser Tool](tools/browser.md) +- [Canvas Tool](tools/canvas.md) +- [Skills](tools/skills.md) + +### Seguridad +- [Modelo de seguridad](ARCHITECTURE.md#security-model) +- [Mejores prΓ‘cticas](security/best-practices.md) +- [Gateway security](gateway/security.md) + +### Plataformas +- [macOS](platforms/macos/) +- [iOS](platforms/ios/) +- [Android](platforms/android/) +- [Linux](platforms/linux/) + +--- + +## πŸ“Š Diagramas + +Los documentos incluyen varios diagramas ASCII para visualizar: + +- **Arquitectura del Sistema**: [ARCHITECTURE.md](ARCHITECTURE.md#high-level-architecture) +- **Flujo de Datos**: [ARCHITECTURE.md](ARCHITECTURE.md#data-flow) +- **Flujo de Mensajes**: [README-ES.md](README-ES.md#arquitectura-del-sistema) +- **Diagrama de Uso**: Ver README mejorado en raΓ­z del proyecto +- **Diagrama de ConfiguraciΓ³n**: Ver README mejorado en raΓ­z del proyecto + +--- + +## πŸ”— Enlaces Útiles + +### Repositorio +- **CΓ³digo fuente**: https://github.com/jeturing/Jarvis +- **Issues**: https://github.com/jeturing/Jarvis/issues +- **Pull Requests**: https://github.com/jeturing/Jarvis/pulls +- **Discussions**: https://github.com/jeturing/Jarvis/discussions + +### Comunidad +- **Discord**: (AΓ±adir enlace si existe) +- **Foro**: (AΓ±adir enlace si existe) + +### Recursos Externos +- **Anthropic Claude**: https://www.anthropic.com/ +- **OpenAI GPT**: https://openai.com/ +- **Playwright**: https://playwright.dev/ +- **grammY (Telegram)**: https://grammy.dev/ + +--- + +## 🀝 Contribuir a la DocumentaciΓ³n + +ΒΏEncontraste un error o quieres mejorar la documentaciΓ³n? + +1. **Reporta issues**: [GitHub Issues](https://github.com/jeturing/Jarvis/issues) +2. **EnvΓ­a PRs**: Sigue las guΓ­as en [CONTRIBUTING.md](../CONTRIBUTING.md) +3. **Discute mejoras**: [GitHub Discussions](https://github.com/jeturing/Jarvis/discussions) + +### GuΓ­as para Contribuir + +- MantΓ©n un tono claro y profesional +- Incluye ejemplos de cΓ³digo cuando sea posible +- AΓ±ade diagramas ASCII para conceptos complejos +- Actualiza el Γ­ndice cuando aΓ±adas nuevos documentos +- Verifica que todos los enlaces funcionen + +--- + +## πŸ“„ Licencia + +La documentaciΓ³n estΓ‘ licenciada bajo la misma licencia MIT que el proyecto principal. Ver [LICENSE](../LICENSE). + +--- + +## ⚑ Actualizaciones Recientes + +- **2024-01**: CreaciΓ³n de documentaciΓ³n completa en espaΓ±ol +- **2024-01**: AΓ±adida documentaciΓ³n de arquitectura tΓ©cnica +- **2024-01**: AΓ±adida documentaciΓ³n de componentes +- **2024-01**: Creado Γ­ndice de navegaciΓ³n + +--- + +## πŸ“§ Contacto + +ΒΏNecesitas mΓ‘s ayuda? + +- **Email**: (AΓ±adir email de contacto) +- **Discord**: (AΓ±adir enlace de Discord) +- **Twitter**: (AΓ±adir handle de Twitter) + +--- + +

+ Β‘Feliz aprendizaje y desarrollo con Jarvis! πŸ€– +

diff --git a/docs/README-ES.md b/docs/README-ES.md new file mode 100644 index 000000000..68641405d --- /dev/null +++ b/docs/README-ES.md @@ -0,0 +1,979 @@ +# 🦞 Moltbot - DocumentaciΓ³n Completa del Proyecto + +## Índice +1. [VisiΓ³n General](#visiΓ³n-general) +2. [ΒΏQuΓ© es Moltbot?](#quΓ©-es-moltbot) +3. [Arquitectura del Sistema](#arquitectura-del-sistema) +4. [Componentes Principales](#componentes-principales) +5. [Canales de MensajerΓ­a](#canales-de-mensajerΓ­a) +6. [TecnologΓ­as Utilizadas](#tecnologΓ­as-utilizadas) +7. [Sistema de Plugins](#sistema-de-plugins) +8. [ConfiguraciΓ³n y Despliegue](#configuraciΓ³n-y-despliegue) +9. [Desarrollo](#desarrollo) +10. [Estructura de Directorios](#estructura-de-directorios) + +--- + +## VisiΓ³n General + +**Moltbot** (tambiΓ©n conocido como Jarvis o Clawdbot) es un **asistente personal de IA** que se ejecuta en tus propios dispositivos. Es una plataforma local-first, auto-hospedada y diseΓ±ada para control de usuario ΓΊnico. + +### CaracterΓ­sticas Principales + +βœ… **Multi-canal**: Conecta con WhatsApp, Telegram, Slack, Discord, Signal, iMessage, Microsoft Teams, Matrix, Zalo y mΓ‘s +βœ… **Capacidades de voz**: Wake Voice, Talk Mode (entrada/salida de voz en macOS/iOS/Android) +βœ… **Canvas en vivo**: Espacio de trabajo visual controlado por agente con framework A2UI +βœ… **Herramientas de primera clase**: Browser, Canvas, Cron, Sessions, acciones de Discord/Slack +βœ… **Enrutamiento multi-agente**: Aisla agentes por espacio de trabajo/canal +βœ… **Asistente de configuraciΓ³n**: `moltbot onboard` para configuraciΓ³n fΓ‘cil +βœ… **Daemon siempre activo**: vΓ­a systemd/launchd +βœ… **Soporte Gateway remoto**: para servidores Linux sin interfaz grΓ‘fica +βœ… **Privacidad**: Se ejecuta localmente, sin dependencia de servidor + +--- + +## ΒΏQuΓ© es Moltbot? + +Moltbot es un asistente de IA personal que: + +### PropΓ³sito Principal +- Asistente de IA personal siempre activo usando modelos Claude/OpenAI +- Gateway de mensajerΓ­a multi-canal (bandeja de entrada unificada entre plataformas) +- Funciona en macOS, iOS, Android, Linux, Windows (WSL2) +- Enfocado en privacidad: se ejecuta localmente, sin dependencia de servidor + +### Casos de Uso +1. **Asistente Personal**: Responde preguntas, ejecuta tareas, gestiona calendarios +2. **Centro de MensajerΓ­a Unificado**: Una interfaz para todos tus canales de chat +3. **AutomatizaciΓ³n**: Ejecuta scripts, gestiona tareas programadas (cron) +4. **NavegaciΓ³n Web**: AutomatizaciΓ³n de navegador con Playwright +5. **Procesamiento de Medios**: TranscripciΓ³n de audio, anΓ‘lisis de imΓ‘genes, procesamiento de video +6. **Desarrollo**: Asistente de cΓ³digo, revisiΓ³n de cΓ³digo, depuraciΓ³n + +### Ventajas Únicas +- **Control Total**: TΓΊ posees tus datos y configuraciΓ³n +- **Sin Servidor Central**: No hay dependencia de servicios de terceros +- **Extensible**: Sistema de plugins robusto para aΓ±adir funcionalidad +- **Multi-Plataforma**: Funciona en todos los sistemas operativos principales +- **Seguro**: AutenticaciΓ³n local, polΓ­ticas de lista de permitidos + +--- + +## Arquitectura del Sistema + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Gateway (Servidor WebSocket) β”‚ +β”‚ - Plano de control para sesiones/canales β”‚ +β”‚ - Registro de chat y enrutamiento de mensajes β”‚ +β”‚ - CatΓ‘logo de modelos y perfiles de autenticaciΓ³n β”‚ +β”‚ - Trabajos cron, webhooks, herramienta de navegadorβ”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Runtime de Agente (Pi Agent) β”‚ +β”‚ - Modo RPC embedding β”‚ +β”‚ - Streaming de herramientas y bloques β”‚ +β”‚ - Failover de modelos/rotaciΓ³n de auth β”‚ +β”‚ - Ventana de contexto de sesiΓ³n β”‚ +β”‚ - Entorno sandbox (Docker opcional) β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Capa Multi-Canal β”‚ +β”‚ - Manejadores de canal base β”‚ +β”‚ - AnΓ‘lisis de mensajes entrantes β”‚ +β”‚ - Enrutamiento y formato salientes β”‚ +β”‚ - PolΓ­ticas de lista de permitidos/emparejamiento DMβ”‚ +β”‚ - Enrutamiento de menciones en grupo β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Sistema de Herramientas β”‚ +β”‚ - Browser (automatizaciΓ³n web) β”‚ +β”‚ - Canvas (espacio de trabajo visual) β”‚ +β”‚ - Image (analizar/generar) β”‚ +β”‚ - Message (enviar entre canales) β”‚ +β”‚ - Session (generar sub-agentes) β”‚ +β”‚ - Bash (ejecutar comandos) β”‚ +β”‚ - Web (fetch, search, readability) β”‚ +β”‚ - Memory (recordar contexto) β”‚ +β”‚ - Cron (programar tareas) β”‚ +β”‚ - Acciones Discord/Slack/WhatsApp β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +### Flujo de Mensajes + +1. **Entrada**: Mensaje recibido desde canal (WhatsApp, Telegram, etc.) +2. **Enrutamiento**: Gateway determina sesiΓ³n y agente apropiado +3. **Procesamiento**: Agente procesa mensaje con herramientas disponibles +4. **EjecuciΓ³n**: Herramientas se ejecutan (browser, bash, memory, etc.) +5. **Respuesta**: Agente genera respuesta basada en resultados +6. **Salida**: Mensaje enviado de vuelta al canal original o cruzado + +--- + +## Componentes Principales + +### 1. Gateway (`src/gateway/`) + +El **Gateway** es el corazΓ³n del sistema. Es un servidor WebSocket que: + +- **Gestiona todas las sesiones** de chat activas +- **Enruta mensajes** entre canales y agentes +- **Mantiene catΓ‘logo de modelos** (Claude, GPT, Bedrock) +- **Ejecuta trabajos cron** y webhooks +- **Proporciona herramienta de navegador** compartida +- **Maneja descubrimiento** de servicios (mDNS) + +**Archivos clave:** +- `server.ts` - Servidor principal WebSocket +- `chat-registry.ts` - Registro de chats activos +- `model-catalog.ts` - CatΓ‘logo de modelos AI +- `browser-tool.ts` - IntegraciΓ³n de Playwright + +### 2. Runtime de Agente (`src/agents/`) + +El **Runtime de Agente** ejecuta modelos de IA y gestiona interacciones: + +- **IntegraciΓ³n Pi Agent** (`pi-embedded-runner.ts`) - Ejecuta Claude/GPT en modo RPC +- **GestiΓ³n de sesiones** (`session-*.ts`) - Aisla contextos de chat +- **Streaming de herramientas** - Streaming en tiempo real de uso de herramientas +- **Failover de modelos** - RotaciΓ³n automΓ‘tica si un modelo falla +- **Manejo de perfiles de auth** - OAuth y claves API + +**Archivos clave:** +- `pi-embedded-runner.ts` - Ejecutor principal de agente +- `session-manager.ts` - Gestor de sesiones de chat +- `tool-registry.ts` - Registro de herramientas disponibles +- `model-auth.ts` - AutenticaciΓ³n de modelos + +### 3. Canales (`src/channels/`, `extensions/`) + +**Canales integrados** (en `src/`): +- `whatsapp/` - WhatsApp (biblioteca Baileys) +- `telegram/` - Telegram (grammY) +- `signal/` - Signal (signal-cli) +- `imessage/` - iMessage (imsg) +- `discord/` - Discord (discord.js) +- `slack/` - Slack (Bolt) + +**Canales de extensiΓ³n** (en `extensions/`): +- `msteams/` - Microsoft Teams +- `matrix/` - Matrix con soporte E2E +- `zalo/`, `zalouser/` - MensajerΓ­a vietnamita +- `bluebubbles/` - Relay iMessage +- Y mΓ‘s de 20 extensiones de canal + +**CaracterΓ­sticas:** +- Emparejamiento DM (lista de permitidos basada en cΓ³digo) +- Enrutamiento de grupo/canal con control de menciones +- Etiquetas de respuesta para respuestas basadas en hilos +- FragmentaciΓ³n de mensajes por canal +- Reconocimientos de reacciΓ³n +- Indicadores de escritura + +### 4. Sistema de Plugins (`src/plugins/`) + +El **sistema de plugins** permite extensibilidad: + +**Tipos de plugins:** +- **Plugins de canal** - Nuevas integraciones de mensajerΓ­a +- **Plugins de auth** - Manejadores OAuth +- **Plugins de herramientas** - Herramientas personalizadas de agente +- **Plugins de memoria** - Backends de almacenamiento personalizados +- **Plugins de hooks** - Manejadores de eventos globales + +**Archivos clave:** +- `discovery.ts` - Auto-detecta plugins +- `loader.ts` - Carga plugins validados +- `manifest.ts` - ValidaciΓ³n de esquema de manifiesto +- `services.ts` - Proveedores de inyecciΓ³n de servicios + +### 5. Herramienta de Navegador (`src/browser/`) + +La **herramienta de navegador** proporciona automatizaciΓ³n web: + +- **AutomatizaciΓ³n Chromium** vΓ­a Playwright +- **Snapshots conscientes de IA** de pΓ‘ginas +- **Rellenado de formularios e interacciΓ³n** +- **GeneraciΓ³n de screenshots y PDF** +- **Perfiles personalizados** con cookies/almacenamiento +- **Puente CDP** para depuraciΓ³n DevTools + +**Archivos clave:** +- `browser-tool.ts` - API principal de herramienta +- `playwright-bridge.ts` - Puente Playwright +- `snapshot.ts` - GeneraciΓ³n de snapshots de pΓ‘gina + +### 6. Pipeline de Medios (`src/media/`) + +El **pipeline de medios** maneja procesamiento de medios: + +- Procesamiento de imagen/audio/video +- Hooks de transcripciΓ³n +- AlmacΓ©n de archivos con lΓ­mites de tamaΓ±o +- DetecciΓ³n de tipo MIME +- GestiΓ³n de ciclo de vida temporal + +**Archivos clave:** +- `index.ts` - API principal de medios +- `transcription.ts` - Hooks de transcripciΓ³n de audio +- `file-store.ts` - Almacenamiento persistente de archivos + +### 7. Canvas Host (`src/canvas-host/`) + +El **Canvas Host** proporciona un espacio de trabajo visual: + +- Framework A2UI para renderizado +- ActualizaciΓ³n de estado en tiempo real +- SerializaciΓ³n de DOM +- IntegraciΓ³n WebSocket + +**Archivos clave:** +- `index.ts` - API principal de Canvas +- `a2ui/` - Paquetes de framework A2UI + +### 8. CLI (`src/cli/`) + +La **CLI** proporciona interfaz de lΓ­nea de comandos: + +**Comandos principales:** +- `gateway` - Iniciar servidor gateway +- `agent` - Ejecutar agente AI +- `onboard` - Asistente de configuraciΓ³n +- `models` - Gestionar modelos AI +- `channels` - Gestionar canales +- `cron` - Gestionar trabajos programados +- `daemon` - Gestionar servicio daemon +- `plugins` - Gestionar plugins +- `skills` - Gestionar skills + +**Archivos clave:** +- `index.ts` - Entry point de CLI +- `commands/` - Implementaciones de comandos + +### 9. ConfiguraciΓ³n (`src/config/`) + +El **sistema de configuraciΓ³n** gestiona ajustes: + +- Carga de configuraciΓ³n YAML +- ValidaciΓ³n de esquema Zod +- Almacenamiento de sesiΓ³n +- GestiΓ³n de rutas +- Migraciones de configuraciΓ³n + +**Archivos clave:** +- `index.ts` - Cargador principal de configuraciΓ³n +- `schema.ts` - Esquema de validaciΓ³n Zod +- `paths.ts` - ResoluciΓ³n de rutas de sistema + +--- + +## Canales de MensajerΓ­a + +### Canales Integrados + +| Canal | Biblioteca | Estado | +|-------|-----------|--------| +| **WhatsApp** | @whiskeysockets/baileys | βœ… Estable | +| **Telegram** | grammy | βœ… Estable | +| **Signal** | signal-cli | βœ… Estable | +| **iMessage** | imsg | βœ… Estable | +| **Discord** | discord.js | βœ… Estable | +| **Slack** | @slack/bolt | βœ… Estable | +| **Google Chat** | Chat API | βœ… Estable | + +### Canales de ExtensiΓ³n + +| Canal | UbicaciΓ³n | Estado | +|-------|-----------|--------| +| **BlueBubbles** | extensions/bluebubbles | βœ… Estable | +| **Microsoft Teams** | extensions/msteams | βœ… Estable | +| **Matrix** | extensions/matrix | βœ… Estable | +| **Zalo** | extensions/zalo | βœ… Estable | +| **Zalo Personal** | extensions/zalouser | βœ… Estable | +| **Twitch** | extensions/twitch | βœ… Estable | +| **Mattermost** | extensions/mattermost | βœ… Estable | +| **Nextcloud Talk** | extensions/nextcloud-talk | βœ… Estable | +| **Tlon** | extensions/tlon | βœ… Estable | +| **Nostr** | extensions/nostr | βœ… Estable | +| **LINE** | extensions/line | βœ… Estable | +| **Voice Call** | extensions/voice-call | βœ… Beta | + +### CaracterΓ­sticas de Canal + +- **Emparejamiento DM**: Lista de permitidos basada en cΓ³digo +- **Enrutamiento de grupo**: Control de menciones +- **Etiquetas de respuesta**: Respuestas basadas en hilos +- **FragmentaciΓ³n de mensajes**: LΓ­mites especΓ­ficos por canal +- **Reacciones**: Reconocimientos +- **Indicadores de escritura**: Estado en tiempo real +- **RedacciΓ³n de medios**: Capacidades de privacidad + +--- + +## TecnologΓ­as Utilizadas + +### Stack Backend + +| TecnologΓ­a | VersiΓ³n | PropΓ³sito | +|------------|---------|-----------| +| **TypeScript** | 5.9+ | Lenguaje principal | +| **Node.js** | β‰₯22.12.0 | Runtime | +| **Hono** | 4.11.4 | Framework HTTP | +| **Express** | 5.2 | Servidor WebSocket (legacy) | +| **ws** | 8.19 | Biblioteca WebSocket | +| **Zod** | 4.3 | ValidaciΓ³n de esquema | + +### IntegraciΓ³n AI/Modelo + +| TecnologΓ­a | PropΓ³sito | +|------------|-----------| +| **@mariozechner/pi-agent-core** | Agente Pi de Anthropic | +| **@mariozechner/pi-tui** | UI de terminal para agente | +| **Anthropic SDK** | API Claude | +| **OpenAI SDK** | API ChatGPT | +| **AWS Bedrock SDK** | Modelos AWS | +| **Ollama SDK** | Soporte LLM local | + +### MensajerΓ­a & ComunicaciΓ³n + +| Biblioteca | Canal | +|-----------|-------| +| **@whiskeysockets/baileys** | WhatsApp | +| **grammy** | Telegram | +| **@slack/bolt** | Slack | +| **discord.js** | Discord | +| **@line/bot-sdk** | LINE | +| **signal-cli** | Signal | +| **imsg** | iMessage | + +### AutomatizaciΓ³n de Navegador + +| TecnologΓ­a | PropΓ³sito | +|------------|-----------| +| **Playwright Core** | 1.58 - AutomatizaciΓ³n web | +| **chromium-bidi** | 13.0 - Protocolo DevTools Chrome | +| **Sharp** | 0.34 - Procesamiento de imΓ‘genes | +| **pdfjs-dist** | ManipulaciΓ³n de PDF | + +### Base de Datos & Almacenamiento + +| TecnologΓ­a | PropΓ³sito | +|------------|-----------| +| **SQLite-vec** | Almacenamiento vectorial para memoria | +| **LanceDB** | BΓΊsqueda vectorial (extensiΓ³n) | +| **Sistema de archivos** | Persistencia de sesiΓ³n/configuraciΓ³n | +| **proper-lockfile** | Control de acceso concurrente | + +### CLI & DevOps + +| TecnologΓ­a | PropΓ³sito | +|------------|-----------| +| **Commander.js** | AnΓ‘lisis de argumentos CLI | +| **@clack/prompts** | Prompts CLI interactivos | +| **Chalk** | Colores de terminal | +| **dotenv** | ConfiguraciΓ³n de entorno | +| **YAML** | Soporte de formato de configuraciΓ³n | + +### Herramientas de Desarrollo + +| TecnologΓ­a | PropΓ³sito | +|------------|-----------| +| **TypeScript** | VerificaciΓ³n de tipos estricta | +| **Vitest** | Ejecutor de tests | +| **oxlint** | Linting (OxC) | +| **oxfmt** | Formateo | +| **tsx** | EjecuciΓ³n TS | +| **Playwright Core** | Testing E2E | +| **Wireit** | OrquestaciΓ³n de tareas de build | + +--- + +## Sistema de Plugins + +### Arquitectura de Plugins + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Descubrimiento de Plugins β”‚ +β”‚ - Auto-detecta desde extensions/ β”‚ +β”‚ - Auto-detecta desde node_modules/@moltbot/β”‚ +β”‚ - ValidaciΓ³n de manifiesto β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Cargador de Plugins β”‚ +β”‚ - ValidaciΓ³n de esquema de configuraciΓ³n β”‚ +β”‚ - InicializaciΓ³n de runtime β”‚ +β”‚ - Registro de hooks β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Proveedores de Servicios β”‚ +β”‚ - Acceso a cliente Gateway β”‚ +β”‚ - Proveedor de configuraciΓ³n β”‚ +β”‚ - InyecciΓ³n de logger β”‚ +β”‚ - Utilidades de cliente HTTP β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +### Tipos de Plugins + +#### 1. Plugins de Canal +AΓ±aden nuevos canales de mensajerΓ­a: +```typescript +export function createChannelPlugin(): ChannelPlugin { + return { + name: 'my-channel', + type: 'channel', + init: async (config) => { + // Inicializar canal + }, + send: async (message) => { + // Enviar mensaje + }, + receive: async (handler) => { + // Recibir mensajes + } + } +} +``` + +#### 2. Plugins de Herramientas +AΓ±aden herramientas personalizadas para agentes: +```typescript +export function createToolPlugin(): ToolPlugin { + return { + name: 'my-tool', + type: 'tool', + schema: z.object({ + input: z.string() + }), + execute: async (params) => { + // Ejecutar herramienta + return { result: 'done' } + } + } +} +``` + +#### 3. Plugins de Auth +AΓ±aden manejadores OAuth personalizados: +```typescript +export function createAuthPlugin(): AuthPlugin { + return { + name: 'my-auth', + type: 'auth', + authorize: async (credentials) => { + // Manejar OAuth + return { token: 'access_token' } + } + } +} +``` + +#### 4. Plugins de Memoria +AΓ±aden backends de almacenamiento personalizados: +```typescript +export function createMemoryPlugin(): MemoryPlugin { + return { + name: 'my-memory', + type: 'memory', + store: async (key, value) => { + // Almacenar valor + }, + retrieve: async (key) => { + // Recuperar valor + } + } +} +``` + +#### 5. Plugins de Hooks +AΓ±aden manejadores de eventos globales: +```typescript +export function createHookPlugin(): HookPlugin { + return { + name: 'my-hook', + type: 'hook', + hooks: { + 'message:received': async (message) => { + // Manejar mensaje recibido + }, + 'message:sent': async (message) => { + // Manejar mensaje enviado + } + } + } +} +``` + +### Esquema de Manifiesto de Plugin + +```json +{ + "name": "plugin-name", + "version": "1.0.0", + "description": "Plugin description", + "exports": { + ".": "./dist/index.js", + "./config-schema": "./dist/config-schema.js" + }, + "hooks": ["channel", "tool"], + "permissions": ["network", "fs"], + "dependencies": { + "some-lib": "^1.0.0" + } +} +``` + +### Ciclo de Vida de Plugin + +1. **Descubrimiento** - Auto-detecta plugins desde directorios conocidos +2. **ValidaciΓ³n** - Valida manifiesto y esquema de configuraciΓ³n +3. **Carga** - Carga mΓ³dulo de plugin +4. **InicializaciΓ³n** - Ejecuta funciΓ³n init de plugin +5. **Registro** - Registra hooks y herramientas +6. **EjecuciΓ³n** - Plugin maneja eventos y llamadas +7. **Apagado** - Limpieza durante apagado de gateway + +--- + +## ConfiguraciΓ³n y Despliegue + +### Archivo de ConfiguraciΓ³n Principal + +El archivo `.moltbot.yaml` (o `.clawdbot.yaml`) controla toda la configuraciΓ³n: + +```yaml +# ConfiguraciΓ³n de Gateway +gateway: + mode: local # o 'remote' + port: 18789 + bind: loopback # o 'all' + verbose: true + +# ConfiguraciΓ³n de Agentes +agents: + default: + model: claude-4.5-sonnet + thinking: high + temperature: 0.7 + max_tokens: 8192 + +# ConfiguraciΓ³n de Canales +channels: + whatsapp: + enabled: true + pairing: code + allowlist: + - "+1234567890" + + telegram: + enabled: true + bot_token: "${TELEGRAM_BOT_TOKEN}" + + discord: + enabled: true + bot_token: "${DISCORD_BOT_TOKEN}" + +# ConfiguraciΓ³n de Herramientas +tools: + browser: + enabled: true + headless: true + timeout: 30000 + + canvas: + enabled: true + port: 8080 + +# ConfiguraciΓ³n de Sandbox +sandbox: + enabled: false + docker_image: "moltbot/sandbox" + +# ConfiguraciΓ³n de Plugins +plugins: + - name: matrix + enabled: true + config: + homeserver: "https://matrix.org" + +# ConfiguraciΓ³n de Skills +skills: + - workspace1 + - workspace2 +``` + +### Variables de Entorno + +Archivo `.env`: +```bash +# Tokens de API +ANTHROPIC_API_KEY=sk-ant-... +OPENAI_API_KEY=sk-... +TELEGRAM_BOT_TOKEN=123456:ABC-DEF... +DISCORD_BOT_TOKEN=MTk4... + +# ConfiguraciΓ³n de Gateway +CLAWDBOT_GATEWAY_PORT=18789 +CLAWDBOT_GATEWAY_BIND=loopback + +# ConfiguraciΓ³n de Modo +CLAWDBOT_PROFILE=production # o 'dev' +CLAWDBOT_SKIP_CHANNELS=0 + +# ConfiguraciΓ³n de DepuraciΓ³n +CLAWDBOT_DEBUG=0 +CLAWDBOT_VERBOSE=0 +``` + +### InstalaciΓ³n + +#### InstalaciΓ³n rΓ‘pida (npm) +```bash +npm install -g moltbot@latest +moltbot onboard --install-daemon +``` + +#### Desde fuente (desarrollo) +```bash +git clone https://github.com/moltbot/moltbot.git +cd moltbot +pnpm install +pnpm ui:build +pnpm build +pnpm moltbot onboard --install-daemon +``` + +#### Docker +```bash +docker-compose up -d +``` + +### Despliegue como Daemon + +#### macOS (launchd) +```bash +moltbot daemon install +moltbot daemon start +moltbot daemon status +``` + +#### Linux (systemd) +```bash +moltbot daemon install +systemctl --user start moltbot-gateway +systemctl --user status moltbot-gateway +``` + +#### Windows (WSL2) +```bash +# En WSL2 +moltbot daemon install +moltbot daemon start +``` + +### Gateway Remoto + +Para servidores sin interfaz grΓ‘fica: + +```yaml +# En servidor remoto +gateway: + mode: remote + bind: all + port: 18789 + +# En cliente local +agents: + gateway_url: "ws://your-server:18789" +``` + +--- + +## Desarrollo + +### ConfiguraciΓ³n de Entorno de Desarrollo + +```bash +# 1. Clonar repositorio +git clone https://github.com/moltbot/moltbot.git +cd moltbot + +# 2. Instalar dependencias +pnpm install + +# 3. Construir UI +pnpm ui:build + +# 4. Construir proyecto +pnpm build + +# 5. Ejecutar en modo desarrollo +pnpm gateway:watch # Auto-recarga en cambios +``` + +### Scripts de Desarrollo + +```bash +# Desarrollo +pnpm dev # Ejecutar CLI en modo dev +pnpm gateway:watch # Gateway con auto-recarga +pnpm gateway:dev # Gateway dev sin canales +pnpm tui:dev # UI de terminal dev + +# Build +pnpm build # Compilar TypeScript +pnpm ui:build # Construir UI web +pnpm canvas:a2ui:bundle # Empaquetar Canvas A2UI + +# Testing +pnpm test # Ejecutar todos los tests +pnpm test:watch # Tests en modo watch +pnpm test:coverage # Tests con cobertura +pnpm test:e2e # Tests end-to-end +pnpm test:live # Tests con APIs reales + +# Linting & Formatting +pnpm lint # Lint TypeScript +pnpm lint:fix # Fix problemas de lint +pnpm format # Verificar formato +pnpm format:fix # Fix formato + +# Plataformas +pnpm ios:build # Construir app iOS +pnpm ios:run # Ejecutar app iOS +pnpm android:assemble # Ensamblar app Android +pnpm android:run # Ejecutar app Android +pnpm mac:package # Empaquetar app macOS +``` + +### Estructura de Testing + +``` +test/ +β”œβ”€β”€ unit/ # Tests unitarios +β”œβ”€β”€ e2e/ # Tests end-to-end +β”œβ”€β”€ integration/ # Tests de integraciΓ³n +└── fixtures/ # Datos de prueba +``` + +**Configuraciones de Vitest:** +- `vitest.config.ts` - ConfiguraciΓ³n principal +- `vitest.unit.config.ts` - Tests unitarios +- `vitest.e2e.config.ts` - Tests E2E +- `vitest.live.config.ts` - Tests con APIs reales +- `vitest.extensions.config.ts` - Tests de extensiones +- `vitest.gateway.config.ts` - Tests de gateway + +### Requisitos de Cobertura de Tests + +- **LΓ­neas**: 70% +- **Funciones**: 70% +- **Ramas**: 70% +- **Declaraciones**: 70% + +### EstΓ‘ndares de CΓ³digo + +- **TypeScript estricto**: VerificaciΓ³n de tipos completa +- **ESLint**: Linting con oxlint +- **Prettier**: Formateo con oxfmt +- **Pre-commit hooks**: Ejecuta lint + format antes de commit +- **LΓ­mite de LOC**: ~700 lΓ­neas por archivo (guΓ­a) + +--- + +## Estructura de Directorios + +``` +/ +β”œβ”€β”€ src/ # CΓ³digo fuente TypeScript +β”‚ β”œβ”€β”€ agents/ # Runtime de agente y gestiΓ³n de sesiones +β”‚ β”œβ”€β”€ gateway/ # Servidor gateway y registro de chat +β”‚ β”œβ”€β”€ channels/ # Infraestructura base de canales +β”‚ β”œβ”€β”€ cli/ # Comandos de interfaz de lΓ­nea de comandos +β”‚ β”œβ”€β”€ browser/ # Herramienta de automatizaciΓ³n de navegador +β”‚ β”œβ”€β”€ canvas-host/ # Host de Canvas y framework A2UI +β”‚ β”œβ”€β”€ media/ # Pipeline de procesamiento de medios +β”‚ β”œβ”€β”€ plugins/ # Sistema de plugins y cargador +β”‚ β”œβ”€β”€ config/ # Sistema de configuraciΓ³n +β”‚ β”œβ”€β”€ whatsapp/ # IntegraciΓ³n WhatsApp +β”‚ β”œβ”€β”€ telegram/ # IntegraciΓ³n Telegram +β”‚ β”œβ”€β”€ signal/ # IntegraciΓ³n Signal +β”‚ β”œβ”€β”€ discord/ # IntegraciΓ³n Discord +β”‚ β”œβ”€β”€ slack/ # IntegraciΓ³n Slack +β”‚ β”œβ”€β”€ imessage/ # IntegraciΓ³n iMessage +β”‚ β”œβ”€β”€ routing/ # Enrutamiento de mensajes +β”‚ β”œβ”€β”€ security/ # Auth y polΓ­ticas de seguridad +β”‚ β”œβ”€β”€ memory/ # GestiΓ³n de memoria/contexto +β”‚ β”œβ”€β”€ tts/ # IntegraciΓ³n text-to-speech +β”‚ β”œβ”€β”€ wizard/ # Flujo de asistente de onboarding CLI +β”‚ β”œβ”€β”€ web/ # Frontend WebChat y Control UI +β”‚ β”œβ”€β”€ utils/ # Utilidades compartidas +β”‚ └── ... +β”‚ +β”œβ”€β”€ extensions/ # Plugins de canal y extensiones +β”‚ β”œβ”€β”€ bluebubbles/ # Plugin BlueBubbles +β”‚ β”œβ”€β”€ matrix/ # Plugin Matrix +β”‚ β”œβ”€β”€ msteams/ # Plugin Microsoft Teams +β”‚ β”œβ”€β”€ zalo/ # Plugin Zalo +β”‚ β”œβ”€β”€ zalouser/ # Plugin Zalo Personal +β”‚ β”œβ”€β”€ voice-call/ # Plugin Voice Call +β”‚ └── ... +β”‚ +β”œβ”€β”€ apps/ # Aplicaciones nativas +β”‚ β”œβ”€β”€ macos/ # App macOS (SwiftUI) +β”‚ β”œβ”€β”€ ios/ # App iOS (SwiftUI) +β”‚ └── android/ # App Android (Kotlin) +β”‚ +β”œβ”€β”€ docs/ # DocumentaciΓ³n +β”‚ β”œβ”€β”€ start/ # GuΓ­as de inicio +β”‚ β”œβ”€β”€ install/ # GuΓ­as de instalaciΓ³n +β”‚ β”œβ”€β”€ channels/ # DocumentaciΓ³n de canales +β”‚ β”œβ”€β”€ concepts/ # DocumentaciΓ³n de conceptos +β”‚ β”œβ”€β”€ cli/ # DocumentaciΓ³n de CLI +β”‚ β”œβ”€β”€ gateway/ # DocumentaciΓ³n de gateway +β”‚ β”œβ”€β”€ platforms/ # GuΓ­as especΓ­ficas de plataforma +β”‚ β”œβ”€β”€ providers/ # DocumentaciΓ³n de proveedores +β”‚ β”œβ”€β”€ reference/ # DocumentaciΓ³n de referencia +β”‚ └── ... +β”‚ +β”œβ”€β”€ skills/ # Paquetes de skills de workspace +β”‚ └── workspace1/ # Ejemplo de workspace +β”‚ +β”œβ”€β”€ packages/ # Paquetes monorepo +β”‚ └── ... +β”‚ +β”œβ”€β”€ scripts/ # Scripts de utilidad +β”‚ β”œβ”€β”€ build-*.ts # Scripts de build +β”‚ β”œβ”€β”€ test-*.sh # Scripts de test +β”‚ β”œβ”€β”€ package-*.sh # Scripts de empaquetado +β”‚ └── ... +β”‚ +β”œβ”€β”€ test/ # Fixtures de test y helpers +β”‚ β”œβ”€β”€ fixtures/ # Datos de prueba +β”‚ └── helpers/ # Utilidades de test +β”‚ +β”œβ”€β”€ ui/ # UI web (Control UI) +β”‚ └── ... +β”‚ +β”œβ”€β”€ vendor/ # Dependencias vendorizadas +β”‚ └── ... +β”‚ +β”œβ”€β”€ .github/ # Workflows de GitHub Actions +β”‚ β”œβ”€β”€ workflows/ # Definiciones de workflow CI/CD +β”‚ └── labeler.yml # ConfiguraciΓ³n de auto-etiquetado +β”‚ +β”œβ”€β”€ dist/ # Salida compilada (generada) +β”‚ └── ... +β”‚ +β”œβ”€β”€ package.json # ConfiguraciΓ³n de paquete npm +β”œβ”€β”€ pnpm-workspace.yaml # ConfiguraciΓ³n de workspace pnpm +β”œβ”€β”€ tsconfig.json # ConfiguraciΓ³n de TypeScript +β”œβ”€β”€ vitest.config.ts # ConfiguraciΓ³n de Vitest +β”œβ”€β”€ docker-compose.yml # ConfiguraciΓ³n de Docker Compose +β”œβ”€β”€ Dockerfile # Dockerfile principal +β”œβ”€β”€ README.md # README principal (inglΓ©s) +β”œβ”€β”€ CHANGELOG.md # Registro de cambios +β”œβ”€β”€ LICENSE # Licencia MIT +└── ... +``` + +### Directorios Clave + +#### `/src/` +CΓ³digo fuente principal de TypeScript. Organizado por dominio: +- **Agentes & Runtime**: `agents/`, `memory/`, `sessions/` +- **ComunicaciΓ³n**: `gateway/`, `channels/`, `routing/` +- **Canales Integrados**: `whatsapp/`, `telegram/`, `discord/`, etc. +- **Herramientas**: `browser/`, `canvas-host/`, `media/`, `tts/` +- **Sistema**: `cli/`, `config/`, `plugins/`, `daemon/` +- **Seguridad**: `security/`, `pairing/` +- **UI**: `web/`, `wizard/`, `tui/` + +#### `/extensions/` +Plugins de extensiΓ³n (20+ canales). Cada extensiΓ³n es un paquete npm auto-contenido: +- Tiene su propio `package.json` +- Define `plugin.manifest.json` +- Implementa hooks de plugin +- Puede tener dependencias propias + +#### `/apps/` +Aplicaciones nativas para mΓΊltiples plataformas: +- **macOS**: App SwiftUI con integraciΓ³n de menubar +- **iOS**: App SwiftUI con soporte de voz +- **Android**: App Kotlin con soporte de voz + +#### `/docs/` +DocumentaciΓ³n completa (Mintlify): +- GuΓ­as de inicio rΓ‘pido +- Tutoriales de instalaciΓ³n +- DocumentaciΓ³n de conceptos +- Referencia de API +- GuΓ­as especΓ­ficas de plataforma +- DocumentaciΓ³n de desarrollo de plugins + +#### `/skills/` +Skills de workspace. Cada workspace puede tener: +- Prompts personalizados +- Herramientas bash personalizadas +- Integraciones personalizadas +- ConfiguraciΓ³n especΓ­fica de workspace + +#### `/scripts/` +Scripts de utilidad para: +- ConstrucciΓ³n y empaquetado +- Testing (unit, E2E, Docker) +- GeneraciΓ³n de cΓ³digo (protocol, Swift) +- GestiΓ³n de releases +- AutomatizaciΓ³n de desarrollo + +#### `/test/` +Fixtures de test y helpers: +- Datos de prueba +- Mocks y stubs +- Utilidades de test +- Configuraciones de test + +--- + +## Recursos Adicionales + +### DocumentaciΓ³n Oficial +- **Sitio Web**: https://molt.bot +- **DocumentaciΓ³n**: https://docs.molt.bot +- **Comenzar**: https://docs.molt.bot/start/getting-started +- **FAQ**: https://docs.molt.bot/start/faq +- **Showcase**: https://docs.molt.bot/start/showcase + +### Comunidad +- **Discord**: https://discord.gg/clawd +- **GitHub**: https://github.com/moltbot/moltbot +- **Releases**: https://github.com/moltbot/moltbot/releases + +### GuΓ­as de Desarrollo +- **Desarrollo de Plugins**: Ver `PLUGIN-DEVELOPMENT.md` +- **Referencia de API**: Ver `API-REFERENCE.md` +- **GuΓ­a de Arquitectura**: Ver `ARCHITECTURE.md` +- **GuΓ­a de Despliegue**: Ver `DEPLOYMENT.md` + +--- + +## Licencia + +MIT License - Ver [LICENSE](../LICENSE) para detalles. + +--- + +## Contribuir + +Β‘Las contribuciones son bienvenidas! Ver [CONTRIBUTING.md](../CONTRIBUTING.md) para guΓ­as. + +--- + +**Β‘Feliz hacking con Moltbot! 🦞**