# ============================================
# AGENTE PLANTILLA
# ============================================
# Este archivo sirve como referencia canonica para la configuracion de todos los agentes.
# NO se lanza (template: true). Copiar y adaptar para crear nuevos agentes.

agent:
  id: "_template"
  name: "Template Agent"
  version: "0.0.0"
  enabled: true
  template: true          # el launcher ignora este agente
  description: "Agente plantilla. No se lanza. Sirve como referencia para crear nuevos agentes."
  tags: [template]

# ============================================
# PERSONALIDAD Y COMPORTAMIENTO
# ============================================
personality:
  # --- Identidad narrativa ---
  role: "asistente general"
  backstory: "Un asistente amigable creado para ayudar con tareas cotidianas."
  expertise: [general]
  limitations: []

  # --- Estilo basico ---
  tone: friendly              # direct | friendly | formal | casual | technical
  verbosity: concise          # minimal | concise | detailed | verbose
  language: es
  languages_supported: [es, en]
  emoji_style: minimal        # none | minimal | moderate | heavy
  prefix: ""
  error_style: helpful        # terse | helpful | detailed

  # --- Comunicacion avanzada ---
  communication:
    formality: semiformal     # formal | semiformal | casual | coloquial
    humor: none               # none | subtle | moderate | frequent
    personality: pragmatic    # analytical | creative | pragmatic | empathetic | assertive
    response_style: structured  # structured | conversational | bullet_points | narrative
    quirks: []                # rasgos unicos del personaje
    avoid_topics: []          # temas a evitar
    catchphrases: []          # frases tipicas

  # --- Directivas libres ---
  custom_directives: []       # instrucciones extra para el system prompt

  # --- Templates de respuesta ---
  templates:
    greeting: "Hola, soy {name}. En que puedo ayudarte?"
    unknown_command: "No entiendo ese comando. Usa !help."
    permission_denied: "No tienes permiso para eso."
    error: "Algo salio mal: {{.Error}}"
    success: "{{.Summary}}"
    busy: "Estoy procesando otra solicitud, un momento..."

  # --- Comportamiento ---
  behavior:
    proactive: false
    ask_confirmation: false
    show_reasoning: false
    thread_replies: true
    typing_indicator: true
    acknowledge_receipt: false

# ============================================
# LLM — CONEXION Y RAZONAMIENTO
# ============================================
llm:
  primary:
    provider: openai          # openai | anthropic | claude-code
    model: "gpt-4o"
    api_key_env: OPENAI_API_KEY
    base_url: ""              # opcional: custom endpoint
    max_tokens: 4096
    temperature: 0.7

    # Claude Code: subproceso claude -p (solo si provider: claude-code)
    claude_code:
      binary: "claude"
      timeout: 3m
      disable_tools: false
      allowed_tools: []       # vacio = permitir todas
      disallowed_tools: []
      working_dir: ""         # default: tmpdir aislado
      permission_mode: "default"  # default | acceptEdits | bypassPermissions | plan
      model: "sonnet"         # sonnet | opus | haiku | full model name
      fallback_model: ""
      session_id: ""
      add_dirs: []

  # Fallback LLM (opcional)
  fallback:
    provider: ""
    model: ""
    api_key_env: ""
    base_url: ""
    max_tokens: 0
    temperature: 0

  reasoning:
    system_prompt_file: "prompts/system.md"  # relativo a agents/<id>/
    context_window: 16384
    memory_messages: 30      # mensajes previos a incluir en el contexto

  tool_use:
    enabled: false           # habilitar function calling
    max_iterations: 5        # ciclos tool-call → execute → feedback
    parallel_calls: false    # permitir llamadas paralelas a tools

  rate_limit:
    requests_per_minute: 60
    tokens_per_minute: 200000
    concurrent_requests: 5

