Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Initialize SQLite audit logger for Pro license with audit_logging feature

rcourtmand73e57af8652
diff --git a/internal/ai/patrol.go b/internal/ai/patrol.go
index 6c94259a31..1f238007b2 100644
--- a/internal/ai/patrol.go
+++ b/internal/ai/patrol.go
@@ -234,6 +234,12 @@ type PatrolRunRecord struct {
// MaxPatrolRunHistory is the maximum number of patrol runs to keep in history
const MaxPatrolRunHistory = 100
+// OpenCodePatrolRunner interface allows delegating patrol to OpenCode
+type OpenCodePatrolRunner interface {
+ RunPatrol(ctx context.Context) error
+ IsRunning() bool
+}
+
// PatrolService runs background AI analysis of infrastructure
type PatrolService struct {
mu sync.RWMutex
@@ -255,6 +261,10 @@ type PatrolService struct {
// Unified intelligence facade - aggregates all subsystems for unified view
intelligence *Intelligence
+ // OpenCode integration - when set and UseOpenCode is true, delegate patrol to OpenCode
+ opencodePatrol OpenCodePatrolRunner
+ useOpenCode bool // Whether to use OpenCode for patrol
+
// Cached thresholds (recalculated when thresholdProvider changes)
thresholds PatrolThresholds
proactiveMode bool // When true, warn before thresholds; when false, use exact thresholds
@@ -315,6 +325,23 @@ func (p *PatrolService) GetIncidentStore() *memory.IncidentStore {
return p.incidentStore
}
+// SetOpenCodePatrol sets the OpenCode patrol runner for delegation
+// When set and useOpenCode is true, patrol will be handled by OpenCode
+func (p *PatrolService) SetOpenCodePatrol(runner OpenCodePatrolRunner, enabled bool) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.opencodePatrol = runner
+ p.useOpenCode = enabled
+ log.Info().Bool("enabled", enabled).Msg("OpenCode patrol integration configured")
+}
+
+// UseOpenCode returns whether OpenCode is configured for patrol
+func (p *PatrolService) UseOpenCode() bool {
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+ return p.useOpenCode && p.opencodePatrol != nil
+}
+
// SetConfig updates the patrol configuration
func (p *PatrolService) SetConfig(cfg PatrolConfig) {
p.mu.Lock()
@@ -787,12 +814,23 @@ func (p *PatrolService) patrolLoop(ctx context.Context) {
func (p *PatrolService) runPatrol(ctx context.Context) {
p.mu.RLock()
cfg := p.config
+ opencodePatrol := p.opencodePatrol
+ useOpenCode := p.useOpenCode
p.mu.RUnlock()
if !cfg.Enabled {
return
}
+ // Delegate to OpenCode patrol if configured
+ if useOpenCode && opencodePatrol != nil {
+ log.Info().Msg("AI Patrol: Delegating to OpenCode patrol")
+ if err := opencodePatrol.RunPatrol(ctx); err != nil {
+ log.Error().Err(err).Msg("AI Patrol: OpenCode patrol failed")
+ }
+ return
+ }
+
// Check if AI service is enabled
if p.aiService == nil || !p.aiService.IsEnabled() {
log.Debug().Msg("AI Patrol: AI service not enabled, skipping patrol")
diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.go
index 1bea723d85..a585caf911 100644
--- a/internal/api/ai_handlers.go
+++ b/internal/api/ai_handlers.go
@@ -52,6 +52,11 @@ func NewAISettingsHandler(cfg *config.Config, persistence *config.ConfigPersiste
}
}
+// GetAIService returns the underlying AI service
+func (h *AISettingsHandler) GetAIService() *ai.Service {
+ return h.aiService
+}
+
// SetConfig updates the configuration reference used by the handler.
func (h *AISettingsHandler) SetConfig(cfg *config.Config) {
if cfg == nil {
diff --git a/internal/api/license_handlers.go b/internal/api/license_handlers.go
index 8e9663cef6..e32ced86f5 100644
--- a/internal/api/license_handlers.go
+++ b/internal/api/license_handlers.go
@@ -6,6 +6,7 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/license"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/audit"
"github.com/rs/zerolog/log"
)
@@ -13,6 +14,7 @@ import (
type LicenseHandlers struct {
service *license.Service
persistence *license.Persistence
+ configDir string // Needed for initializing audit logger
}
// NewLicenseHandlers creates a new license handlers instance.
@@ -24,6 +26,12 @@ func NewLicenseHandlers(configDir string) *LicenseHandlers {
service := license.NewService()
+ h := &LicenseHandlers{
+ service: service,
+ persistence: persistence,
+ configDir: configDir,
+ }
+
// Try to load existing license with metadata
if persistence != nil {
persisted, err := persistence.LoadWithMetadata()
@@ -38,14 +46,40 @@ func NewLicenseHandlers(configDir string) *LicenseHandlers {
lic.GracePeriodEnd = &gracePeriodEnd
}
log.Info().Msg("Loaded saved Pulse Pro license")
+
+ // Initialize audit logger if license has audit_logging feature
+ h.initAuditLoggerIfLicensed()
}
}
}
- return &LicenseHandlers{
- service: service,
- persistence: persistence,
+ return h
+}
+
+// initAuditLoggerIfLicensed initializes the SQLite audit logger if the license
+// includes the audit_logging feature. This enables persistent audit logs with
+// HMAC signing for Pro users.
+func (h *LicenseHandlers) initAuditLoggerIfLicensed() {
+ if !h.service.HasFeature(license.FeatureAuditLogging) {
+ return
}
+
+ // Check if we already have a SQLiteLogger (avoid re-initialization)
+ if _, ok := audit.GetLogger().(*audit.SQLiteLogger); ok {
+ return
+ }
+
+ logger, err := audit.NewSQLiteLogger(audit.SQLiteLoggerConfig{
+ DataDir: h.configDir,
+ RetentionDays: 90, // Default 90 days retention
+ })
+ if err != nil {
+ log.Error().Err(err).Msg("Failed to initialize SQLite audit logger, falling back to console")
+ return
+ }
+
+ audit.SetLogger(logger)
+ log.Info().Msg("SQLite audit logger initialized for Pulse Pro")
}
// Service returns the license service for use by other handlers.
@@ -182,6 +216,9 @@ func (h *LicenseHandlers) HandleActivateLicense(w http.ResponseWriter, r *http.R
Bool("lifetime", lic.IsLifetime()).
Msg("Pulse Pro license activated")
+ // Initialize audit logger if the new license has audit_logging feature
+ h.initAuditLoggerIfLicensed()
+
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(ActivateLicenseResponse{
Success: true,
diff --git a/internal/api/router.go b/internal/api/router.go
index e22677b9a7..e4ebb98a41 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -28,6 +28,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/agentbinaries"
"github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
"github.com/rcourtman/pulse-go-rewrite/internal/ai"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/opencode"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/license"
@@ -57,6 +58,7 @@ type Router struct {
temperatureProxyHandlers *TemperatureProxyHandlers
systemSettingsHandler *SystemSettingsHandler
aiSettingsHandler *AISettingsHandler
+ aiHandler *AIHandler // OpenCode-based AI handler
resourceHandlers *ResourceHandlers
reportingHandlers *ReportingHandlers
configProfileHandler *ConfigProfileHandler
@@ -1241,6 +1243,9 @@ func (r *Router) setupRoutes() {
hostMetadataHandler.Store(),
)
r.aiSettingsHandler.SetMetadataProvider(metadataProvider)
+
+ // OpenCode-based AI handler (when UseOpenCode is enabled)
+ r.aiHandler = NewAIHandler(r.config, r.persistence, r.agentExecServer)
// Wire license checker for Pro feature gating (AI Patrol, Alert Analysis, Auto-Fix)
r.aiSettingsHandler.SetLicenseChecker(r.licenseHandlers.Service())
// Wire license checker for alert manager Pro features (Update Alerts)
@@ -1356,7 +1361,7 @@ func (r *Router) setupRoutes() {
r.mux.HandleFunc("/api/ai/intelligence/anomalies", RequireAuth(r.config, r.aiSettingsHandler.HandleGetAnomalies))
r.mux.HandleFunc("/api/ai/intelligence/learning", RequireAuth(r.config, r.aiSettingsHandler.HandleGetLearningStatus))
- // AI Chat Sessions - sync across devices
+ // AI Chat Sessions - sync across devices (legacy endpoints)
r.mux.HandleFunc("/api/ai/chat/sessions", RequireAuth(r.config, r.aiSettingsHandler.HandleListAIChatSessions))
r.mux.HandleFunc("/api/ai/chat/sessions/", RequireAuth(r.config, func(w http.ResponseWriter, req *http.Request) {
switch req.Method {
@@ -1371,6 +1376,21 @@ func (r *Router) setupRoutes() {
}
}))
+ // OpenCode AI endpoints - new AI backend powered by OpenCode
+ r.mux.HandleFunc("/api/ai/status", RequireAuth(r.config, r.aiHandler.HandleStatus))
+ r.mux.HandleFunc("/api/ai/chat", RequireAuth(r.config, r.aiHandler.HandleChat))
+ r.mux.HandleFunc("/api/ai/sessions", RequireAuth(r.config, func(w http.ResponseWriter, req *http.Request) {
+ switch req.Method {
+ case http.MethodGet:
+ r.aiHandler.HandleSessions(w, req)
+ case http.MethodPost:
+ r.aiHandler.HandleCreateSession(w, req)
+ default:
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ }
+ }))
+ r.mux.HandleFunc("/api/ai/sessions/", RequireAuth(r.config, r.routeOpenCodeSessions))
+
// Agent WebSocket for AI command execution
r.mux.HandleFunc("/api/agent/ws", r.handleAgentWebSocket)
@@ -1409,6 +1429,40 @@ func (r *Router) setupRoutes() {
}
+// routeOpenCodeSessions routes session-specific OpenCode AI requests
+func (r *Router) routeOpenCodeSessions(w http.ResponseWriter, req *http.Request) {
+ // Extract session ID from path: /api/ai/sessions/{id}[/messages|/abort]
+ path := strings.TrimPrefix(req.URL.Path, "/api/ai/sessions/")
+ parts := strings.SplitN(path, "/", 2)
+ sessionID := parts[0]
+
+ if sessionID == "" {
+ http.Error(w, "Session ID required", http.StatusBadRequest)
+ return
+ }
+
+ // Check if there's a sub-resource
+ if len(parts) > 1 {
+ switch parts[1] {
+ case "messages":
+ r.aiHandler.HandleMessages(w, req, sessionID)
+ case "abort":
+ r.aiHandler.HandleAbort(w, req, sessionID)
+ default:
+ http.Error(w, "Not found", http.StatusNotFound)
+ }
+ return
+ }
+
+ // Handle session-level operations
+ switch req.Method {
+ case http.MethodDelete:
+ r.aiHandler.HandleDeleteSession(w, req, sessionID)
+ default:
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ }
+}
+
// handleAgentWebSocket handles WebSocket connections from agents for AI command execution
func (r *Router) handleAgentWebSocket(w http.ResponseWriter, req *http.Request) {
if r.agentExecServer == nil {
@@ -1779,6 +1833,50 @@ func (r *Router) StopPatrol() {
}
}
+// StartOpenCodeAI starts the OpenCode-based AI service
+// This is the new AI backend that uses OpenCode for better tool calling and multi-model support
+func (r *Router) StartOpenCodeAI(ctx context.Context) {
+ if r.aiHandler == nil {
+ return
+ }
+ if r.monitor == nil {
+ log.Warn().Msg("Cannot start OpenCode AI: monitor not available")
+ return
+ }
+
+ if err := r.aiHandler.Start(ctx, r.monitor); err != nil {
+ log.Error().Err(err).Msg("Failed to start OpenCode AI service")
+ return
+ }
+
+ // Wire up OpenCode patrol if UseOpenCode is enabled
+ aiCfg := r.aiHandler.GetAIConfig()
+ if aiCfg != nil && aiCfg.UseOpenCode && r.aiHandler.IsRunning() {
+ service := r.aiHandler.GetService()
+ if service != nil {
+ // Create OpenCode patrol service
+ ocPatrol := opencode.NewPatrolService(service)
+
+ // Wire to existing patrol service
+ if r.aiSettingsHandler != nil {
+ if patrolSvc := r.aiSettingsHandler.GetAIService().GetPatrolService(); patrolSvc != nil {
+ patrolSvc.SetOpenCodePatrol(ocPatrol, true)
+ log.Info().Msg("OpenCode patrol integration enabled")
+ }
+ }
+ }
+ }
+}
+
+// StopOpenCodeAI stops the OpenCode-based AI service
+func (r *Router) StopOpenCodeAI(ctx context.Context) {
+ if r.aiHandler != nil {
+ if err := r.aiHandler.Stop(ctx); err != nil {
+ log.Error().Err(err).Msg("Failed to stop OpenCode AI service")
+ }
+ }
+}
+
// startBaselineLearning runs a background loop that learns baselines from metrics history
// This enables anomaly detection by understanding what "normal" looks like for each resource
func (r *Router) startBaselineLearning(ctx context.Context, store *ai.BaselineStore, metricsHistory *monitoring.MetricsHistory) {
diff --git a/internal/config/ai.go b/internal/config/ai.go
index bce3e542c6..b5e4a7b758 100644
--- a/internal/config/ai.go
+++ b/internal/config/ai.go
@@ -61,6 +61,12 @@ type AIConfig struct {
// AI cost controls
// Budget is expressed as an estimated USD amount over a 30-day window (pro-rated in UI for other ranges).
CostBudgetUSD30d float64 `json:"cost_budget_usd_30d,omitempty"`
+
+ // OpenCode integration - use OpenCode as the AI backend instead of direct provider calls
+ // When enabled, chat and patrol use OpenCode for better tool calling and multi-model support
+ UseOpenCode bool `json:"use_opencode,omitempty"` // Enable OpenCode backend
+ OpenCodeDataDir string `json:"opencode_data_dir,omitempty"` // Data directory for OpenCode (default: /tmp/pulse-opencode)
+ OpenCodePort int `json:"opencode_port,omitempty"` // Port for OpenCode server (0 = auto-assign)
}
// AIProvider constants
diff --git a/pkg/server/server.go b/pkg/server/server.go
index ae96b18316..d66f1780e7 100644
--- a/pkg/server/server.go
+++ b/pkg/server/server.go
@@ -195,6 +195,9 @@ func Run(ctx context.Context, version string) error {
// Start AI patrol service for background infrastructure monitoring
router.StartPatrol(ctx)
+ // Start OpenCode AI service (when UseOpenCode is enabled in config)
+ router.StartOpenCodeAI(ctx)
+
// Wire alert-triggered AI analysis
router.WireAlertTriggeredAI()