feat: agente Telegram con IA + Coolify multi-instancia
- Coolify: soporte multi-instancia (CRUD de configs, ?config_id= en todos los endpoints, endpoints expandidos para services/databases/teams/envs) - AiConfig: campos es_agente_bot + telegram_config_id para marcar qué config de IA actúa como cerebro del bot administrador - TelegramAgentHistory + TelegramAgentAuth: historial de conversación por chat_id y whitelist de chats autorizados - Agent Engine: function calling OpenAI-compatible con 25+ herramientas (clientes, contratos, contabilidad, proyectos, tickets, tareas, Coolify multi-instancia, servidores, monitores URL) - Webhook POST /webhooks/telegram-agent/:bot_token (público, sin sesión) - API /api/v2/agent/auth y /api/v2/agent/history para administrar el agente - AutoMigrate: AiConfig, TelegramAgentHistory, TelegramAgentAuth Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
50812749ea
commit
33cfe4fdb0
+21
-1
@@ -24,7 +24,11 @@ type AiConfig struct {
|
||||
// "" = global (disponible para todos como fallback)
|
||||
// "landing" = exclusivo para Landing Generator
|
||||
// "query_runner" = exclusivo para Query Runner SQL
|
||||
Modulo string `gorm:"size:50;default:''" json:"modulo"`
|
||||
Modulo string `gorm:"size:50;default:''" json:"modulo"`
|
||||
// Agente Telegram: si EsAgenteBot=true, esta config es el cerebro del bot administrador.
|
||||
// Solo debe haber una config activa como agente a la vez.
|
||||
EsAgenteBot bool `gorm:"default:false" json:"es_agente_bot"`
|
||||
TelegramConfigID *uint `gorm:"index" json:"telegram_config_id"`
|
||||
}
|
||||
|
||||
func (AiConfig) TableName() string { return "ai_configs" }
|
||||
@@ -107,6 +111,22 @@ func GetAiConfigSelect() ([]AiConfig, error) {
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// GetAgenteBotConfig retorna la config marcada como agente Telegram, con su TelegramConfig cargada.
|
||||
func GetAgenteBotConfig() (*AiConfig, *TelegramConfig, error) {
|
||||
var ai AiConfig
|
||||
if err := app.Http.Database.DB.Where("es_agente_bot = ? AND is_active = ?", true, true).First(&ai).Error; err != nil {
|
||||
return nil, nil, fmt.Errorf("no hay agente bot configurado: %w", err)
|
||||
}
|
||||
if ai.TelegramConfigID == nil {
|
||||
return &ai, nil, fmt.Errorf("el agente no tiene bot de Telegram asignado")
|
||||
}
|
||||
tg, err := GetTelegramConfigByID(*ai.TelegramConfigID)
|
||||
if err != nil {
|
||||
return &ai, nil, fmt.Errorf("bot de Telegram no encontrado: %w", err)
|
||||
}
|
||||
return &ai, tg, nil
|
||||
}
|
||||
|
||||
// GetAiConfigForService retorna la config activa asignada al módulo indicado.
|
||||
// Lógica de prioridad:
|
||||
// 1. Config activa con modulo conteniendo service (puede ser comma-separated)
|
||||
|
||||
@@ -17,25 +17,65 @@ type CoolifyConfig struct {
|
||||
|
||||
func (CoolifyConfig) TableName() string { return "coolify_configs" }
|
||||
|
||||
// GetCoolifyConfig retorna la primera instancia activa (compatibilidad legacy).
|
||||
func GetCoolifyConfig() (*CoolifyConfig, error) {
|
||||
var cfg CoolifyConfig
|
||||
if err := app.Http.Database.DB.First(&cfg).Error; err != nil {
|
||||
if err := app.Http.Database.DB.Where("activo = ?", true).First(&cfg).Error; err != nil {
|
||||
// fallback: cualquier registro
|
||||
if err2 := app.Http.Database.DB.First(&cfg).Error; err2 != nil {
|
||||
return nil, err2
|
||||
}
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
// GetCoolifyConfigByID retorna una instancia específica.
|
||||
func GetCoolifyConfigByID(id uint) (*CoolifyConfig, error) {
|
||||
var cfg CoolifyConfig
|
||||
if err := app.Http.Database.DB.First(&cfg, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
// GetAllCoolifyConfigs retorna todas las instancias.
|
||||
func GetAllCoolifyConfigs() ([]CoolifyConfig, error) {
|
||||
var items []CoolifyConfig
|
||||
err := app.Http.Database.DB.Order("id ASC").Find(&items).Error
|
||||
return items, err
|
||||
}
|
||||
|
||||
func CreateCoolifyConfig(cfg *CoolifyConfig) error {
|
||||
return app.Http.Database.DB.Create(cfg).Error
|
||||
}
|
||||
|
||||
func UpdateCoolifyConfig(id uint, nombre, baseURL, apiToken string, activo bool) (*CoolifyConfig, error) {
|
||||
var cfg CoolifyConfig
|
||||
if err := app.Http.Database.DB.First(&cfg, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.Nombre = nombre
|
||||
cfg.BaseURL = baseURL
|
||||
if apiToken != "" {
|
||||
cfg.ApiToken = apiToken
|
||||
}
|
||||
cfg.Activo = activo
|
||||
if err := app.Http.Database.DB.Save(&cfg).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
func DeleteCoolifyConfig(id uint) error {
|
||||
return app.Http.Database.DB.Delete(&CoolifyConfig{}, id).Error
|
||||
}
|
||||
|
||||
// UpsertCoolifyConfig mantiene compatibilidad con código legado.
|
||||
func UpsertCoolifyConfig(nombre, baseURL, apiToken string, activo bool) (*CoolifyConfig, error) {
|
||||
var cfg CoolifyConfig
|
||||
err := app.Http.Database.DB.First(&cfg).Error
|
||||
if err != nil {
|
||||
// No existe → crear
|
||||
cfg = CoolifyConfig{
|
||||
Nombre: nombre,
|
||||
BaseURL: baseURL,
|
||||
ApiToken: apiToken,
|
||||
Activo: activo,
|
||||
}
|
||||
cfg = CoolifyConfig{Nombre: nombre, BaseURL: baseURL, ApiToken: apiToken, Activo: activo}
|
||||
if createErr := app.Http.Database.DB.Create(&cfg).Error; createErr != nil {
|
||||
return nil, createErr
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// TelegramAgentHistory guarda el historial de conversación por chat_id.
|
||||
// Se usan los últimos N mensajes como contexto en cada llamada al AI.
|
||||
type TelegramAgentHistory struct {
|
||||
gorm.Model
|
||||
ChatID int64 `json:"chat_id" gorm:"column:chat_id;index;not null"`
|
||||
Role string `json:"role" gorm:"column:role;not null"` // user | assistant | tool
|
||||
Content string `json:"content" gorm:"column:content;type:text;not null"`
|
||||
// ToolName y ToolResult se usan para mensajes de tipo "tool"
|
||||
ToolName string `json:"tool_name" gorm:"column:tool_name"`
|
||||
ToolResult string `json:"tool_result" gorm:"column:tool_result;type:text"`
|
||||
}
|
||||
|
||||
func (TelegramAgentHistory) TableName() string { return "telegram_agent_history" }
|
||||
|
||||
// TelegramAgentChatID guarda qué chat_ids están autorizados a usar el agente.
|
||||
type TelegramAgentAuth struct {
|
||||
gorm.Model
|
||||
ChatID int64 `json:"chat_id" gorm:"column:chat_id;uniqueIndex;not null"`
|
||||
Nombre string `json:"nombre" gorm:"column:nombre"`
|
||||
Activo bool `json:"activo" gorm:"column:activo;default:true"`
|
||||
}
|
||||
|
||||
func (TelegramAgentAuth) TableName() string { return "telegram_agent_auth" }
|
||||
|
||||
// GetAgentHistory retorna los últimos n mensajes del historial para un chat_id.
|
||||
func GetAgentHistory(chatID int64, n int) ([]TelegramAgentHistory, error) {
|
||||
var items []TelegramAgentHistory
|
||||
err := app.Http.Database.DB.
|
||||
Where("chat_id = ?", chatID).
|
||||
Order("created_at DESC").
|
||||
Limit(n).
|
||||
Find(&items).Error
|
||||
// Invertir para orden cronológico
|
||||
for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 {
|
||||
items[i], items[j] = items[j], items[i]
|
||||
}
|
||||
return items, err
|
||||
}
|
||||
|
||||
func SaveAgentMessage(chatID int64, role, content, toolName, toolResult string) error {
|
||||
msg := &TelegramAgentHistory{
|
||||
ChatID: chatID,
|
||||
Role: role,
|
||||
Content: content,
|
||||
ToolName: toolName,
|
||||
ToolResult: toolResult,
|
||||
}
|
||||
return app.Http.Database.DB.Create(msg).Error
|
||||
}
|
||||
|
||||
// ClearAgentHistory borra el historial de un chat (comando /reset).
|
||||
func ClearAgentHistory(chatID int64) error {
|
||||
return app.Http.Database.DB.Where("chat_id = ?", chatID).Delete(&TelegramAgentHistory{}).Error
|
||||
}
|
||||
|
||||
// IsAgentAuthChat verifica si un chat_id está autorizado.
|
||||
func IsAgentAuthChat(chatID int64) bool {
|
||||
var auth TelegramAgentAuth
|
||||
err := app.Http.Database.DB.Where("chat_id = ? AND activo = ?", chatID, true).First(&auth).Error
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func GetAllAgentAuth() ([]TelegramAgentAuth, error) {
|
||||
var items []TelegramAgentAuth
|
||||
err := app.Http.Database.DB.Order("created_at DESC").Find(&items).Error
|
||||
return items, err
|
||||
}
|
||||
|
||||
func CreateAgentAuth(chatID int64, nombre string) error {
|
||||
auth := &TelegramAgentAuth{ChatID: chatID, Nombre: nombre, Activo: true}
|
||||
return app.Http.Database.DB.Create(auth).Error
|
||||
}
|
||||
|
||||
func DeleteAgentAuth(id uint) error {
|
||||
return app.Http.Database.DB.Delete(&TelegramAgentAuth{}, id).Error
|
||||
}
|
||||
Reference in New Issue
Block a user