Commit Graph

12 Commits

Author SHA1 Message Date
egutierrez 3dcd890dc9 test: tests para rate limiter y registry con rate limiting
Tests unitarios para tools/ratelimit.go:
- Allow dentro del limite, denegacion al exceder
- Keys independientes (rooms distintas no interfieren)
- Expiracion de ventana temporal
- Cleanup de entries expiradas vs activas

Tests de integracion para Registry.ExecuteForRoom:
- Rate limiting activo bloquea tras exceder limite
- Sin rate limiter todas las llamadas pasan

Parte de issue 0019c (tarea 6.5).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 19:45:47 +00:00
egutierrez 69efb6ab95 feat: rate limiting de tools por room en registry
Añade rate limiting de tool calls por room usando sliding window:

- tools/ratelimit.go: RateLimiter con sliding window per key (room),
  Allow() para verificar/registrar llamadas, Cleanup() para limpiar
  entries expiradas
- tools/registry.go: SetRateLimiter() y ExecuteForRoom() que verifica
  el rate limit antes de ejecutar, logueando tool_rate_limited si excede
- internal/config/schema.go: ToolRateLimitCfg en SecurityCfg con
  enabled, max_calls_per_min y cleanup_interval_s
- agents/runtime.go: inicializa rate limiter desde config y arranca
  goroutine de cleanup periodico
- agents/commands.go: usa ExecuteForRoom en !tool command

Config YAML:
  security:
    tool_rate_limit:
      enabled: true
      max_calls_per_min: 10

Parte de issue 0019c (prompt injection hardening — rate limiting).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 19:45:41 +00:00
egutierrez f875a98acf test: tests para hardening de tools (file, ssh, http, matrix)
40 tests cubriendo:
- file: deny-by-default, path traversal, symlink escape, prefix confusion
- ssh: allowlist, blocklist, sintaxis shell (pipes, subshells, redirects)
- http: SSRF (loopback, IPs privadas, link-local, metadata), dominios
- matrix: room authorization allowlist

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 19:17:05 +00:00
egutierrez 4e7aa95adb feat: hardening de tools — deny-by-default, SSRF, path traversal, allowlists
Cambios de seguridad en las 4 herramientas de agentes:

- tools/file: deny-by-default (AllowedPaths vacío = todo denegado),
  resolución de symlinks con EvalSymlinks, protección contra path
  traversal (../) y confusión de prefijos (/opt vs /opt1234)
- tools/ssh: nuevo AllowedCommands allowlist (complementa ForbiddenCommands),
  validación de sintaxis shell (bloquea pipes, subshells, redirects, chains)
- tools/http: protección SSRF bloqueando IPs privadas, loopback, link-local,
  metadata (169.254.169.254). Validación de dominio case-insensitive.
- tools/matrix: nuevo parámetro AllowedRooms para restringir rooms destino
- internal/config/schema: AllowedCommands en SSHToolCfg, MatrixToolCfg nueva
- agents/runtime: pasa MatrixToolCfg al constructor de matrix_send

Parte de issue 0019 (prompt injection hardening). Feature flag OFF.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 19:17:00 +00:00
egutierrez 8d89a762fb refactor: mover tools a subpackages individuales
Cada tool ahora vive en su propio subpackage dentro de tools/ (clock, file,
http, knowledgetools, matrix, memorytools, ssh, weather) en lugar de archivos
planos en el paquete raíz tools/. Esto mejora la organización, permite imports
selectivos y reduce acoplamiento entre tools. El paquete tools/ raíz conserva
los tipos base (Def, Param, Result, ToolFunc, Tool, Registry).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 17:16:45 +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 828eb175fe feat: renderizar Markdown a HTML en mensajes Matrix con goldmark
Se reemplaza SendText por SendMarkdown en todos los puntos donde el agente
envía respuestas: runtime.go (comandos built-in y tareas orquestadas),
effects/runner.go (acciones Reply) y tools/matrix.go (matrix_send tool).

shell/matrix/client.go ahora usa goldmark para convertir Markdown a HTML real
en el campo FormattedBody del evento Matrix, cumpliendo con la spec de Matrix
para mensajes formateados. El Body conserva el markdown raw como fallback.

Se añade dependencia github.com/yuin/goldmark v1.7.16.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 02:21:06 +00:00
egutierrez 69607b3a65 feat: añadir sistema de knowledge por agente
Implementa una base de conocimiento persistente por agente siguiendo
el patrón pure core / impure shell:

- pkg/knowledge/: tipos puros (Document, Store interface)
- shell/knowledge/: FileStore con SQLite para indexación y archivos .md
- tools/knowledge.go: 4 tools LLM (search, read, write, list)
- tools/knowledge_test.go: tests unitarios de las tools
- internal/config/schema.go: nuevo KnowledgeToolCfg en ToolsCfg
- agents/runtime.go: inicialización del store y registro de tools
- agents/*/knowledge/about-me.md: documentos semilla para cada agente

Cada agente puede buscar, leer, crear y actualizar documentos de
conocimiento. Los archivos .md viven en agents/<id>/knowledge/ y se
indexan en SQLite (agents/<id>/data/knowledge.db).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 23:02:39 +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 cb9489e633 feat: implement memory management system with SQLite persistence, including conversation windows and episodic facts 2026-03-06 00:39:22 +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 0f8d2f9ca0 feat: implement tool registry and add various tools for HTTP, file operations, SSH, and Matrix messaging 2026-03-04 21:10:29 +00:00