Commit Graph

23 Commits

Author SHA1 Message Date
egutierrez 8811d45fd1 feat: conectar sistema centralizado de seguridad al launcher y runtime
- Migrar admin a security/user-groups.yaml (admins group)
- agents.New() ahora acepta acl.ACL pre-resuelta como parámetro;
  elimina construcción interna desde cfg.Security.Roles
- cmd/launcher: carga shellsecurity.Load("security/") al arranque;
  si falla, WARN + política vacía (open access). Para cada agente
  llama pksecurity.ResolveACL y pasa la ACL a agents.New()
- cmd/launcher/registry.go: stores secPolicy en launchDeps para
  que reload() también resuelva ACL centralmente
- shell/matrix/listener.go: elimina invite gating y allowlist check
  basados en AllowedUsers; el control de acceso lo hace el runtime
- internal/config/schema.go: depreca campos Roles y AllowedUsers
  (backward compat, no eliminados)
- agents/*/config.yaml: elimina bloques security.roles y allowed_users
- dev/feature_flags.json: activa centralized-security-groups (enabled: true)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-08 20:56:21 +00:00
egutierrez f95370de80 test: tests para hot-reload (bus, registry, ciclo de vida del agente)
- shell/bus/bus_test.go: tests de Subscribe/Send/Unsubscribe incluyendo
  idempotencia, canal cerrado tras unsubscribe y resubscribe posterior.

- cmd/launcher/registry_test.go: tests para readReloadTarget (archivo
  ausente, vacío, '*', agentID, whitespace).

- agents/lifecycle_test.go: tests para Agent.Stop()/Done() verificando
  que Stop() desbloquea Run y que es seguro llamarlo múltiples veces o
  con cancel nil.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-08 18:43:46 +00:00
egutierrez 8ec9f39b6d feat: agentctl reload — subcomando de hot-reload via SIGHUP
Nuevo subcomando: agentctl reload [agent-id]

- Sin argumento: elimina run/reload.txt y envía SIGHUP → todos los
  agentes se recargan.
- Con agent-id: escribe run/reload.txt con el ID y envía SIGHUP → solo
  ese agente se recarga.

Si el launcher no está corriendo, muestra error claro.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-08 18:42:38 +00:00
egutierrez 069f8758b1 feat: hot-reload de agentes individuales via SIGHUP
Implementa el mecanismo de hot-reload descrito en el issue 0013:

- agents/runtime.go: añade Agent.Stop() y Agent.Done() para ciclo de vida
  individual. Run() crea un contexto hijo cancelable y cierra el canal
  done al retornar.

- cmd/launcher/registry.go (nuevo): agentRegistry rastrea agentes vivos
  por ID. Métodos: register, stopAndWait, reload, reloadAll, waitAll,
  cleanupLogs. reload() sigue el flujo completo: stop→wait→unsubscribe
  →reload config→recreate→rewire bus/orch→start nueva goroutine.

- cmd/launcher/main.go: usa agentRegistry en lugar de sync.WaitGroup.
  Añade handler de SIGHUP en goroutine separada que lee run/reload.txt
  para determinar el agente objetivo (* o vacío = todos). Tras leer,
  borra run/reload.txt para no afectar el siguiente SIGHUP.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-08 18:41:32 +00:00
egutierrez 0eb9e8741d feat: añadir agente meteorologo con tool get_weather
Nuevo agente Matrix especializado en consultas meteorológicas.
Usa la API pública Open-Meteo (sin API key) para obtener
condiciones actuales y previsión de 3 días para cualquier ciudad.

Incluye:
- agents/meteorologo/ — reglas puras, config.yaml, system prompt
- tools/weather.go — tool get_weather (geocoding + forecast)
- Registro en runtime.go (tool registry) y launcher (rulesRegistry)

El agente responde a DMs y menciones delegando al LLM con tool_use
habilitado. No tiene comandos directos (!xxx).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 13:54:38 +00:00
egutierrez 62783f3655 fix: SQLite WAL mode y busy_timeout para evitar SQLITE_BUSY
Registra un connection hook en el driver modernc/sqlite que ejecuta
PRAGMA journal_mode=WAL y PRAGMA busy_timeout=5000 en cada conexión nueva.

Esto previene errores SQLITE_BUSY cuando múltiples goroutines escriben
concurrentemente (crypto sync de mautrix + memory store + knowledge store).

Incluye tests que verifican:
- Pragmas aplicados correctamente en cada conexión
- Escrituras concurrentes sin error (mismo sql.DB y conexiones separadas)
- Archivo -wal creado en disco confirmando WAL activo

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 01:39:57 +00:00
egutierrez 5697b92ab8 feat: integrar structured logging en todos los componentes del shell
Se propaga *slog.Logger a todos los componentes impuros del shell:
- shell/bus/ — logs de subscribe, send, reply, timeout, unsubscribe
- shell/effects/ — duración y resultado de cada action ejecutada
- shell/llm/ (anthropic, openai, factory) — request/response con tokens, duración, fallback
- shell/memory/sqlite — open, save, recall, close con detalles
- shell/ssh/ — inicio, fin, errores y duración de comandos SSH
- tools/registry — registro, ejecución y errores de herramientas

Se usa el paquete shell/logger para field names consistentes (FieldDurationMS, FieldTokensUsed, etc.).
Cada componente recibe el logger por inyección de dependencias, sin globals.
Las firmas de New/FromConfig se actualizan para aceptar *slog.Logger.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 21:53:31 +00:00
egutierrez 750e896c08 feat: integrate file logger into launcher and update log scripts
Se integra shell/logger en cmd/launcher para que cada agente escriba
sus logs en logs/<agent-id>/YYYY-MM-DD.jsonl. Nuevo flag --log-dir
(default: "logs", "stdout" para consola). El launcher y cada agente
tienen su propio logger con cleanup automático al apagar. Se actualiza
dev-scripts/logs.sh para leer desde la nueva estructura de directorios.
Se corrige .gitignore: "launcher" → "/launcher" para no ignorar cmd/launcher/,
y se añade logs/.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 17:27:24 +00:00
egutierrez 7176afde0a feat: update orchestrator for enhanced multi-bot management and room discovery 2026-03-06 17:03:08 +00:00
egutierrez 2667af52cc feat: implement multi-bot orchestration system with LLM routing
Implementa el sistema de orquestación para salas Matrix con múltiples bots.
El orquestador es un "special agent" sin identidad Matrix que coordina qué bot
responde y cuándo, usando LLM (Claude) para routing y evaluación de calidad.

Cambios principales:
- pkg/orchestration/task.go: tipos puros (TaskEvent, BotResponse, QualityScore, RoutingDecision)
- shell/orchestration/: runtime del orquestador (orchestrator.go, router.go, evaluator.go)
- agents/specials/orchestrator/: config + prompts (routing, quality, refinement)
- internal/config/: SpecialConfig, OrchestrationCfg, LoadSpecial()
- shell/bus/bus.go: protocolo request-reply (SendAndWait, Reply) para delegación
- shell/matrix/listener.go: InterceptFunc para interceptar eventos en salas orquestadas
- agents/runtime.go: SetBus, listenBus, handleTaskEvent para recibir tareas del orquestador
- cmd/launcher/main.go: creación de bus compartido, arranque del orquestador antes de bots

Incluye deduplicación para evitar que múltiples listeners en la misma sala
disparen el orquestador más de una vez por mensaje.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 09:05:42 +00:00
egutierrez 08dcb332b7 refactor: rename agent directories to match agent IDs
Renombrar directorios de agentes para que coincidan exactamente con el
agent.id del config.yaml, eliminando la disonancia entre nombres:
- agents/assistant/ → agents/assistant-bot/ (ID: assistant-bot)
- agents/asistente2/ → agents/asistente-2/ (ID: asistente-2)

Se actualizan los imports en cmd/launcher/main.go, los store_path de
crypto, los paths de storage/logs/audit en ambos configs para que
apunten a ./agents/<agent-id>/data/. También se corrige el memory.db
que se creaba en directorios fantasma fuera del directorio real del
agente.

Se eliminan las referencias a devops-bot en el config de assistant-bot
(peers, delegation).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 00:55:09 +00:00
egutierrez f2626f7007 Refactor code structure for improved readability and maintainability 2026-03-05 23:52:58 +00:00
egutierrez a92fbff801 feat: update access token environment variables and enhance device signing process for E2EE agents; add verification script and system flow documentation 2026-03-05 23:46:07 +00:00
egutierrez 0f900d1560 feat: add recovery key support for E2EE agents, including configuration and documentation updates 2026-03-05 00:56:15 +00:00
egutierrez 1e5103eb70 feat: enhance agent management with support for multiple instances and update UI accordingly 2026-03-04 23:41:26 +00:00
egutierrez dd4a101139 feat: add asistente-2 agent with tool-use and E2EE verification
Nuevo agente asistente-2 con herramienta current_time habilitada para
demostrar el flujo completo de tool-use (LLM → tool call → resultado → respuesta).

Incluye:
- agents/asistente2/: reglas puras, config con tool_use.enabled, system prompt
- tools/time.go: herramienta current_time (siempre disponible para todos los agentes)
- cmd/verify/: comando para subir cross-signing keys y eliminar el warning
  "Encrypted by a device not verified by its owner"
- Registro en runtime.go (current_time) y launcher/main.go (rulesRegistry)

El cmd/verify usa mautrix GenerateAndUploadCrossSigningKeysWithPassword
para configurar cross-signing via UIA con la password del bot.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 21:38:55 +00:00
egutierrez 150f9d2990 chore: track agentctl avatar and displayname commands
Añade avatar.go que implementa los subcomandos avatar y displayname
de agentctl. Ya existía en el proyecto pero no estaba commiteado.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 19:38:44 +00:00
egutierrez f5b857dbc6 feat: add bubbletea TUI dashboard for bot server management
Implementa un dashboard interactivo con bubbletea siguiendo el patrón
pure core / impure shell del proyecto:

- pkg/tui/ (PURE): Model, Update, View — solo fmt y strings, cero I/O.
  Update produce Intent[] (datos puros) en vez de side effects.
- shell/tui/ (IMPURE): Adapter convierte Intent[] en tea.Cmd[] con I/O real
  (process management, /proc stats, log tail).
- cmd/dashboard/ (composición): Bridge conecta pure Update con shell Adapter
  usando la Elm Architecture de bubbletea.

Pantallas: Main Menu → Agent List → Agent Actions (start/stop/restart/kill) → Logs.
Navegación: flechas ↑↓, Enter seleccionar, 0 volver, q salir.

Dependencias añadidas: bubbletea, lipgloss.
Actualiza .gitignore para anclar binarios a raíz (/agentctl, /dashboard).
Documenta nuevos scripts en CLAUDE.md.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 19:38:30 +00:00
egutierrez 00dac8b77f refactor: extract process management to shell/process package
Extrae toda la lógica de gestión de procesos (scan, start, stop, kill, stats,
log tail) de cmd/agentctl/main.go a shell/process/manager.go como paquete
reutilizable siguiendo el patrón impure shell del proyecto.

agentctl queda como thin wrapper sobre process.Manager — misma funcionalidad,
mismo comportamiento. El nuevo paquete será compartido por el TUI dashboard.

Añade funcionalidad nueva al Manager: Stats() para métricas de /proc,
LogTail() para últimas N líneas, Stop() con espera graceful + SIGKILL fallback.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 19:38:19 +00:00
egutierrez 062dac268f Refactor code structure for improved readability and maintainability 2026-03-04 19:02:34 +00:00
egutierrez 396fc39b90 bot contesta con e2ee 2026-03-04 00:59:10 +00:00
egutierrez bd8e1432e5 feat: add assistant bot with LLM integration and configuration
- Implemented the assistant bot with basic command handling and LLM routing.
- Created configuration file for the assistant bot with personality, behavior, and LLM settings.
- Added system prompt for the assistant bot to define its capabilities and limitations.
- Developed registration script for creating Matrix bot users via Synapse admin API.
- Introduced common development scripts for agent management (start, stop, list, logs).
- Scaffolded new agent creation script to streamline the addition of new agents.
- Implemented agent removal script to disable agents without deleting data.
2026-03-03 23:57:13 +00:00
egutierrez c126187c5a Repo iniciado 2026-03-03 23:19:23 +00:00