# ============================================
# TOOLS — HERRAMIENTAS DISPONIBLES
# ============================================
tools:
  ssh:
    enabled: false
    allowed_targets: []      # lista de targets definidos en ssh.targets
    allowed_commands: []     # allowlist: si no esta vacio, solo estos comandos
    forbidden_commands: []   # blocklist
    timeout: 30s
    max_concurrent: 3
    require_confirmation: [] # comandos que necesitan confirmacion

  http:
    enabled: false
    allowed_domains: []      # si no esta vacio, solo estos dominios
    timeout: 10s
    max_retries: 2

  scripts:
    enabled: false
    scripts_dir: "./scripts"
    allowed: []              # si no esta vacio, solo estos scripts
    timeout: 60s
    sandbox: false

  file_ops:
    enabled: false
    allowed_paths: []        # si no esta vacio, solo estos paths
    read_only: true

  matrix_send:
    allowed_rooms: []        # si no esta vacio, solo enviar a estos rooms

  mcp:
    enabled: false
    servers: []              # lista de servidores MCP externos
    # Ejemplo:
    # - name: "filesystem"
    #   transport: stdio
    #   command: "npx"
    #   args: ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/data"]
    #   env: {}
    #   tools: []            # filtro: solo estas tools (vacio = todas)
    #   prefix: "fs_"        # prefijo para evitar colisiones
    #   timeout: 30s
    expose:
      port: 0                # exponer las tools propias via MCP server
      tools: []              # tools a exponer (vacio = todas)

  memory:
    enabled: false           # tool para acceder a memoria del agente

  knowledge:
    enabled: false
    dir: "./knowledge"       # knowledge privado del agente

  shared_knowledge:
    enabled: false
    dir: "knowledges"        # knowledge compartido entre agentes
    db_path: "knowledges/data/knowledge.db"

  skills:
    allowed_interpreters: ["bash", "sh"]  # interpretes permitidos para skills

# ============================================
# SKILLS — SISTEMA DE SKILLS
# ============================================
skills:
  enabled: false
  path: "skills/"            # ruta base de skills (relativa al proyecto)
  categories: []             # vacio = todas las categorias | ["devops", "system"] = filtradas
  timeout: 60s               # timeout para ejecucion de scripts

# ============================================
# MEMORIA — VENTANA DE CONVERSACION
# ============================================
memory:
  enabled: false
  window_size: 20            # mensajes por room en ventana deslizante
  db_path: ""                # default: agents/<id>/data/memory.db

# ============================================
# MATRIX — CONEXION Y ROOMS
# ============================================
matrix:
  homeserver: "https://matrix.example.com"
  user_id: "@template:matrix.example.com"
  access_token_env: MATRIX_TOKEN_TEMPLATE
  device_id: "DEVICEID"

  encryption:
    enabled: false
    store_path: "./agents/_template/data/crypto/"
    pickle_key_env: PICKLE_KEY_TEMPLATE
    trust_mode: tofu          # tofu | cross-signing | manual
    recovery_key_env: ""      # SSSS recovery key para cross-signing

  rooms:
    listen: []                # rooms donde escuchar sin responder
    respond: []               # rooms donde responder automaticamente
    admin: []                 # rooms de admin (para comandos especiales)

  filters:
    command_prefix: "!"
    mention_respond: true     # responder a menciones
    dm_respond: true          # responder a DMs
    ignore_bots: true
    ignore_users: []
    unauthorized_response: silent  # silent | explicit
    min_power_level: 0

  threads:
    enabled: true             # responder en threads si el mensaje viene de un thread
    auto_thread: false        # crear thread automatico por cada conversacion nueva

# ============================================
# COMUNICACION INTER-AGENTES
# ============================================
agents:
  peers: []
  # Ejemplo:
  # - id: other-agent
  #   capabilities: [devops, monitoring]
  #   room: "!roomid:server.com"

  delegation:
    enabled: false
    can_delegate_to: []
    can_receive_from: []
    max_delegation_depth: 1
    timeout: 30s

  protocol:
    format: json              # json | protobuf | msgpack
    channel: matrix           # matrix | grpc | channel
    heartbeat_interval: 60s

