Local Agent - Debugging & Diagnostics Guide
⚠️ Nota (2026-07): esta guía describe la era v6.0.x/v2.0.x del Agente y está pendiente de regeneración por el Bibliotecario. La versión vigente vive en
terminal/agent/version.py(AGENT_VERSION); el auto-update desatendido (onedir + Ed25519) está operativo desde 2026-07.
Local Agent - Debugging & Diagnostics Guide
Agente: CreaRack Local Agent v2.0.13
Puerto: localhost:5050
Framework: FastAPI + Uvicorn
Fuente de verdad versión: terminal/agent/version.py
Guia completa de todos los endpoints HTTP, WebSocket y herramientas de diagnóstico disponibles en el Local Agent para debugging desde navegador, cURL o JavaScript.
Quick Reference
| URL | Descripcion |
|---|---|
| http://localhost:5050 | Panel de debug (HTML) |
| http://localhost:5050/info | Info completa (JSON) — incluye role |
| http://localhost:5050/health | Health check rapido |
| http://localhost:5050/agent/role | Rol actual (primary/secondary) + sentinel_active |
| http://localhost:5050/check?host=IP&port=22 | Verificar puerto abierto |
| http://localhost:5050/terminal/ui | Terminal SSH (XTerm.js) |
1. Endpoints Basicos (GET - Navegador)
GET / - Panel de Debug
Acceder directamente desde el navegador. Muestra un panel HTML con:
- Version del agente y uptime
- Entorno (Python, plataforma, modo frozen/dev)
- Estado del cluster engine (Scrapli disponible, drivers)
- Sesiones SSH activas (con indicador SFTP y logging)
- Boton para abrir la Debug Console (logs en tiempo real)
- Estado de conexion SaaS y cache offline
http://localhost:5050
Si se llama con header
Accept: application/json(ej. desde fetch/cURL), devuelve JSON en vez de HTML.
GET /info - Info Completa (JSON)
Misma informacion que / pero siempre en formato JSON. Util para consumir desde scripts.
http://localhost:5050/info
Respuesta:
{
"version": "6.5.0",
"uptime": "2d 5h 30m 45s",
"role": "primary",
"environment": {
"python": "3.14.0",
"platform": "Windows",
"machine": "AMD64",
"frozen": true
},
"cluster": {
"scrapli": true,
"drivers": ["cisco_iosxe", "cisco_nxos", "arista_eos", "juniper_junos"]
},
"sessions": {
"count": 1,
"active": [
{
"id": "term_001",
"connected": true,
"has_sftp": true,
"logging": false
}
]
},
"saas": {
"authenticated": true,
"agent_id": "agent_12345",
"tenant_id": 1,
"saas_url": "http://localhost:8000"
},
"cache": { "metrics": {}, "alerts": {} },
"monitoring": { "running": true, "targets_count": 5 },
"connector": { "state": "connected", "is_connected": true },
"sentinel": { "running": true, "mode": "sentinel", "connected": true, "pending": 0 }
}
GET /health - Health Check
Endpoint minimalista para verificar que el agente esta corriendo.
http://localhost:5050/health
Respuesta:
{
"status": "healthy",
"version": "6.5.0"
}
GET /agent/role - Rol del Agente (v6.5.0)
Consulta el rol actual del agente en el sistema de fleet Primary/Secondary.
http://localhost:5050/agent/role
Respuesta:
{
"role": "primary",
"sentinel_active": true
}
| Campo | Descripcion |
|---|---|
role | "primary" o "secondary" |
sentinel_active | true si Sentinel Mode esta ejecutandose |
Nota: Solo el agente Primary ejecuta Sentinel monitoring. Los Secondary proporcionan SSH/Tools.
GET /check - Verificar Puerto Abierto
Comprueba si un host tiene un puerto TCP abierto. Muy util para diagnosticar conectividad antes de intentar SSH.
Parametros query:
| Param | Tipo | Default | Descripcion |
|---|---|---|---|
host | string | 127.0.0.1 | IP o hostname |
port | int | 22 | Puerto a verificar |
Ejemplos desde navegador:
http://localhost:5050/check?host=192.168.0.51&port=22
http://localhost:5050/check?host=10.0.0.1&port=443
http://localhost:5050/check?host=8.8.8.8&port=53
Respuesta (puerto abierto):
{
"host": "192.168.0.51",
"port": 22,
"open": true,
"reachable": true,
"response_time": 15
}
Respuesta (puerto cerrado):
{
"host": "192.168.0.51",
"port": 8080,
"open": false,
"reachable": false,
"response_time": null
}
2. Diagnostico de Red (Network)
GET /network/ping-icmp - Ping ICMP
Ping real usando ICMP (mas preciso que TCP connect). Usa icmplib si esta disponible, fallback a comando ping del sistema.
Parametros query:
| Param | Tipo | Default | Descripcion |
|---|---|---|---|
host | string | requerido | IP o hostname |
timeout | int | 2000 | Timeout en ms |
http://localhost:5050/network/ping-icmp?host=8.8.8.8
http://localhost:5050/network/ping-icmp?host=192.168.0.1&timeout=5000
GET /network/hostname - Reverse DNS Lookup
Resuelve el hostname de una IP via DNS inverso.
Parametros query:
| Param | Tipo | Descripcion |
|---|---|---|
ip | string | IP a resolver |
http://localhost:5050/network/hostname?ip=8.8.8.8
Respuesta:
{
"ip": "8.8.8.8",
"hostname": "dns.google"
}
GET /network/arp-table - Tabla ARP del Sistema
Lee la tabla ARP de Windows para ver dispositivos en la red local. Opcionalmente filtra por subnet.
Parametros query:
| Param | Tipo | Default | Descripcion |
|---|---|---|---|
subnet | string | null | Filtro de subnet (ej: 192.168.1) |
http://localhost:5050/network/arp-table
http://localhost:5050/network/arp-table?subnet=192.168.0
GET /network/banner - SSH Banner / Deteccion de Vendor
Conecta al puerto SSH y lee el banner para identificar el sistema operativo o vendor del equipo.
Parametros query:
| Param | Tipo | Default | Descripcion |
|---|---|---|---|
host | string | requerido | IP o hostname |
port | int | 22 | Puerto SSH |
timeout | int | 2000 | Timeout en ms |
http://localhost:5050/network/banner?host=192.168.0.51
http://localhost:5050/network/banner?host=10.0.0.1&port=2222
Respuesta:
{
"host": "192.168.0.51",
"port": 22,
"banner": "SSH-2.0-OpenSSH_7.4",
"vendor": "Linux/Unix"
}
POST /network/ping - Ping Batch (TCP)
Ping TCP a multiples hosts simultaneamente.
curl -X POST http://localhost:5050/network/ping \
-H "Content-Type: application/json" \
-d '{"targets": ["192.168.0.1", "192.168.0.51", "8.8.8.8"], "timeout": 1000}'
Body:
{
"targets": ["192.168.0.1", "192.168.0.51", "8.8.8.8"],
"timeout": 1000
}
POST /network/scan - Port Scanner
Escanea puertos en una IP o rango de IPs.
curl -X POST http://localhost:5050/network/scan \
-H "Content-Type: application/json" \
-d '{"target": "192.168.0.1-10", "ports": "22,80,443,3389", "timeout": 500, "concurrent": 50}'
Body:
{
"target": "192.168.0.1-10",
"ports": "22,80,443,3389",
"timeout": 500,
"concurrent": 50
}
| Campo | Formato | Ejemplo |
|---|---|---|
target | IP o rango | 192.168.0.1 o 192.168.0.1-254 |
ports | CSV o rango | 22,80,443 o 1-1024 |
POST /network/discover - Network Discovery
Descubre dispositivos activos en una subnet completa.
curl -X POST http://localhost:5050/network/discover \
-H "Content-Type: application/json" \
-d '{"subnet": "192.168.0.0/24", "scan_type": "standard", "timeout": 500, "concurrent": 50}'
Body:
{
"subnet": "192.168.0.0/24",
"scan_type": "standard",
"timeout": 500,
"concurrent": 50
}
| scan_type | Puertos escaneados |
|---|---|
quick | 22 |
standard | 22, 23, 80, 443 |
deep | 22, 23, 80, 443, 21, 25, 53, 3389, 8080 |
3. Cluster (Multi-Device)
GET /cluster/status - Estado del Cluster Engine
Verifica si Scrapli esta disponible y que drivers soporta.
http://localhost:5050/cluster/status
Respuesta:
{
"scrapli_available": true,
"supported_platforms": ["cisco_iosxe", "cisco_nxos", "arista_eos", "juniper_junos"],
"active_sessions": 0
}
POST /cluster/execute - Ejecutar Comando en Multiples Dispositivos
curl -X POST http://localhost:5050/cluster/execute \
-H "Content-Type: application/json" \
-d '{
"devices": [
{"ip": "192.168.0.1", "username": "admin", "password": "pass", "vendor": "cisco_iosxe", "name": "Core-SW"}
],
"command": "show interfaces status"
}'
POST /cluster/script - Ejecutar Script (Multiples Comandos)
curl -X POST http://localhost:5050/cluster/script \
-H "Content-Type: application/json" \
-d '{
"devices": [
{"ip": "192.168.0.1", "username": "admin", "password": "pass", "vendor": "cisco_iosxe"}
],
"commands": ["show version", "show ip route", "show running-config"]
}'
POST /cluster/health - Health Check Batch
curl -X POST http://localhost:5050/cluster/health \
-H "Content-Type: application/json" \
-d '{
"targets": [
{"ip": "192.168.0.1", "port": 22, "name": "Router-1"},
{"ip": "192.168.0.51", "port": 22, "name": "Server-1"}
]
}'
POST /cluster/backup - Backup de Configuracion Batch
curl -X POST http://localhost:5050/cluster/backup \
-H "Content-Type: application/json" \
-d '{
"devices": [
{"ip": "192.168.0.1", "username": "admin", "password": "pass", "vendor": "cisco_iosxe", "command": "show running-config"}
]
}'
POST /execute/single - Ejecutar Comando en Un Dispositivo
Endpoint de conveniencia para un solo device.
curl -X POST "http://localhost:5050/execute/single?command=show%20version" \
-H "Content-Type: application/json" \
-d '{"ip": "192.168.0.1", "username": "admin", "password": "pass", "vendor": "cisco_iosxe"}'
4. Terminal SSH
GET /terminal/ui - Interfaz Terminal (XTerm.js)
Abre un terminal SSH completo en el navegador con XTerm.js.
http://localhost:5050/terminal/ui
Funcionalidades:
- Terminal interactivo completo
- Temas: Campbell, Gruvbox, Greenscreen, Tango
- Syntax highlighting (IPs, keywords, banners)
- Links clickeables
- Buffer de 5000 lineas
- Efecto Asteroids (easter egg)
GET /terminal/sessions - Listar Sesiones Activas
http://localhost:5050/terminal/sessions
Respuesta:
{
"sessions": ["term_001", "admin_session"]
}
POST /terminal/session/{id}/terminate - Cerrar Sesion
curl -X POST http://localhost:5050/terminal/session/term_001/terminate
Tambien disponible como DELETE /terminal/session/{id}.
Session Logging
| Endpoint | Metodo | Descripcion |
|---|---|---|
/terminal/session/{id}/log/start | POST | Iniciar grabacion |
/terminal/session/{id}/log/stop | POST | Detener grabacion |
/terminal/session/{id}/log/download | GET | Descargar log |
5. SFTP (Transferencia de Archivos)
Requieren una sesion SSH activa (client_id).
POST /sftp/list - Listar Directorio Remoto
curl -X POST http://localhost:5050/sftp/list \
-H "Content-Type: application/json" \
-d '{"client_id": "term_001", "path": "/home/admin"}'
GET /sftp/download - Descargar Archivo
http://localhost:5050/sftp/download?client_id=term_001&path=/etc/hosts
POST /sftp/upload - Subir Archivo
curl -X POST http://localhost:5050/sftp/upload \
-F "client_id=term_001" \
-F "path=/home/admin/" \
-F "file=@config_backup.txt"
POST /sftp/read - Leer Archivo Remoto (texto)
curl -X POST http://localhost:5050/sftp/read \
-H "Content-Type: application/json" \
-d '{"client_id": "term_001", "path": "/etc/hosts"}'
POST /sftp/write - Escribir Archivo Remoto
curl -X POST http://localhost:5050/sftp/write \
-H "Content-Type: application/json" \
-d '{"client_id": "term_001", "path": "/tmp/test.txt", "content": "Hello from CreaRack"}'
6. SaaS Integration (v5.0.x)
GET /saas/status - Estado de Conexion SaaS
http://localhost:5050/saas/status
Respuesta:
{
"authenticated": true,
"agent_id": "agent_12345",
"tenant_id": 1,
"saas_url": "http://localhost:8000",
"user_email": "user@example.com"
}
POST /saas/configure - Configurar Conexion SaaS
curl -X POST "http://localhost:5050/saas/configure?token=eyJhbG...&saas_url=http://localhost:8000"
POST /saas/connect - Conectar WebSocket al SaaS
curl -X POST http://localhost:5050/saas/connect
POST /saas/disconnect - Desconectar del SaaS
curl -X POST http://localhost:5050/saas/disconnect
7. Cache Offline & Monitoreo
GET /cache/stats - Estadisticas del Cache SQLite
http://localhost:5050/cache/stats
POST /cache/sync - Forzar Sincronizacion
curl -X POST http://localhost:5050/cache/sync
GET /monitoring/status - Estado del Monitoreo
http://localhost:5050/monitoring/status
POST /monitoring/start - Iniciar Monitoreo
curl -X POST http://localhost:5050/monitoring/start
POST /monitoring/stop - Detener Monitoreo
curl -X POST http://localhost:5050/monitoring/stop
7.1 Sentinel Endpoints
GET /sentinel/status - Estado del Sentinel
Devuelve estado completo del Sentinel Mode: targets, intervalos, ciclos, métricas escritas, circuit breaker, diagnósticos SNMP y estado de Edge Intelligence (anomaly detector + insight reporter).
http://localhost:5050/sentinel/status
POST /sentinel/start - Iniciar Sentinel Mode
Inicia el modo Sentinel 24/7. Opcionalmente acepta un body JSON con targets:
curl -X POST http://localhost:5050/sentinel/start \
-H "Content-Type: application/json" \
-d '{"targets": [{"target_id": 1, "ip": "192.168.1.1", "hostname": "switch-core", "monitor_types": ["ping", "snmp"], "snmp_community": "public", "snmp_version": "v2c"}]}'
Target con SNMPv3:
curl -X POST http://localhost:5050/sentinel/start \
-H "Content-Type: application/json" \
-d '{"targets": [{"target_id": 1, "ip": "10.0.0.1", "hostname": "switch-v3", "monitor_types": ["ping", "snmp"], "snmp_version": "v3", "snmp_v3_username": "snmpuser", "snmp_v3_auth_protocol": "SHA256", "snmp_v3_auth_key": "authPass", "snmp_v3_priv_protocol": "AES128", "snmp_v3_priv_key": "privPass"}]}'
POST /sentinel/stop - Detener Sentinel Mode
curl -X POST http://localhost:5050/sentinel/stop
POST /sentinel/reset - Reset Estado del Sentinel
Limpia el estado in-memory sin reiniciar el proceso del Agent. Útil cuando el Agent acumula errores, cooldowns o rate limits que bloquean la generación de insights.
curl -X POST http://localhost:5050/sentinel/reset
Qué resetea:
- AnomalyDetector: Cooldowns por target, rate limit (10/hora), anomalías activas
- InsightReporter: Contadores de error, cola de eventos pendientes
- CircuitBreaker: Todos los circuitos vuelven a CLOSED
Respuesta:
{
"status": "reset",
"anomaly_detector": {"cooldowns_cleared": 5, "active_anomalies_cleared": 2, "rate_limit_reset": true},
"insight_reporter": {"errors_cleared": 80, "queue_dropped": 0},
"circuit_breaker": "all_reset"
}
Desde la UI: Abrir el modal Agent Fleet Manager → columna Actions → botón Reset (visible en agentes online con Sentinel activo).
8. Admin
POST /admin/uninstall - Desinstalar Agente Completamente
Limpia claves del registro Windows (protocolo crearack:// y startup), elimina el directorio completo %APPDATA%\CreaRackAgent (exe, credentials, cache, logs) y cierra el proceso.
curl -X POST http://localhost:5050/admin/uninstall
Solo funciona en Windows. Tambien disponible desde el dashboard de CreaRack Pro via boton “Uninstall Local Agent”.
9. WebSocket Endpoints
ws://localhost:5050/ws/terminal/{client_id} - Terminal SSH
Terminal bidireccional sobre WebSocket. Soporta reattach a sesiones existentes con replay de buffer.
Conectar:
{"action": "connect", "host": "192.168.0.51", "username": "admin", "password": "pass", "port": 22}
Enviar comando:
{"action": "data", "data": "show version\n"}
Mensajes del servidor:
{"type": "status", "message": "Tunnel Established!"}
{"type": "output", "data": "Router#show version\n..."}
{"type": "error", "message": "Connectivity failed"}
ws://localhost:5050/ws/debug - Debug Console (Logs en Tiempo Real)
Recibe todos los logs del agente en tiempo real. Al conectar, recibe el buffer historico completo.
Mensajes del servidor:
{
"timestamp": "2026-02-05 14:30:45.123",
"level": "INFO",
"message": "[Cluster] Execute on 2 devices: show version..."
}
Accesible desde el panel de debug (http://localhost:5050 > boton Debug Console).
10. Referencia Rapida por Caso de Uso
“Quiero verificar si un equipo tiene el puerto SSH abierto”
http://localhost:5050/check?host=192.168.0.51&port=22
“Quiero ver todos los equipos en mi red”
curl -X POST http://localhost:5050/network/discover -H "Content-Type: application/json" -d '{"subnet":"192.168.0.0/24","scan_type":"standard"}'
“Quiero saber que puertos tiene abiertos un equipo”
curl -X POST http://localhost:5050/network/scan -H "Content-Type: application/json" -d '{"target":"192.168.0.51","ports":"1-1024"}'
“Quiero ver la tabla ARP de mi PC”
http://localhost:5050/network/arp-table
“Quiero saber que OS/vendor tiene un equipo”
http://localhost:5050/network/banner?host=192.168.0.51
“Quiero hacer ping ICMP real a un host”
http://localhost:5050/network/ping-icmp?host=8.8.8.8
“Quiero ver los logs del agente en tiempo real”
http://localhost:5050 → Debug Console
“Quiero ver que sesiones SSH estan activas”
http://localhost:5050/terminal/sessions
“Quiero ver si el agente esta conectado al SaaS”
http://localhost:5050/saas/status
“Quiero ver el estado completo del agente”
http://localhost:5050/info
11. Vendors Soportados (Cluster/Scrapli)
| Vendor Key | Plataforma |
|---|---|
cisco_iosxe | Cisco IOS-XE |
cisco_nxos | Cisco NX-OS |
arista_eos | Arista EOS |
juniper_junos | Juniper JunOS |
generic | SSH generico (asyncssh) |
12. Portabilidad Cross-Platform (Futuro)
Estado: Estudio de viabilidad completado (06-02-2026) Prioridad: Baja — El agente actual solo soporta Windows
Situación actual
El Local Agent depende de APIs específicas de Windows en 3 de sus 7 módulos:
| Módulo | Cross-platform | Dependencia Windows |
|---|---|---|
monitoring_service.py | ✅ | — |
saas_connector.py | ✅ | — |
offline_cache.py | ✅ | Solo %APPDATA% path |
local_agent.py | ✅ | File locking ya tiene fallback fcntl |
auth_manager.py | ❌ | DPAPI (ctypes.windll.crypt32) |
installer.py | ❌ | Registry, MessageBox, toast, taskkill |
windows_integration.py | ❌ | 100% Windows (registry, protocol handler, startup) |
Dependencias críticas y alternativas
auth_manager.py — Cifrado de credenciales
| Plataforma | API actual / propuesta |
|---|---|
| Windows | DPAPI (CryptProtectData) — vinculado al usuario Windows |
| macOS | Keychain API via librería keyring |
| Linux | Secret Service API via librería keyring (requiere desktop environment) |
installer.py — Integración con el OS
| Feature | Windows | macOS | Linux |
|---|---|---|---|
| Notificaciones | win10toast | pync / osascript | notify-send |
| Protocol handler | Registry | Info.plist en .app bundle | .desktop file |
| Auto-start | Registry Run key | LaunchAgent plist | .desktop en ~/.config/autostart/ |
| Kill proceso | taskkill /F /PID | os.kill(pid, SIGTERM) | os.kill(pid, SIGTERM) |
Paths del sistema
| Tipo | Windows | macOS | Linux |
|---|---|---|---|
| User Data | %APPDATA% | ~/Library/Application Support | ~/.local/share |
| Cache | %LOCALAPPDATA% | ~/Library/Caches | ~/.cache |
Solución: librería platformdirs para resolución automática.
icmplib (ICMP Ping)
- Windows: funciona sin privilegios especiales
- Linux/macOS: requiere root o
CAP_NET_RAW(sudo setcap cap_net_raw+ep ./agent)
Estimación de esfuerzo
| Fase | Horas estimadas |
|---|---|
| Core cross-platform (paths, auth, platform_integration) | 12-16h |
| Instaladores específicos (pkg, deb, LaunchAgent, desktop files) | 16-20h |
| Build system (Python script + CI/CD para 3 plataformas) | 6-8h |
| Testing (Windows 10/11, macOS 13+, Ubuntu 22.04+) | 10-15h |
| Total | ~50-60h |
Alternativa rápida: Agent en Docker
En lugar de portar el agente nativo, un contenedor Docker elimina todo el código platform-specific:
docker run -d --name crearack-agent --net=host crearack/agent:latest
| Port nativo | Docker | |
|---|---|---|
| Esfuerzo | ~60h | ~8-10h |
| Requisito usuario | Ninguno | Docker instalado |
| Integración OS | Nativa (toast, auto-start, protocol) | Ninguna |
| Actualización | Auto-update propio | docker pull |
| Peso | ~20MB exe | ~150MB imagen |
Recomendación
Mientras el target principal sea Windows, no merece la pena invertir en port nativo. Si se necesita soporte Mac/Linux, la opción Docker ofrece el mejor ratio coste/beneficio. El port nativo solo tiene sentido si la integración con el OS (auto-start, notificaciones, protocol handler) es un requisito de producto.
Ultima actualizacion: 13-02-2026 Version del agente: v6.5.0
Véase también
- [[crearack-tech—backend—local-agent]] — backend del Local Agent
- [[crearack-tech—admin—local-agent]] — admin del Local Agent
- [[crearack-tech—guides—agent-distribution]] — distribución del Local Agent
- [[crearack-tech—agents—dev-terminal]] — perfil de subagente dev-terminal
- [[crearack—terminal—local-agent]] — Local Agent desde el usuario
- [[crearack—terminal—troubleshooting-terminal]] — troubleshooting del Terminal
- [[concept—terminal—local-agent]] — arquitectura del Local Agent
- [[entity—terminal—model—agentinstance]] — instancia de Local Agent registrada