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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
feat(mcp): expand MCP tools and add session management APIs
rcourtman4cea85ec97c7
diff --git a/internal/ai/mcp/adapters.go b/internal/ai/mcp/adapters.goindex 91e7dd6d8e..385cde9727 100644--- a/internal/ai/mcp/adapters.go+++ b/internal/ai/mcp/adapters.go@@ -1,9 +1,18 @@package mcpimport (+ "fmt"+ "time"+"github.com/rcourtman/pulse-go-rewrite/internal/alerts"+ "github.com/rcourtman/pulse-go-rewrite/internal/models")+// StateGetter provides access to the current infrastructure state+type StateGetter interface {+ GetState() models.StateSnapshot+}+// AlertManagerMCPAdapter adapts alerts.Manager to MCP AlertProvider interfacetype AlertManagerMCPAdapter struct {manager AlertManager@@ -47,3 +56,546 @@ func (a *AlertManagerMCPAdapter) GetActiveAlerts() []ActiveAlert {return result}++// StorageMCPAdapter adapts the monitor state to MCP StorageProvider interface+type StorageMCPAdapter struct {+ stateGetter StateGetter+}++// NewStorageMCPAdapter creates a new adapter for storage data+func NewStorageMCPAdapter(stateGetter StateGetter) *StorageMCPAdapter {+ if stateGetter == nil {+ return nil+ }+ return &StorageMCPAdapter{stateGetter: stateGetter}+}++// GetStorage implements mcp.StorageProvider+func (a *StorageMCPAdapter) GetStorage() []models.Storage {+ if a.stateGetter == nil {+ return nil+ }+ state := a.stateGetter.GetState()+ return state.Storage+}++// GetCephClusters implements mcp.StorageProvider+func (a *StorageMCPAdapter) GetCephClusters() []models.CephCluster {+ if a.stateGetter == nil {+ return nil+ }+ state := a.stateGetter.GetState()+ return state.CephClusters+}++// BackupMCPAdapter adapts the monitor state to MCP BackupProvider interface+type BackupMCPAdapter struct {+ stateGetter StateGetter+}++// NewBackupMCPAdapter creates a new adapter for backup data+func NewBackupMCPAdapter(stateGetter StateGetter) *BackupMCPAdapter {+ if stateGetter == nil {+ return nil+ }+ return &BackupMCPAdapter{stateGetter: stateGetter}+}++// GetBackups implements mcp.BackupProvider+func (a *BackupMCPAdapter) GetBackups() models.Backups {+ if a.stateGetter == nil {+ return models.Backups{}+ }+ state := a.stateGetter.GetState()+ return state.Backups+}++// GetPBSInstances implements mcp.BackupProvider+func (a *BackupMCPAdapter) GetPBSInstances() []models.PBSInstance {+ if a.stateGetter == nil {+ return nil+ }+ state := a.stateGetter.GetState()+ return state.PBSInstances+}++// DiskHealthMCPAdapter adapts the monitor state to MCP DiskHealthProvider interface+type DiskHealthMCPAdapter struct {+ stateGetter StateGetter+}++// NewDiskHealthMCPAdapter creates a new adapter for disk health data+func NewDiskHealthMCPAdapter(stateGetter StateGetter) *DiskHealthMCPAdapter {+ if stateGetter == nil {+ return nil+ }+ return &DiskHealthMCPAdapter{stateGetter: stateGetter}+}++// GetHosts implements mcp.DiskHealthProvider+func (a *DiskHealthMCPAdapter) GetHosts() []models.Host {+ if a.stateGetter == nil {+ return nil+ }+ state := a.stateGetter.GetState()+ return state.Hosts+}++// RawMetricPoint represents a single metric value at a point in time+type RawMetricPoint struct {+ Value float64+ Timestamp time.Time+}++// MetricsSource provides access to historical metrics data+type MetricsSource interface {+ GetGuestMetrics(guestID string, metricType string, duration time.Duration) []RawMetricPoint+ GetNodeMetrics(nodeID string, metricType string, duration time.Duration) []RawMetricPoint+ GetAllGuestMetrics(guestID string, duration time.Duration) map[string][]RawMetricPoint+}++// MetricsHistoryMCPAdapter adapts the metrics history to MCP MetricsHistoryProvider interface+type MetricsHistoryMCPAdapter struct {+ stateGetter StateGetter+ metricsSource MetricsSource+}++// NewMetricsHistoryMCPAdapter creates a new adapter for metrics history+func NewMetricsHistoryMCPAdapter(stateGetter StateGetter, metricsSource MetricsSource) *MetricsHistoryMCPAdapter {+ if stateGetter == nil || metricsSource == nil {+ return nil+ }+ return &MetricsHistoryMCPAdapter{+ stateGetter: stateGetter,+ metricsSource: metricsSource,+ }+}++// GetResourceMetrics implements mcp.MetricsHistoryProvider+func (a *MetricsHistoryMCPAdapter) GetResourceMetrics(resourceID string, period time.Duration) ([]MetricPoint, error) {+ if a.metricsSource == nil {+ return nil, nil+ }++ // Try guest metrics first (VMs and containers)+ allMetrics := a.metricsSource.GetAllGuestMetrics(resourceID, period)+ if len(allMetrics) == 0 {+ // Try node metrics+ cpuPoints := a.metricsSource.GetNodeMetrics(resourceID, "cpu", period)+ memPoints := a.metricsSource.GetNodeMetrics(resourceID, "memory", period)+ if len(cpuPoints) > 0 || len(memPoints) > 0 {+ allMetrics = map[string][]RawMetricPoint{+ "cpu": cpuPoints,+ "memory": memPoints,+ }+ }+ }++ if len(allMetrics) == 0 {+ return nil, nil+ }++ // Merge metrics by timestamp+ return mergeMetricsByTimestamp(allMetrics), nil+}++// GetAllMetricsSummary implements mcp.MetricsHistoryProvider+func (a *MetricsHistoryMCPAdapter) GetAllMetricsSummary(period time.Duration) (map[string]ResourceMetricsSummary, error) {+ if a.stateGetter == nil || a.metricsSource == nil {+ return nil, nil+ }++ state := a.stateGetter.GetState()+ result := make(map[string]ResourceMetricsSummary)++ // Process VMs+ for _, vm := range state.VMs {+ vmID := fmt.Sprintf("%d", vm.VMID)+ if summary := a.computeSummary(vmID, vm.Name, "vm", period); summary != nil {+ result[vmID] = *summary+ }+ }++ // Process containers+ for _, ct := range state.Containers {+ ctID := fmt.Sprintf("%d", ct.VMID)+ if summary := a.computeSummary(ctID, ct.Name, "container", period); summary != nil {+ result[ctID] = *summary+ }+ }++ // Process nodes+ for _, node := range state.Nodes {+ if summary := a.computeSummary(node.ID, node.Name, "node", period); summary != nil {+ result[node.ID] = *summary+ }+ }++ return result, nil+}++func (a *MetricsHistoryMCPAdapter) computeSummary(resourceID, resourceName, resourceType string, period time.Duration) *ResourceMetricsSummary {+ var cpuPoints, memPoints []RawMetricPoint++ if resourceType == "node" {+ cpuPoints = a.metricsSource.GetNodeMetrics(resourceID, "cpu", period)+ memPoints = a.metricsSource.GetNodeMetrics(resourceID, "memory", period)+ } else {+ cpuPoints = a.metricsSource.GetGuestMetrics(resourceID, "cpu", period)+ memPoints = a.metricsSource.GetGuestMetrics(resourceID, "memory", period)+ }++ if len(cpuPoints) == 0 && len(memPoints) == 0 {+ return nil+ }++ summary := &ResourceMetricsSummary{+ ResourceID: resourceID,+ ResourceName: resourceName,+ ResourceType: resourceType,+ Trend: "stable",+ }++ if len(cpuPoints) > 0 {+ summary.AvgCPU, summary.MaxCPU = computeStats(cpuPoints)+ summary.Trend = computeTrend(cpuPoints)+ }+ if len(memPoints) > 0 {+ summary.AvgMemory, summary.MaxMemory = computeStats(memPoints)+ }++ return summary+}++func mergeMetricsByTimestamp(allMetrics map[string][]RawMetricPoint) []MetricPoint {+ // Build a map of timestamp -> MetricPoint+ pointsByTime := make(map[int64]*MetricPoint)++ for metricType, points := range allMetrics {+ for _, p := range points {+ ts := p.Timestamp.Unix()+ if _, exists := pointsByTime[ts]; !exists {+ pointsByTime[ts] = &MetricPoint{Timestamp: p.Timestamp}+ }+ switch metricType {+ case "cpu":+ pointsByTime[ts].CPU = p.Value+ case "memory":+ pointsByTime[ts].Memory = p.Value+ case "disk":+ pointsByTime[ts].Disk = p.Value+ }+ }+ }++ // Convert to slice and sort by timestamp+ result := make([]MetricPoint, 0, len(pointsByTime))+ for _, p := range pointsByTime {+ result = append(result, *p)+ }++ return result+}++func computeStats(points []RawMetricPoint) (avg, max float64) {+ if len(points) == 0 {+ return 0, 0+ }++ var sum float64+ for _, p := range points {+ sum += p.Value+ if p.Value > max {+ max = p.Value+ }+ }+ avg = sum / float64(len(points))+ return avg, max+}++func computeTrend(points []RawMetricPoint) string {+ if len(points) < 2 {+ return "stable"+ }++ // Compare first quarter average to last quarter average+ quarter := len(points) / 4+ if quarter < 1 {+ quarter = 1+ }++ var firstSum, lastSum float64+ for i := 0; i < quarter; i++ {+ firstSum += points[i].Value+ }+ for i := len(points) - quarter; i < len(points); i++ {+ lastSum += points[i].Value+ }++ firstAvg := firstSum / float64(quarter)+ lastAvg := lastSum / float64(quarter)++ diff := lastAvg - firstAvg+ threshold := 5.0 // 5% change threshold++ if diff > threshold {+ return "growing"+ } else if diff < -threshold {+ return "declining"+ }+ return "stable"+}++// ========== Baseline Provider Adapter ==========++// BaselineSource provides access to baseline data+type BaselineSource interface {+ GetBaseline(resourceID, metric string) (mean, stddev float64, sampleCount int, ok bool)+ GetAllBaselines() map[string]map[string]BaselineData+}++// BaselineData represents baseline data from the source+type BaselineData struct {+ Mean float64+ StdDev float64+ SampleCount int+}++// BaselineMCPAdapter adapts baseline.Store to MCP BaselineProvider interface+type BaselineMCPAdapter struct {+ source BaselineSource+}++// NewBaselineMCPAdapter creates a new adapter for baseline data+func NewBaselineMCPAdapter(source BaselineSource) *BaselineMCPAdapter {+ if source == nil {+ return nil+ }+ return &BaselineMCPAdapter{source: source}+}++// GetBaseline implements mcp.BaselineProvider+func (a *BaselineMCPAdapter) GetBaseline(resourceID, metric string) *MetricBaseline {+ if a.source == nil {+ return nil+ }++ mean, stddev, _, ok := a.source.GetBaseline(resourceID, metric)+ if !ok {+ return nil+ }++ return &MetricBaseline{+ Mean: mean,+ StdDev: stddev,+ Min: mean - 2*stddev, // Approximate+ Max: mean + 2*stddev, // Approximate+ }+}++// GetAllBaselines implements mcp.BaselineProvider+func (a *BaselineMCPAdapter) GetAllBaselines() map[string]map[string]*MetricBaseline {+ if a.source == nil {+ return nil+ }++ sourceData := a.source.GetAllBaselines()+ if sourceData == nil {+ return nil+ }++ result := make(map[string]map[string]*MetricBaseline)+ for resourceID, metrics := range sourceData {+ result[resourceID] = make(map[string]*MetricBaseline)+ for metric, data := range metrics {+ result[resourceID][metric] = &MetricBaseline{+ Mean: data.Mean,+ StdDev: data.StdDev,+ Min: data.Mean - 2*data.StdDev,+ Max: data.Mean + 2*data.StdDev,+ }+ }+ }++ return result+}++// ========== Pattern Provider Adapter ==========++// PatternSource provides access to pattern and prediction data+type PatternSource interface {+ GetPatterns() []PatternData+ GetPredictions() []PredictionData+}++// PatternData represents pattern data from the source+type PatternData struct {+ ResourceID string+ PatternType string+ Description string+ Confidence float64+ LastSeen time.Time+}++// PredictionData represents prediction data from the source+type PredictionData struct {+ ResourceID string+ IssueType string+ PredictedTime time.Time+ Confidence float64+ Recommendation string+}++// PatternMCPAdapter adapts patterns.Detector to MCP PatternProvider interface+type PatternMCPAdapter struct {+ source PatternSource+ stateGetter StateGetter+}++// NewPatternMCPAdapter creates a new adapter for pattern data+func NewPatternMCPAdapter(source PatternSource, stateGetter StateGetter) *PatternMCPAdapter {+ if source == nil {+ return nil+ }+ return &PatternMCPAdapter{source: source, stateGetter: stateGetter}+}++// GetPatterns implements mcp.PatternProvider+func (a *PatternMCPAdapter) GetPatterns() []Pattern {+ if a.source == nil {+ return nil+ }++ sourcePatterns := a.source.GetPatterns()+ if sourcePatterns == nil {+ return nil+ }++ result := make([]Pattern, 0, len(sourcePatterns))+ for _, p := range sourcePatterns {+ result = append(result, Pattern{+ ResourceID: p.ResourceID,+ ResourceName: a.getResourceName(p.ResourceID),+ PatternType: p.PatternType,+ Description: p.Description,+ Confidence: p.Confidence,+ LastSeen: p.LastSeen,+ })+ }++ return result+}++// GetPredictions implements mcp.PatternProvider+func (a *PatternMCPAdapter) GetPredictions() []Prediction {+ if a.source == nil {+ return nil+ }++ sourcePredictions := a.source.GetPredictions()+ if sourcePredictions == nil {+ return nil+ }++ result := make([]Prediction, 0, len(sourcePredictions))+ for _, p := range sourcePredictions {+ result = append(result, Prediction{+ ResourceID: p.ResourceID,+ ResourceName: a.getResourceName(p.ResourceID),+ IssueType: p.IssueType,+ PredictedTime: p.PredictedTime,+ Confidence: p.Confidence,+ Recommendation: p.Recommendation,+ })+ }++ return result+}++func (a *PatternMCPAdapter) getResourceName(resourceID string) string {+ if a.stateGetter == nil {+ return resourceID+ }+ state := a.stateGetter.GetState()+ for _, vm := range state.VMs {+ if fmt.Sprintf("%d", vm.VMID) == resourceID {+ return vm.Name+ }+ }+ for _, ct := range state.Containers {+ if fmt.Sprintf("%d", ct.VMID) == resourceID {+ return ct.Name+ }+ }+ for _, node := range state.Nodes {+ if node.ID == resourceID {+ return node.Name+ }+ }+ return resourceID+}++// ========== Findings Manager Adapter ==========++// FindingsManagerSource provides findings management operations+type FindingsManagerSource interface {+ ResolveFinding(findingID, note string) error+ DismissFinding(findingID, reason, note string) error+}++// FindingsManagerMCPAdapter adapts PatrolService to MCP FindingsManager interface+type FindingsManagerMCPAdapter struct {+ source FindingsManagerSource+}++// NewFindingsManagerMCPAdapter creates a new adapter for findings management+func NewFindingsManagerMCPAdapter(source FindingsManagerSource) *FindingsManagerMCPAdapter {+ if source == nil {+ return nil+ }+ return &FindingsManagerMCPAdapter{source: source}+}++// ResolveFinding implements mcp.FindingsManager+func (a *FindingsManagerMCPAdapter) ResolveFinding(findingID, note string) error {+ if a.source == nil {+ return fmt.Errorf("findings manager not available")+ }+ return a.source.ResolveFinding(findingID, note)+}++// DismissFinding implements mcp.FindingsManager+func (a *FindingsManagerMCPAdapter) DismissFinding(findingID, reason, note string) error {+ if a.source == nil {+ return fmt.Errorf("findings manager not available")+ }+ return a.source.DismissFinding(findingID, reason, note)+}++// ========== Metadata Updater Adapter ==========++// MetadataUpdaterSource provides metadata update operations+type MetadataUpdaterSource interface {+ SetResourceURL(resourceType, resourceID, url string) error+}++// MetadataUpdaterMCPAdapter adapts ai.Service to MCP MetadataUpdater interface+type MetadataUpdaterMCPAdapter struct {+ source MetadataUpdaterSource+}++// NewMetadataUpdaterMCPAdapter creates a new adapter for metadata updates+func NewMetadataUpdaterMCPAdapter(source MetadataUpdaterSource) *MetadataUpdaterMCPAdapter {+ if source == nil {+ return nil+ }+ return &MetadataUpdaterMCPAdapter{source: source}+}++// SetResourceURL implements mcp.MetadataUpdater+func (a *MetadataUpdaterMCPAdapter) SetResourceURL(resourceType, resourceID, url string) error {+ if a.source == nil {+ return fmt.Errorf("metadata updater not available")+ }+ return a.source.SetResourceURL(resourceType, resourceID, url)+}diff --git a/internal/ai/mcp/data_types.go b/internal/ai/mcp/data_types.goindex d637a5ebca..429ab41675 100644--- a/internal/ai/mcp/data_types.go+++ b/internal/ai/mcp/data_types.go@@ -96,11 +96,20 @@ type GuestInfo struct {// ========== JSON Response Types ==========// CapabilitiesResponse is returned by pulse_get_capabilities+// AgentInfo represents a connected execution agent+type AgentInfo struct {+ Hostname string `json:"hostname"`+ Version string `json:"version,omitempty"`+ Platform string `json:"platform,omitempty"`+ ConnectedAt string `json:"connected_at,omitempty"`+}+type CapabilitiesResponse struct {ControlLevel string `json:"control_level"`Features FeatureFlags `json:"features"`ProtectedGuests []string `json:"protected_guests,omitempty"`ConnectedAgents int `json:"connected_agents"`+ Agents []AgentInfo `json:"agents,omitempty"` // List of connected agents with hostnamesVersion string `json:"version"`}@@ -130,9 +139,10 @@ type InfrastructureResponse struct {// NodeSummary is a summarized node for list responsestype NodeSummary struct {- Name string `json:"name"`- Status string `json:"status"`- ID string `json:"id,omitempty"`+ Name string `json:"name"`+ Status string `json:"status"`+ ID string `json:"id,omitempty"`+ AgentConnected bool `json:"agent_connected"` // True if an execution agent is connected for this node}// VMSummary is a summarized VM for list responses@@ -161,6 +171,7 @@ type DockerHostSummary struct {Hostname string `json:"hostname"`DisplayName string `json:"display_name,omitempty"`ContainerCount int `json:"container_count"`+ AgentConnected bool `json:"agent_connected"` // True if an execution agent is connected for this hostContainers []DockerContainerSummary `json:"containers,omitempty"`}@@ -188,6 +199,87 @@ type PaginationInfo struct {Offset int `json:"offset"`}+// ========== Topology Response Types (Hierarchical View) ==========++// TopologyResponse provides a fully hierarchical view of infrastructure+// This is the recommended tool for understanding infrastructure relationships+type TopologyResponse struct {+ Proxmox ProxmoxTopology `json:"proxmox"`+ Docker DockerTopology `json:"docker"`+ Summary TopologySummary `json:"summary"`+}++// ProxmoxTopology shows Proxmox nodes with their nested VMs and containers+type ProxmoxTopology struct {+ Nodes []ProxmoxNodeTopology `json:"nodes"`+}++// ProxmoxNodeTopology represents a Proxmox node with its guests+type ProxmoxNodeTopology struct {+ Name string `json:"name"`+ ID string `json:"id,omitempty"`+ Status string `json:"status"`+ AgentConnected bool `json:"agent_connected"`+ CanExecute bool `json:"can_execute"` // True if commands can be executed on this node+ VMs []TopologyVM `json:"vms,omitempty"`+ Containers []TopologyLXC `json:"containers,omitempty"`+ VMCount int `json:"vm_count"`+ ContainerCount int `json:"container_count"`+}++// TopologyVM represents a VM in the topology+type TopologyVM struct {+ VMID int `json:"vmid"`+ Name string `json:"name"`+ Status string `json:"status"`+ CPU float64 `json:"cpu_percent,omitempty"`+ Memory float64 `json:"memory_percent,omitempty"`+ OS string `json:"os,omitempty"`+ Tags []string `json:"tags,omitempty"`+}++// TopologyLXC represents an LXC container in the topology+type TopologyLXC struct {+ VMID int `json:"vmid"`+ Name string `json:"name"`+ Status string `json:"status"`+ CPU float64 `json:"cpu_percent,omitempty"`+ Memory float64 `json:"memory_percent,omitempty"`+ OS string `json:"os,omitempty"`+ Tags []string `json:"tags,omitempty"`+ HasDocker bool `json:"has_docker,omitempty"` // True if Docker is installed inside this container+}++// DockerTopology shows Docker hosts with their nested containers+type DockerTopology struct {+ Hosts []DockerHostTopology `json:"hosts"`+}++// DockerHostTopology represents a Docker host with its containers+type DockerHostTopology struct {+ Hostname string `json:"hostname"`+ DisplayName string `json:"display_name,omitempty"`+ AgentConnected bool `json:"agent_connected"`+ CanExecute bool `json:"can_execute"` // True if commands can be executed on this host+ Containers []DockerContainerSummary `json:"containers,omitempty"`+ ContainerCount int `json:"container_count"`+ RunningCount int `json:"running_count"`+}++// TopologySummary provides aggregate counts and status+type TopologySummary struct {+ TotalNodes int `json:"total_nodes"`+ TotalVMs int `json:"total_vms"`+ TotalLXCContainers int `json:"total_lxc_containers"`+ TotalDockerHosts int `json:"total_docker_hosts"`+ TotalDockerContainers int `json:"total_docker_containers"`+ NodesWithAgents int `json:"nodes_with_agents"`+ DockerHostsWithAgents int `json:"docker_hosts_with_agents"`+ RunningVMs int `json:"running_vms"`+ RunningLXC int `json:"running_lxc"`+ RunningDocker int `json:"running_docker"`+}+// ResourceResponse is returned by pulse_get_resourcetype ResourceResponse struct {Type string `json:"type"` // "vm", "container", "docker"diff --git a/internal/ai/mcp/tools_control.go b/internal/ai/mcp/tools_control.goindex 64a4b87604..f585a70248 100644--- a/internal/ai/mcp/tools_control.go+++ b/internal/ai/mcp/tools_control.go@@ -17,22 +17,30 @@ import (func (e *PulseToolExecutor) registerControlTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_run_command",- Description: "Execute a shell command on Pulse-managed infrastructure. By default runs on the current target, set run_on_host=true for host commands.",+ Name: "pulse_run_command",+ Description: `Execute a shell command on infrastructure via a connected agent.++Returns: Command output (stdout/stderr) and exit code. Exit code 0 = success.++Use when: User explicitly asks to run a command, or you need to investigate something inside a system.++Do NOT use for: Checking if something is running (use pulse_get_topology), or starting/stopping VMs/containers (use pulse_control_guest or pulse_control_docker).++Important: Commands run on the HOST, not inside VMs/containers. To run inside an LXC, use: pct exec <vmid> -- <command>`,InputSchema: InputSchema{Type: "object",Properties: map[string]PropertySchema{"command": {Type: "string",- Description: "The shell command to execute",+ Description: "Shell command to execute (runs via sh -c)",},"run_on_host": {Type: "boolean",- Description: "If true, run on the host instead of inside the container/VM",+ Description: "If true, run on host. If false/omitted, runs on host anyway (use pct exec for LXC internals)",},"target_host": {Type: "string",- Description: "Optional hostname of the specific host/node to run the command on",+ Description: "Hostname to run on (e.g. 'delly'). Required if multiple agents connected.",},},Required: []string{"command"},@@ -46,23 +54,31 @@ func (e *PulseToolExecutor) registerControlTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_control_guest",- Description: "Control Proxmox VMs and LXC containers. Actions: start, stop, shutdown (graceful), restart. Requires an agent on the Proxmox host.",+ Name: "pulse_control_guest",+ Description: `Start, stop, or restart Proxmox VMs and LXC containers.++Returns: Success message with VM/container name, or error if failed.++Use when: User asks to start, stop, restart, or shutdown a VM or LXC container.++Do NOT use for: Docker containers (use pulse_control_docker), or checking status (use pulse_get_topology).++Note: These are LXC containers managed by Proxmox, NOT Docker containers. Uses 'pct' commands internally.`,InputSchema: InputSchema{Type: "object",Properties: map[string]PropertySchema{"guest_id": {Type: "string",- Description: "The VMID (e.g., '101') or name of the VM/container to control",+ Description: "VMID number (e.g. '101') or exact name of the VM/LXC container",},"action": {Type: "string",- Description: "Action to perform: start, stop, shutdown, restart",+ Description: "start, stop (immediate), shutdown (graceful), or restart",Enum: []string{"start", "stop", "shutdown", "restart"},},"force": {Type: "boolean",- Description: "If true, force stop without graceful shutdown (use with caution)",+ Description: "Force stop without graceful shutdown (rarely needed)",},},Required: []string{"guest_id", "action"},@@ -76,22 +92,30 @@ func (e *PulseToolExecutor) registerControlTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_control_docker",- Description: "Control Docker containers. Actions: start, stop, restart. Requires an agent on the Docker host.",+ Name: "pulse_control_docker",+ Description: `Start, stop, or restart Docker containers.++Returns: Success message with container name and host, or error if failed.++Use when: User asks to start, stop, or restart a Docker container.++Do NOT use for: Proxmox VMs/LXC containers (use pulse_control_guest), or checking status (use pulse_get_topology).++Note: These are Docker containers, not Proxmox LXC containers. Uses 'docker' commands internally.`,InputSchema: InputSchema{Type: "object",Properties: map[string]PropertySchema{"container": {Type: "string",- Description: "The container name or ID to control",+ Description: "Container name (e.g. 'nginx') or container ID",},"host": {Type: "string",- Description: "The Docker host name (required if multiple hosts)",+ Description: "Docker host name (e.g. 'Tower'). Required if multiple Docker hosts exist.",},"action": {Type: "string",- Description: "Action to perform: start, stop, restart",+ Description: "start, stop, or restart",Enum: []string{"start", "stop", "restart"},},},@@ -175,10 +199,14 @@ func (e *PulseToolExecutor) executeRunCommand(ctx context.Context, args map[strioutput += "\n" + result.Stderr}if result.ExitCode != 0 {- output = fmt.Sprintf("Exit code %d:\n%s", result.ExitCode, output)+ return NewTextResult(fmt.Sprintf("Command failed (exit code %d):\n%s", result.ExitCode, output)), nil}- return NewTextResult(output), nil+ // Success - include guidance to prevent unnecessary verification+ if output == "" {+ return NewTextResult("✓ Command completed successfully (exit code 0). No verification needed."), nil+ }+ return NewTextResult(fmt.Sprintf("✓ Command completed successfully (exit code 0). No verification needed.\n%s", output)), nil}func (e *PulseToolExecutor) executeControlGuest(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {@@ -241,12 +269,20 @@ func (e *PulseToolExecutor) executeControlGuest(ctx context.Context, args map[stif decision == agentexec.PolicyBlock {return NewTextResult(formatPolicyBlocked(command, "This command is blocked by security policy")), nil}- if e.controlLevel == ControlLevelControlled || (decision == agentexec.PolicyRequireApproval && !e.isAutonomous) {- approvalID := createApprovalRecord(command, guest.Type, fmt.Sprintf("%d", guest.VMID), guest.Name, fmt.Sprintf("%s guest %s", action, guest.Name))+ if decision == agentexec.PolicyRequireApproval && !e.isAutonomous {+ // Use guest.Node (the Proxmox host) as targetName so approval execution can find the correct agent+ approvalID := createApprovalRecord(command, guest.Type, fmt.Sprintf("%d", guest.VMID), guest.Node, fmt.Sprintf("%s guest %s", action, guest.Name))return NewTextResult(formatControlApprovalNeeded(guest.Name, guest.VMID, action, command, approvalID)), nil}}+ // Check control level - this must be outside policy check since policy may be nil+ if e.controlLevel == ControlLevelControlled {+ // Use guest.Node (the Proxmox host) as targetName so approval execution can find the correct agent+ approvalID := createApprovalRecord(command, guest.Type, fmt.Sprintf("%d", guest.VMID), guest.Node, fmt.Sprintf("%s guest %s", action, guest.Name))+ return NewTextResult(formatControlApprovalNeeded(guest.Name, guest.VMID, action, command, approvalID)), nil+ }+if e.controlLevel == ControlLevelSuggest {return NewTextResult(formatControlSuggestion(guest.Name, guest.VMID, action, command, guest.Node)), nil}@@ -275,7 +311,7 @@ func (e *PulseToolExecutor) executeControlGuest(ctx context.Context, args map[st}if result.ExitCode == 0 {- return NewTextResult(fmt.Sprintf("Successfully executed '%s' on %s (VMID %d).\n%s", action, guest.Name, guest.VMID, output)), nil+ return NewTextResult(fmt.Sprintf("✓ Successfully executed '%s' on %s (VMID %d). Action complete - no verification needed (state updates in ~10s).\n%s", action, guest.Name, guest.VMID, output)), nil}return NewTextResult(fmt.Sprintf("Command failed (exit code %d):\n%s", result.ExitCode, output)), nil@@ -307,17 +343,26 @@ func (e *PulseToolExecutor) executeControlDocker(ctx context.Context, args map[scommand := fmt.Sprintf("docker %s %s", action, container.Name)+ // Get the agent hostname for approval records (may differ from docker host display name)+ agentHostname := e.getAgentHostnameForDockerHost(dockerHost)+if e.policy != nil {decision := e.policy.Evaluate(command)if decision == agentexec.PolicyBlock {return NewTextResult(formatPolicyBlocked(command, "This command is blocked by security policy")), nil}- if e.controlLevel == ControlLevelControlled || (decision == agentexec.PolicyRequireApproval && !e.isAutonomous) {- approvalID := createApprovalRecord(command, "docker", container.Name, dockerHost.Hostname, fmt.Sprintf("%s Docker container %s", action, container.Name))+ if decision == agentexec.PolicyRequireApproval && !e.isAutonomous {+ approvalID := createApprovalRecord(command, "docker", container.Name, agentHostname, fmt.Sprintf("%s Docker container %s", action, container.Name))return NewTextResult(formatDockerApprovalNeeded(container.Name, dockerHost.Hostname, action, command, approvalID)), nil}}+ // Check control level - this must be outside policy check since policy may be nil+ if e.controlLevel == ControlLevelControlled {+ approvalID := createApprovalRecord(command, "docker", container.Name, agentHostname, fmt.Sprintf("%s Docker container %s", action, container.Name))+ return NewTextResult(formatDockerApprovalNeeded(container.Name, dockerHost.Hostname, action, command, approvalID)), nil+ }+if e.controlLevel == ControlLevelSuggest {return NewTextResult(formatDockerSuggestion(container.Name, dockerHost.Hostname, action, command)), nil}@@ -346,7 +391,7 @@ func (e *PulseToolExecutor) executeControlDocker(ctx context.Context, args map[s}if result.ExitCode == 0 {- return NewTextResult(fmt.Sprintf("Successfully executed 'docker %s' on container '%s' (host: %s).\n%s", action, container.Name, dockerHost.Hostname, output)), nil+ return NewTextResult(fmt.Sprintf("✓ Successfully executed 'docker %s' on container '%s' (host: %s). Action complete - no verification needed (state updates in ~10s).\n%s", action, container.Name, dockerHost.Hostname, output)), nil}return NewTextResult(fmt.Sprintf("Command failed (exit code %d):\n%s", result.ExitCode, output)), nil@@ -477,6 +522,17 @@ func (e *PulseToolExecutor) findAgentForDockerHost(dockerHost *models.DockerHost}agents := e.agentServer.GetConnectedAgents()++ // First try to match by AgentID (most reliable)+ if dockerHost.AgentID != "" {+ for _, agent := range agents {+ if agent.AgentID == dockerHost.AgentID {+ return agent.AgentID+ }+ }+ }++ // Fall back to hostname matchfor _, agent := range agents {if agent.Hostname == dockerHost.Hostname {return agent.AgentID@@ -486,6 +542,27 @@ func (e *PulseToolExecutor) findAgentForDockerHost(dockerHost *models.DockerHostreturn ""}+// getAgentHostnameForDockerHost finds the agent hostname for a Docker host (for approval records)+func (e *PulseToolExecutor) getAgentHostnameForDockerHost(dockerHost *models.DockerHost) string {+ if e.agentServer == nil {+ return dockerHost.Hostname // fallback+ }++ agents := e.agentServer.GetConnectedAgents()++ // Try to match by AgentID first+ if dockerHost.AgentID != "" {+ for _, agent := range agents {+ if agent.AgentID == dockerHost.AgentID {+ return agent.Hostname+ }+ }+ }++ // Fall back to the docker host's hostname+ return dockerHost.Hostname+}+// createApprovalRecord creates an approval record in the store and returns the approval ID.// Returns empty string if store is not available (approvals will still work, just without persistence).func createApprovalRecord(command, targetType, targetID, targetName, context string) string {diff --git a/internal/ai/mcp/tools_patrol.go b/internal/ai/mcp/tools_patrol.goindex f5396afe21..9268e9dbaf 100644--- a/internal/ai/mcp/tools_patrol.go+++ b/internal/ai/mcp/tools_patrol.go@@ -68,23 +68,29 @@ func (e *PulseToolExecutor) registerPatrolTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_list_alerts",- Description: "List all currently active alerts. Use to understand current problems in the infrastructure.",+ Name: "pulse_list_alerts",+ Description: `List active threshold alerts (CPU > 80%, disk full, etc).++Returns: JSON array of alerts with resource, type, severity, value, threshold.++Use when: User asks about alerts, warnings, or "what's wrong" with infrastructure.++Do NOT use for: Checking if something is running (use pulse_get_topology).`,InputSchema: InputSchema{Type: "object",Properties: map[string]PropertySchema{"severity": {Type: "string",- Description: "Filter by severity: 'critical', 'warning', 'info'. Omit for all.",+ Description: "Filter: 'critical', 'warning', or 'info'. Omit for all.",Enum: []string{"critical", "warning", "info"},},"limit": {Type: "integer",- Description: "Maximum number of results (default: 100)",+ Description: "Max results (default 100)",},"offset": {Type: "integer",- Description: "Number of results to skip",+ Description: "Skip N results for pagination",},},},@@ -96,27 +102,33 @@ func (e *PulseToolExecutor) registerPatrolTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_list_findings",- Description: "List AI patrol findings. Active findings are current issues; dismissed findings show user feedback.",+ Name: "pulse_list_findings",+ Description: `List AI patrol findings - issues detected by automated analysis.++Returns: JSON with active findings (current issues) and counts.++Use when: User asks about findings, issues, or "what did the AI find".++Do NOT use for: Checking if something is running (use pulse_get_topology), or threshold alerts (use pulse_list_alerts).`,InputSchema: InputSchema{Type: "object",Properties: map[string]PropertySchema{"include_dismissed": {Type: "boolean",- Description: "If true, also include dismissed findings",+ Description: "Include previously dismissed findings",},"severity": {Type: "string",- Description: "Filter by severity: 'critical', 'warning', 'info'. Omit for all.",+ Description: "Filter: 'critical', 'warning', or 'info'. Omit for all.",Enum: []string{"critical", "warning", "info"},},"limit": {Type: "integer",- Description: "Maximum number of results (default: 100)",+ Description: "Max results (default 100)",},"offset": {Type: "integer",- Description: "Number of results to skip",+ Description: "Skip N results for pagination",},},},diff --git a/internal/ai/mcp/tools_query.go b/internal/ai/mcp/tools_query.goindex f4c4efecaa..d5ab616cd6 100644--- a/internal/ai/mcp/tools_query.go+++ b/internal/ai/mcp/tools_query.go@@ -13,8 +13,12 @@ import (func (e *PulseToolExecutor) registerQueryTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_get_capabilities",- Description: "Get server capabilities, available features, and current configuration. Call this first to understand what tools and data are available.",+ Name: "pulse_get_capabilities",+ Description: `Get server capabilities and connected agents.++Returns: JSON with control_level, enabled features, connected agent count and details.++Use when: You need to check if control features are enabled or verify agent connectivity before running commands.`,InputSchema: InputSchema{Type: "object",Properties: map[string]PropertySchema{},@@ -47,34 +51,23 @@ func (e *PulseToolExecutor) registerQueryTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_list_infrastructure",- Description: "List all monitored infrastructure including VMs, containers, Docker hosts, and Proxmox nodes.",+ Name: "pulse_get_topology",+ Description: `Get live infrastructure state - all Proxmox nodes with VMs/LXC containers, and Docker hosts with containers.++Returns: JSON with 'proxmox.nodes[]' (each with vms[], containers[], status, agent_connected), 'docker.hosts[]' (each with containers[], status), and 'summary' counts.++Use when: Checking if something is running, finding a VM/container by name, getting current infrastructure state.++Example: User asks "is nginx running?" → call this, find nginx in the response, report its status field directly.++This data is authoritative and updates every ~10 seconds. Trust it for status questions - no verification needed.`,InputSchema: InputSchema{- Type: "object",- Properties: map[string]PropertySchema{- "type": {- Type: "string",- Description: "Filter by type: 'nodes', 'vms', 'containers', 'docker'. Omit for all.",- Enum: []string{"nodes", "vms", "containers", "docker"},- },- "status": {- Type: "string",- Description: "Filter by status: 'running', 'stopped', 'all'. Default: all.",- Enum: []string{"running", "stopped", "all"},- },- "limit": {- Type: "integer",- Description: "Maximum number of results per category (default: 100)",- },- "offset": {- Type: "integer",- Description: "Number of results to skip per category",- },- },+ Type: "object",+ Properties: map[string]PropertySchema{},},},Handler: func(ctx context.Context, exec *PulseToolExecutor, args map[string]interface{}) (CallToolResult, error) {- return exec.executeListInfrastructure(ctx, args)+ return exec.executeGetTopology(ctx)},})@@ -109,19 +102,25 @@ func (e *PulseToolExecutor) registerQueryTools() {e.registry.Register(RegisteredTool{Definition: Tool{- Name: "pulse_get_resource",- Description: "Get detailed information about a specific VM, container, or Docker container including IPs, ports, labels, mounts, and network configuration.",+ Name: "pulse_get_resource",+ Description: `Get detailed information about a specific VM, LXC container, or Docker container.++Returns: JSON with name, status, IPs, ports, labels, mounts, network config, CPU/memory stats.++Use when: You need detailed info about ONE specific resource (IPs, ports, config) that topology doesn't provide.++Note: For simple status checks, use pulse_get_topology instead - it's faster and shows all resources.`,InputSchema: InputSchema{Type: "object",Properties: map[string]PropertySchema{"resource_type": {Type: "string",- Description: "Type of resource: 'vm', 'container', 'docker'",+ Description: "Type: 'vm' (Proxmox VM), 'container' (Proxmox LXC), or 'docker' (Docker container)",Enum: []string{"vm", "container", "docker"},},"resource_id": {Type: "string",- Description: "The resource ID, VMID, or name to look up",+ Description: "VMID number (e.g. '101') or container name",},},Required: []string{"resource_type", "resource_id"},@@ -134,9 +133,17 @@ func (e *PulseToolExecutor) registerQueryTools() {}func (e *PulseToolExecutor) executeGetCapabilities(_ context.Context) (CallToolResult, error) {- connectedAgents := 0+ var agents []AgentInfoif e.agentServer != nil {- connectedAgents = len(e.agentServer.GetConnectedAgents())+ connectedAgents := e.agentServer.GetConnectedAgents()+ for _, a := range connectedAgents {+ agents = append(agents, AgentInfo{+ Hostname: a.Hostname,+ Version: a.Version,+ Platform: a.Platform,+ ConnectedAt: a.ConnectedAt.Format("2006-01-02T15:04:05Z"),+ })+ }}response := CapabilitiesResponse{@@ -154,7 +161,8 @@ func (e *PulseToolExecutor) executeGetCapabilities(_ context.Context) (CallToolRControl: e.controlLevel != ControlLevelReadOnly && e.controlLevel != "",},ProtectedGuests: e.protectedGuests,- ConnectedAgents: connectedAgents,+ ConnectedAgents: len(agents),+ Agents: agents,Version: ServerVersion,}@@ -211,6 +219,15 @@ func (e *PulseToolExecutor) executeListInfrastructure(_ context.Context, args maoffset := intArg(args, "offset", 0)state := e.stateProvider.GetState()++ // Build a set of connected agent hostnames for quick lookup+ connectedAgentHostnames := make(map[string]bool)+ if e.agentServer != nil {+ for _, agent := range e.agentServer.GetConnectedAgents() {+ connectedAgentHostnames[agent.Hostname] = true+ }+ }+response := InfrastructureResponse{Total: TotalCounts{Nodes: len(state.Nodes),@@ -233,9 +250,10 @@ func (e *PulseToolExecutor) executeListInfrastructure(_ context.Context, args macontinue}response.Nodes = append(response.Nodes, NodeSummary{- Name: node.Name,- Status: node.Status,- ID: node.ID,+ Name: node.Name,+ Status: node.Status,+ ID: node.ID,+ AgentConnected: connectedAgentHostnames[node.Name],})}}@@ -300,6 +318,7 @@ func (e *PulseToolExecutor) executeListInfrastructure(_ context.Context, args maHostname: host.Hostname,DisplayName: host.DisplayName,ContainerCount: len(host.Containers),+ AgentConnected: connectedAgentHostnames[host.Hostname],}for _, c := range host.Containers {if filterStatus != "" && filterStatus != "all" && c.State != filterStatus {@@ -320,6 +339,170 @@ func (e *PulseToolExecutor) executeListInfrastructure(_ context.Context, args mareturn NewJSONResult(response), nil}+func (e *PulseToolExecutor) executeGetTopology(_ context.Context) (CallToolResult, error) {+ if e.stateProvider == nil {+ return NewErrorResult(fmt.Errorf("state provider not available")), nil+ }++ state := e.stateProvider.GetState()++ // Build a set of connected agent hostnames for quick lookup+ connectedAgentHostnames := make(map[string]bool)+ if e.agentServer != nil {+ for _, agent := range e.agentServer.GetConnectedAgents() {+ connectedAgentHostnames[agent.Hostname] = true+ }+ }++ // Check if control is enabled+ controlEnabled := e.controlLevel != ControlLevelReadOnly && e.controlLevel != ""++ // Build Proxmox topology - group VMs and containers by node+ nodeMap := make(map[string]*ProxmoxNodeTopology)++ // Initialize nodes from state+ for _, node := range state.Nodes {+ hasAgent := connectedAgentHostnames[node.Name]+ nodeMap[node.Name] = &ProxmoxNodeTopology{+ Name: node.Name,+ ID: node.ID,+ Status: node.Status,+ AgentConnected: hasAgent,+ CanExecute: hasAgent && controlEnabled,+ VMs: []TopologyVM{},+ Containers: []TopologyLXC{},+ }+ }++ // Summary counters+ summary := TopologySummary{+ TotalNodes: len(state.Nodes),+ TotalVMs: len(state.VMs),+ TotalLXCContainers: len(state.Containers),+ TotalDockerHosts: len(state.DockerHosts),+ }++ // Add VMs to their nodes+ for _, vm := range state.VMs {+ nodeTopology, exists := nodeMap[vm.Node]+ if !exists {+ // Create node entry if it doesn't exist (shouldn't happen normally)+ hasAgent := connectedAgentHostnames[vm.Node]+ nodeTopology = &ProxmoxNodeTopology{+ Name: vm.Node,+ Status: "unknown",+ AgentConnected: hasAgent,+ CanExecute: hasAgent && controlEnabled,+ VMs: []TopologyVM{},+ Containers: []TopologyLXC{},+ }+ nodeMap[vm.Node] = nodeTopology+ }++ nodeTopology.VMs = append(nodeTopology.VMs, TopologyVM{+ VMID: vm.VMID,+ Name: vm.Name,+ Status: vm.Status,+ CPU: vm.CPU * 100,+ Memory: vm.Memory.Usage * 100,+ OS: vm.OSName,+ Tags: vm.Tags,+ })+ nodeTopology.VMCount++++ if vm.Status == "running" {+ summary.RunningVMs+++ }+ }++ // Add containers to their nodes+ for _, ct := range state.Containers {+ nodeTopology, exists := nodeMap[ct.Node]+ if !exists {+ hasAgent := connectedAgentHostnames[ct.Node]+ nodeTopology = &ProxmoxNodeTopology{+ Name: ct.Node,+ Status: "unknown",+ AgentConnected: hasAgent,+ CanExecute: hasAgent && controlEnabled,+ VMs: []TopologyVM{},+ Containers: []TopologyLXC{},+ }+ nodeMap[ct.Node] = nodeTopology+ }++ nodeTopology.Containers = append(nodeTopology.Containers, TopologyLXC{+ VMID: ct.VMID,+ Name: ct.Name,+ Status: ct.Status,+ CPU: ct.CPU * 100,+ Memory: ct.Memory.Usage * 100,+ OS: ct.OSName,+ Tags: ct.Tags,+ HasDocker: ct.HasDocker,+ })+ nodeTopology.ContainerCount++++ if ct.Status == "running" {+ summary.RunningLXC+++ }+ }++ // Convert node map to slice+ var proxmoxNodes []ProxmoxNodeTopology+ for _, node := range nodeMap {+ if node.AgentConnected {+ summary.NodesWithAgents+++ }+ proxmoxNodes = append(proxmoxNodes, *node)+ }++ // Build Docker topology+ var dockerHosts []DockerHostTopology+ for _, host := range state.DockerHosts {+ hasAgent := connectedAgentHostnames[host.Hostname]+ runningCount := 0+ var containers []DockerContainerSummary++ for _, c := range host.Containers {+ containers = append(containers, DockerContainerSummary{+ ID: c.ID,+ Name: c.Name,+ State: c.State,+ Image: c.Image,+ Health: c.Health,+ })+ summary.TotalDockerContainers+++ if c.State == "running" {+ runningCount+++ summary.RunningDocker+++ }+ }++ if hasAgent {+ summary.DockerHostsWithAgents+++ }++ dockerHosts = append(dockerHosts, DockerHostTopology{+ Hostname: host.Hostname,+ DisplayName: host.DisplayName,+ AgentConnected: hasAgent,+ CanExecute: hasAgent && controlEnabled,+ Containers: containers,+ ContainerCount: len(containers),+ RunningCount: runningCount,+ })+ }++ response := TopologyResponse{+ Proxmox: ProxmoxTopology{Nodes: proxmoxNodes},+ Docker: DockerTopology{Hosts: dockerHosts},+ Summary: summary,+ }++ return NewJSONResult(response), nil+}+func (e *PulseToolExecutor) executeSetResourceURL(_ context.Context, args map[string]interface{}) (CallToolResult, error) {resourceType, _ := args["resource_type"].(string)resourceID, _ := args["resource_id"].(string)diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.goindex cfc3ae0a45..fdcf2611e1 100644--- a/internal/api/ai_handler.go+++ b/internal/api/ai_handler.go@@ -375,6 +375,116 @@ func (h *AIHandler) HandleStatus(w http.ResponseWriter, r *http.Request) {json.NewEncoder(w).Encode(status)}+// HandleSummarize handles POST /api/ai/sessions/{id}/summarize+// Compresses context when nearing model limits+func (h *AIHandler) HandleSummarize(w http.ResponseWriter, r *http.Request, sessionID string) {+ if !CheckAuth(h.config, w, r) {+ return+ }++ if !h.IsRunning() {+ http.Error(w, "AI is not running", http.StatusServiceUnavailable)+ return+ }++ result, err := h.service.SummarizeSession(r.Context(), sessionID)+ if err != nil {+ http.Error(w, err.Error(), http.StatusInternalServerError)+ return+ }++ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(result)+}++// HandleDiff handles GET /api/ai/sessions/{id}/diff+// Returns file changes made during the session+func (h *AIHandler) HandleDiff(w http.ResponseWriter, r *http.Request, sessionID string) {+ if !CheckAuth(h.config, w, r) {+ return+ }++ if !h.IsRunning() {+ http.Error(w, "AI is not running", http.StatusServiceUnavailable)+ return+ }++ diff, err := h.service.GetSessionDiff(r.Context(), sessionID)+ if err != nil {+ http.Error(w, err.Error(), http.StatusInternalServerError)+ return+ }++ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(diff)+}++// HandleFork handles POST /api/ai/sessions/{id}/fork+// Creates a branch point in the conversation+func (h *AIHandler) HandleFork(w http.ResponseWriter, r *http.Request, sessionID string) {+ if !CheckAuth(h.config, w, r) {+ return+ }++ if !h.IsRunning() {+ http.Error(w, "AI is not running", http.StatusServiceUnavailable)+ return+ }++ session, err := h.service.ForkSession(r.Context(), sessionID)+ if err != nil {+ http.Error(w, err.Error(), http.StatusInternalServerError)+ return+ }++ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(session)+}++// HandleRevert handles POST /api/ai/sessions/{id}/revert+// Reverts file changes from the session+func (h *AIHandler) HandleRevert(w http.ResponseWriter, r *http.Request, sessionID string) {+ if !CheckAuth(h.config, w, r) {+ return+ }++ if !h.IsRunning() {+ http.Error(w, "AI is not running", http.StatusServiceUnavailable)+ return+ }++ result, err := h.service.RevertSession(r.Context(), sessionID)+ if err != nil {+ http.Error(w, err.Error(), http.StatusInternalServerError)+ return+ }++ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(result)+}++// HandleUnrevert handles POST /api/ai/sessions/{id}/unrevert+// Restores previously reverted changes+func (h *AIHandler) HandleUnrevert(w http.ResponseWriter, r *http.Request, sessionID string) {+ if !CheckAuth(h.config, w, r) {+ return+ }++ if !h.IsRunning() {+ http.Error(w, "AI is not running", http.StatusServiceUnavailable)+ return+ }++ result, err := h.service.UnrevertSession(r.Context(), sessionID)+ if err != nil {+ http.Error(w, err.Error(), http.StatusInternalServerError)+ return+ }++ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(result)+}+// AnswerQuestionRequest represents a request to answer a questiontype AnswerQuestionRequest struct {Answers []struct {diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.goindex 5a69dbbdf7..0d2d6700a9 100644--- a/internal/api/ai_handlers.go+++ b/internal/api/ai_handlers.go@@ -295,7 +295,7 @@ func (h *AISettingsHandler) HandleGetAISettings(w http.ResponseWriter, r *http.RAutoFixModel: settings.AutoFixModel,BaseURL: settings.BaseURL,Configured: settings.IsConfigured() || isDemo,- AutonomousMode: settings.AutonomousMode,+ AutonomousMode: settings.IsAutonomous(), // Derived from control_levelCustomContext: settings.CustomContext,AuthMethod: authMethod,OAuthConnected: settings.OAuthAccessToken != "",@@ -442,19 +442,28 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htt}if req.AutonomousMode != nil {- // Autonomous mode requires Pro license with ai_autofix feature- if *req.AutonomousMode && !h.aiService.HasLicenseFeature(ai.FeatureAIAutoFix) {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(http.StatusPaymentRequired)- json.NewEncoder(w).Encode(map[string]interface{}{- "error": "license_required",- "message": "Autonomous Mode requires Pulse Pro",- "feature": ai.FeatureAIAutoFix,- "upgrade_url": "https://pulserelay.pro/",- })- return+ // Legacy: autonomous_mode now maps to control_level for backwards compatibility+ if *req.AutonomousMode {+ // Autonomous mode requires Pro license with ai_autofix feature+ if !h.aiService.HasLicenseFeature(ai.FeatureAIAutoFix) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusPaymentRequired)+ json.NewEncoder(w).Encode(map[string]interface{}{+ "error": "license_required",+ "message": "Autonomous Mode requires Pulse Pro",+ "feature": ai.FeatureAIAutoFix,+ "upgrade_url": "https://pulserelay.pro/",+ })+ return+ }+ settings.ControlLevel = config.ControlLevelAutonomous+ settings.AutonomousMode = true+ } else if settings.GetControlLevel() == config.ControlLevelAutonomous {+ // Only downgrade from autonomous to controlled; preserve other levels+ // (e.g., don't change read_only or suggest to controlled)+ settings.ControlLevel = config.ControlLevelControlled+ settings.AutonomousMode = false}- settings.AutonomousMode = *req.AutonomousMode}if req.CustomContext != nil {@@ -625,6 +634,8 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htt}}settings.ControlLevel = *req.ControlLevel+ // Keep legacy AutonomousMode in sync to prevent fallback issues+ settings.AutonomousMode = (*req.ControlLevel == config.ControlLevelAutonomous)}// Handle protected guests (nil = don't update)@@ -660,7 +671,8 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htt// Update MCP control settings if control level or protected guests changed// This updates tool visibility without restarting OpenCode- if h.onControlSettingsChange != nil && (req.ControlLevel != nil || req.ProtectedGuests != nil) {+ // Note: req.AutonomousMode also maps to control_level for backwards compatibility+ if h.onControlSettingsChange != nil && (req.ControlLevel != nil || req.ProtectedGuests != nil || req.AutonomousMode != nil) {h.onControlSettingsChange()}@@ -691,7 +703,7 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *httAutoFixModel: settings.AutoFixModel,BaseURL: settings.BaseURL,Configured: settings.IsConfigured(),- AutonomousMode: settings.AutonomousMode,+ AutonomousMode: settings.IsAutonomous(), // Derived from control_levelCustomContext: settings.CustomContext,AuthMethod: authMethod,OAuthConnected: settings.OAuthAccessToken != "",@@ -3707,9 +3719,19 @@ func (h *AISettingsHandler) HandleListApprovals(w http.ResponseWriter, r *http.R}// Check license- licenseService := license.NewService()- if !licenseService.HasFeature(license.FeatureAIAutoFix) {- writeErrorResponse(w, http.StatusForbidden, "license_required", "AI Auto-Fix feature requires Pro license", nil)+ licenseState, hasFeatures := h.aiService.GetLicenseState()+ if !h.aiService.HasLicenseFeature(license.FeatureAIAutoFix) {+ log.Warn().+ Str("license_state", licenseState).+ Bool("license_features_available", hasFeatures).+ Str("feature", license.FeatureAIAutoFix).+ Str("data_path", h.config.DataPath).+ Msg("AI Auto-Fix feature not available for approvals")+ writeErrorResponse(w, http.StatusForbidden, "license_required", "AI Auto-Fix feature requires Pro license", map[string]string{+ "license_state": licenseState,+ "license_features_available": strconv.FormatBool(hasFeatures),+ "feature": license.FeatureAIAutoFix,+ })return}@@ -3772,9 +3794,19 @@ func (h *AISettingsHandler) HandleApproveCommand(w http.ResponseWriter, r *http.}// Check license- licenseService := license.NewService()- if !licenseService.HasFeature(license.FeatureAIAutoFix) {- writeErrorResponse(w, http.StatusForbidden, "license_required", "AI Auto-Fix feature requires Pro license", nil)+ licenseState, hasFeatures := h.aiService.GetLicenseState()+ if !h.aiService.HasLicenseFeature(license.FeatureAIAutoFix) {+ log.Warn().+ Str("license_state", licenseState).+ Bool("license_features_available", hasFeatures).+ Str("feature", license.FeatureAIAutoFix).+ Str("data_path", h.config.DataPath).+ Msg("AI Auto-Fix feature not available for approvals")+ writeErrorResponse(w, http.StatusForbidden, "license_required", "AI Auto-Fix feature requires Pro license", map[string]string{+ "license_state": licenseState,+ "license_features_available": strconv.FormatBool(hasFeatures),+ "feature": license.FeatureAIAutoFix,+ })return}@@ -3814,6 +3846,18 @@ func (h *AISettingsHandler) HandleApproveCommand(w http.ResponseWriter, r *http.var execErr errorif h.agentServer != nil && req.TargetName != "" {+ // Debug: list connected agents+ connectedAgents := h.agentServer.GetConnectedAgents()+ agentHostnames := make([]string, len(connectedAgents))+ for i, a := range connectedAgents {+ agentHostnames[i] = a.Hostname+ }+ log.Debug().+ Str("target_name", req.TargetName).+ Strs("connected_agents", agentHostnames).+ Int("agent_count", len(connectedAgents)).+ Msg("Looking for agent to execute approved command")+// Find agent for the target hostagentID, found := h.agentServer.GetAgentForHost(req.TargetName)if found {@@ -3834,7 +3878,13 @@ func (h *AISettingsHandler) HandleApproveCommand(w http.ResponseWriter, r *http.fmt.Sprintf("Failed to execute command: %s - %v", truncateForLog(req.Command, 100), execErr))}} else {- execErr = fmt.Errorf("no agent available for host %s", req.TargetName)+ // Agent not found - provide helpful error message+ connectedAgents := h.agentServer.GetConnectedAgents()+ hostnames := make([]string, len(connectedAgents))+ for i, a := range connectedAgents {+ hostnames[i] = a.Hostname+ }+ execErr = fmt.Errorf("no exec agent connected for host '%s'. Connected agents: %v. The host agent may need to be updated to support remote execution. See /api/ai/agents for details", req.TargetName, hostnames)}}@@ -3926,9 +3976,19 @@ func (h *AISettingsHandler) HandleRollback(w http.ResponseWriter, r *http.Reques}// Check license- licenseService := license.NewService()- if !licenseService.HasFeature(license.FeatureAIAutoFix) {- writeErrorResponse(w, http.StatusForbidden, "license_required", "AI Auto-Fix feature requires Pro license", nil)+ licenseState, hasFeatures := h.aiService.GetLicenseState()+ if !h.aiService.HasLicenseFeature(license.FeatureAIAutoFix) {+ log.Warn().+ Str("license_state", licenseState).+ Bool("license_features_available", hasFeatures).+ Str("feature", license.FeatureAIAutoFix).+ Str("data_path", h.config.DataPath).+ Msg("AI Auto-Fix feature not available for rollback")+ writeErrorResponse(w, http.StatusForbidden, "license_required", "AI Auto-Fix feature requires Pro license", map[string]string{+ "license_state": licenseState,+ "license_features_available": strconv.FormatBool(hasFeatures),+ "feature": license.FeatureAIAutoFix,+ })return}@@ -4024,9 +4084,19 @@ func (h *AISettingsHandler) HandleGetRollbackable(w http.ResponseWriter, r *http}// Check license- licenseService := license.NewService()- if !licenseService.HasFeature(license.FeatureAIAutoFix) {- writeErrorResponse(w, http.StatusForbidden, "license_required", "AI Auto-Fix feature requires Pro license", nil)+ licenseState, hasFeatures := h.aiService.GetLicenseState()+ if !h.aiService.HasLicenseFeature(license.FeatureAIAutoFix) {+ log.Warn().+ Str("license_state", licenseState).+ Bool("license_features_available", hasFeatures).+ Str("feature", license.FeatureAIAutoFix).+ Str("data_path", h.config.DataPath).+ Msg("AI Auto-Fix feature not available for rollbackable list")+ writeErrorResponse(w, http.StatusForbidden, "license_required", "AI Auto-Fix feature requires Pro license", map[string]string{+ "license_state": licenseState,+ "license_features_available": strconv.FormatBool(hasFeatures),+ "feature": license.FeatureAIAutoFix,+ })return}diff --git a/internal/api/router.go b/internal/api/router.goindex 8296286cc0..bc277ea9de 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -1458,7 +1458,7 @@ func (r *Router) setupRoutes() {// routeOpenCodeSessions routes session-specific OpenCode AI requestsfunc (r *Router) routeOpenCodeSessions(w http.ResponseWriter, req *http.Request) {- // Extract session ID from path: /api/ai/sessions/{id}[/messages|/abort]+ // Extract session ID from path: /api/ai/sessions/{id}[/messages|/abort|/summarize|/diff|/fork|/revert|/unrevert]path := strings.TrimPrefix(req.URL.Path, "/api/ai/sessions/")parts := strings.SplitN(path, "/", 2)sessionID := parts[0]@@ -1475,6 +1475,16 @@ func (r *Router) routeOpenCodeSessions(w http.ResponseWriter, req *http.Request)r.aiHandler.HandleMessages(w, req, sessionID)case "abort":r.aiHandler.HandleAbort(w, req, sessionID)+ case "summarize":+ r.aiHandler.HandleSummarize(w, req, sessionID)+ case "diff":+ r.aiHandler.HandleDiff(w, req, sessionID)+ case "fork":+ r.aiHandler.HandleFork(w, req, sessionID)+ case "revert":+ r.aiHandler.HandleRevert(w, req, sessionID)+ case "unrevert":+ r.aiHandler.HandleUnrevert(w, req, sessionID)default:http.Error(w, "Not found", http.StatusNotFound)}@@ -1740,6 +1750,30 @@ func (r *Router) SetMonitor(m *monitoring.Monitor) {} else {log.Warn().Msg("[Router] resourceHandlers is nil, cannot inject resource store")}++ // Set up Docker detector for automatic Docker detection in LXC containers+ if r.agentExecServer != nil {+ // Create a command executor function that wraps the agent exec server+ execFunc := func(ctx context.Context, hostname string, command string, timeout int) (string, int, error) {+ agentID, found := r.agentExecServer.GetAgentForHost(hostname)+ if !found {+ return "", -1, fmt.Errorf("no agent connected for host %s", hostname)+ }+ result, err := r.agentExecServer.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{+ RequestID: fmt.Sprintf("docker-check-%d", time.Now().UnixNano()),+ Command: command,+ Timeout: timeout,+ })+ if err != nil {+ return "", -1, err+ }+ return result.Stdout + result.Stderr, result.ExitCode, nil+ }++ checker := monitoring.NewAgentDockerChecker(execFunc)+ m.SetDockerChecker(checker)+ log.Info().Msg("[Router] Docker detector configured for automatic LXC Docker detection")+ }}}@@ -1998,9 +2032,234 @@ func (r *Router) wireOpenCodeProviders() {log.Debug().Msg("OpenCode: Agent profile manager wired")}+ // Wire storage provider+ if r.monitor != nil {+ storageAdapter := mcp.NewStorageMCPAdapter(r.monitor)+ if storageAdapter != nil {+ service.SetStorageProvider(storageAdapter)+ log.Debug().Msg("OpenCode: Storage provider wired")+ }+ }++ // Wire backup provider+ if r.monitor != nil {+ backupAdapter := mcp.NewBackupMCPAdapter(r.monitor)+ if backupAdapter != nil {+ service.SetBackupProvider(backupAdapter)+ log.Debug().Msg("OpenCode: Backup provider wired")+ }+ }++ // Wire disk health provider+ if r.monitor != nil {+ diskHealthAdapter := mcp.NewDiskHealthMCPAdapter(r.monitor)+ if diskHealthAdapter != nil {+ service.SetDiskHealthProvider(diskHealthAdapter)+ log.Debug().Msg("OpenCode: Disk health provider wired")+ }+ }++ // Wire metrics history provider+ if r.monitor != nil {+ if metricsHistory := r.monitor.GetMetricsHistory(); metricsHistory != nil {+ metricsAdapter := mcp.NewMetricsHistoryMCPAdapter(+ r.monitor,+ &metricsSourceWrapper{history: metricsHistory},+ )+ if metricsAdapter != nil {+ service.SetMetricsHistory(metricsAdapter)+ log.Debug().Msg("OpenCode: Metrics history provider wired")+ }+ }+ }++ // Wire baseline provider+ if r.aiSettingsHandler != nil {+ if patrolSvc := r.aiSettingsHandler.GetAIService().GetPatrolService(); patrolSvc != nil {+ if baselineStore := patrolSvc.GetBaselineStore(); baselineStore != nil {+ baselineAdapter := mcp.NewBaselineMCPAdapter(&baselineSourceWrapper{store: baselineStore})+ if baselineAdapter != nil {+ service.SetBaselineProvider(baselineAdapter)+ log.Debug().Msg("OpenCode: Baseline provider wired")+ }+ }+ }+ }++ // Wire pattern provider+ if r.aiSettingsHandler != nil {+ if patrolSvc := r.aiSettingsHandler.GetAIService().GetPatrolService(); patrolSvc != nil {+ if patternDetector := patrolSvc.GetPatternDetector(); patternDetector != nil {+ patternAdapter := mcp.NewPatternMCPAdapter(+ &patternSourceWrapper{detector: patternDetector},+ r.monitor,+ )+ if patternAdapter != nil {+ service.SetPatternProvider(patternAdapter)+ log.Debug().Msg("OpenCode: Pattern provider wired")+ }+ }+ }+ }++ // Wire findings manager+ if r.aiSettingsHandler != nil {+ if patrolSvc := r.aiSettingsHandler.GetAIService().GetPatrolService(); patrolSvc != nil {+ findingsManagerAdapter := mcp.NewFindingsManagerMCPAdapter(patrolSvc)+ if findingsManagerAdapter != nil {+ service.SetFindingsManager(findingsManagerAdapter)+ log.Debug().Msg("OpenCode: Findings manager wired")+ }+ }+ }++ // Wire metadata updater+ if r.aiSettingsHandler != nil {+ metadataAdapter := mcp.NewMetadataUpdaterMCPAdapter(r.aiSettingsHandler.GetAIService())+ if metadataAdapter != nil {+ service.SetMetadataUpdater(metadataAdapter)+ log.Debug().Msg("OpenCode: Metadata updater wired")+ }+ }+log.Info().Msg("OpenCode MCP tool providers wired")}+// metricsSourceWrapper wraps monitoring.MetricsHistory to implement mcp.MetricsSource+type metricsSourceWrapper struct {+ history *monitoring.MetricsHistory+}++func (w *metricsSourceWrapper) GetGuestMetrics(guestID string, metricType string, duration time.Duration) []mcp.RawMetricPoint {+ points := w.history.GetGuestMetrics(guestID, metricType, duration)+ return convertMetricPoints(points)+}++func (w *metricsSourceWrapper) GetNodeMetrics(nodeID string, metricType string, duration time.Duration) []mcp.RawMetricPoint {+ points := w.history.GetNodeMetrics(nodeID, metricType, duration)+ return convertMetricPoints(points)+}++func (w *metricsSourceWrapper) GetAllGuestMetrics(guestID string, duration time.Duration) map[string][]mcp.RawMetricPoint {+ metricsMap := w.history.GetAllGuestMetrics(guestID, duration)+ result := make(map[string][]mcp.RawMetricPoint, len(metricsMap))+ for key, points := range metricsMap {+ result[key] = convertMetricPoints(points)+ }+ return result+}++func convertMetricPoints(points []monitoring.MetricPoint) []mcp.RawMetricPoint {+ result := make([]mcp.RawMetricPoint, len(points))+ for i, p := range points {+ result[i] = mcp.RawMetricPoint{+ Value: p.Value,+ Timestamp: p.Timestamp,+ }+ }+ return result+}++// baselineSourceWrapper wraps baseline.Store to implement mcp.BaselineSource+type baselineSourceWrapper struct {+ store *ai.BaselineStore+}++func (w *baselineSourceWrapper) GetBaseline(resourceID, metric string) (mean, stddev float64, sampleCount int, ok bool) {+ if w.store == nil {+ return 0, 0, 0, false+ }+ baseline, found := w.store.GetBaseline(resourceID, metric)+ if !found || baseline == nil {+ return 0, 0, 0, false+ }+ return baseline.Mean, baseline.StdDev, baseline.SampleCount, true+}++func (w *baselineSourceWrapper) GetAllBaselines() map[string]map[string]mcp.BaselineData {+ if w.store == nil {+ return nil+ }+ allFlat := w.store.GetAllBaselines()+ if allFlat == nil {+ return nil+ }++ result := make(map[string]map[string]mcp.BaselineData)+ for key, flat := range allFlat {+ // key format is "resourceID:metric"+ parts := strings.SplitN(key, ":", 2)+ if len(parts) != 2 {+ continue+ }+ resourceID, metric := parts[0], parts[1]++ if result[resourceID] == nil {+ result[resourceID] = make(map[string]mcp.BaselineData)+ }+ result[resourceID][metric] = mcp.BaselineData{+ Mean: flat.Mean,+ StdDev: flat.StdDev,+ SampleCount: flat.Samples,+ }+ }+ return result+}++// patternSourceWrapper wraps patterns.Detector to implement mcp.PatternSource+type patternSourceWrapper struct {+ detector *ai.PatternDetector+}++func (w *patternSourceWrapper) GetPatterns() []mcp.PatternData {+ if w.detector == nil {+ return nil+ }++ patterns := w.detector.GetPatterns()+ if patterns == nil {+ return nil+ }++ result := make([]mcp.PatternData, 0, len(patterns))+ for _, p := range patterns {+ if p == nil {+ continue+ }+ result = append(result, mcp.PatternData{+ ResourceID: p.ResourceID,+ PatternType: string(p.EventType),+ Description: fmt.Sprintf("%s pattern with %d occurrences", p.EventType, p.Occurrences),+ Confidence: p.Confidence,+ LastSeen: p.LastOccurrence,+ })+ }+ return result+}++func (w *patternSourceWrapper) GetPredictions() []mcp.PredictionData {+ if w.detector == nil {+ return nil+ }++ predictions := w.detector.GetPredictions()+ if predictions == nil {+ return nil+ }++ result := make([]mcp.PredictionData, 0, len(predictions))+ for _, p := range predictions {+ result = append(result, mcp.PredictionData{+ ResourceID: p.ResourceID,+ IssueType: string(p.EventType),+ PredictedTime: p.PredictedAt,+ Confidence: p.Confidence,+ Recommendation: p.Basis,+ })+ }+ return result+}+// StopOpenCodeAI stops the OpenCode-based AI servicefunc (r *Router) StopOpenCodeAI(ctx context.Context) {if r.aiHandler != nil {@@ -5548,3 +5807,5 @@ func normalizeDockerAgentArch(arch string) string {return ""}}++// trigger rebuild Fri Jan 16 10:52:41 UTC 2026