# ============================================
# SSH — INVENTARIO DE SERVIDORES
# ============================================
ssh:
  defaults:
    user: "root"
    port: 22
    key_file_env: SSH_KEY_FILE
    known_hosts: "~/.ssh/known_hosts"
    keepalive_interval: 30s
    timeout: 60s

  targets: {}
  # Ejemplo:
  # prod-web:
  #   hosts: ["web01.example.com", "web02.example.com"]
  #   user: "deploy"
  #   port: 22
  #   key_file_env: SSH_KEY_PROD
  # bastion:
  #   hosts: ["bastion.example.com"]
  #   user: "admin"

# ============================================
# PERMISOS Y SEGURIDAD
# ============================================
security:
  # Nota: roles/audit/secrets aqui son legacy. Usar security/ centralizado.

  audit:
    enabled: false
    log_file: "./agents/_template/data/audit.log"
    log_to_room: ""
    include: []

  secrets:
    provider: env             # env | vault | sops

  # Sanitizacion de prompts (deteccion de injection)
  sanitize:
    enabled: false
    mode: warn                # warn | strip | reject
    min_severity: medium      # low | medium | high
    disabled_patterns: []

  # Rate limiting de tools por room
  tool_rate_limit:
    enabled: false
    max_calls_per_min: 10
    cleanup_interval_s: 60

# ============================================
# SCHEDULING — AUTOMATIZACIONES CRON
# ============================================
schedules: []
# Ejemplo 1: enviar mensaje (send_message)
# - name: "buenos-dias"
#   cron: "0 9 * * 1-5"         # lunes a viernes a las 9am
#   action:
#     kind: send_message
#     message: "Buenos dias equipo!"  # inline
#     # template: "prompts/daily.md"  # o desde archivo
#   output_room: "!roomid:server.com"
#   on_failure:
#     notify_room: "!admin:server.com"
#     escalate_to: ""

# Ejemplo 2: ejecutar tool (run_tool)
# - name: "check-disk"
#   cron: "0 */6 * * *"         # cada 6 horas
#   action:
#     kind: run_tool
#     target: ssh_exec
#     command: "df -h"
#   output_room: "!ops:server.com"
#   on_failure:
#     notify_room: "!admin:server.com"

# Ejemplo 3: prompt LLM (llm_prompt)
# - name: "resumen-logs"
#   cron: "0 18 * * *"          # diario a las 6pm
#   action:
#     kind: llm_prompt
#     prompt: "Dame un resumen de los logs del dia."
#   output_room: "!ops:server.com"
#   on_failure:
#     notify_room: ""

# ============================================
# OBSERVABILIDAD
# ============================================
observability:
  logging:
    level: info               # debug | info | warn | error
    format: json              # json | text
    output: stdout            # stdout | file
    file: "./agents/_template/data/template.log"

  metrics:
    enabled: false
    port: 9090
    path: /metrics
    export: prometheus        # prometheus | datadog | ...

  health:
    enabled: true
    port: 8080
    path: /healthz

  tracing:
    enabled: false
    provider: ""              # jaeger | zipkin | datadog
    endpoint: ""

# ============================================
# RESILIENCIA
# ============================================
resilience:
  circuit_breaker:
    failure_threshold: 5      # abrir tras N fallos consecutivos
    timeout: 30s              # tiempo en open antes de half-open
    half_open_max: 2          # intentos en half-open antes de cerrar

  retry:
    max_attempts: 2
    backoff: exponential      # fixed | exponential
    initial_delay: 1s
    max_delay: 10s

  shutdown:
    timeout: 10s              # tiempo maximo para graceful shutdown
    drain_messages: true      # procesar mensajes pendientes
    save_state: false
    state_file: ""

  queue:
    enabled: true
    max_size: 100
    priority_users: []        # usuarios con prioridad

# ============================================
# ALMACENAMIENTO Y ESTADO
# ============================================
storage:
  base_path: ""               # root para datos; default: $AGENTS_DATA_DIR/<id> o agents/<id>/data

  state:
    backend: sqlite           # sqlite | redis | file
    path: "./agents/_template/data/template.db"

  cache:
    enabled: true
    backend: memory           # memory | redis
    ttl: 5m
    max_entries: 200

  history:
    backend: sqlite
    path: "./agents/_template/data/history.db"
    retention: 168h           # 7 dias
