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.

feat(ai): improve OpenCode integration and control level handling

rcourtmanc26f0e6e6cca
diff --git a/internal/ai/opencode/client.go b/internal/ai/opencode/client.go
index ca55c9a76f..c399132d47 100644
--- a/internal/ai/opencode/client.go
+++ b/internal/ai/opencode/client.go
@@ -36,9 +36,11 @@ func newHTTPClient(timeout time.Duration) *http.Client {
// Session represents an OpenCode chat session
type Session struct {
- ID string `json:"id"`
- CreatedAt time.Time `json:"createdAt"`
- UpdatedAt time.Time `json:"updatedAt"`
+ ID string `json:"id"`
+ Title string `json:"title,omitempty"` // Generated from first user message
+ MessageCount int `json:"message_count,omitempty"` // Number of messages in the session
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
}
// Message represents a message in a session
@@ -167,11 +169,33 @@ func (c *Client) ListSessions(ctx context.Context) ([]Session, error) {
return nil, fmt.Errorf("list sessions failed: status %d", resp.StatusCode)
}
- var sessions []Session
- if err := json.NewDecoder(resp.Body).Decode(&sessions); err != nil {
+ // OpenCode returns sessions with nested time structure
+ type openCodeTime struct {
+ Created int64 `json:"created"` // Unix timestamp in ms
+ Updated int64 `json:"updated"` // Unix timestamp in ms
+ }
+ type openCodeSession struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ Time openCodeTime `json:"time"`
+ }
+
+ var ocSessions []openCodeSession
+ if err := json.NewDecoder(resp.Body).Decode(&ocSessions); err != nil {
return nil, err
}
+ // Convert to Pulse's Session format
+ sessions := make([]Session, len(ocSessions))
+ for i, oc := range ocSessions {
+ sessions[i] = Session{
+ ID: oc.ID,
+ Title: oc.Title,
+ CreatedAt: time.UnixMilli(oc.Time.Created),
+ UpdatedAt: time.UnixMilli(oc.Time.Updated),
+ }
+ }
+
return sessions, nil
}
@@ -241,7 +265,24 @@ func (c *Client) Prompt(ctx context.Context, req PromptRequest) (*PromptResponse
},
}
if req.Model != "" {
- messageReq["model"] = req.Model
+ // OpenCode expects model as an object with providerID and modelID
+ parts := strings.SplitN(req.Model, "/", 2)
+ if len(parts) == 2 {
+ messageReq["model"] = map[string]string{
+ "providerID": parts[0],
+ "modelID": parts[1],
+ }
+ } else {
+ // Model doesn't contain a "/" - try to infer provider from model name
+ provider := inferProviderFromModel(req.Model)
+ if provider != "" {
+ messageReq["model"] = map[string]string{
+ "providerID": provider,
+ "modelID": req.Model,
+ }
+ }
+ // If we can't infer provider, skip setting model and let OpenCode use its default
+ }
}
body, err := json.Marshal(messageReq)
@@ -337,7 +378,25 @@ func (c *Client) PromptStream(ctx context.Context, req PromptRequest) (<-chan St
},
}
if req.Model != "" {
- messageReq["model"] = req.Model
+ // OpenCode expects model as an object with providerID and modelID
+ parts := strings.SplitN(req.Model, "/", 2)
+ if len(parts) == 2 {
+ messageReq["model"] = map[string]string{
+ "providerID": parts[0],
+ "modelID": parts[1],
+ }
+ } else {
+ // Model doesn't contain a "/" - try to infer provider from model name
+ // OpenCode requires model as an object, not a string
+ provider := inferProviderFromModel(req.Model)
+ if provider != "" {
+ messageReq["model"] = map[string]string{
+ "providerID": provider,
+ "modelID": req.Model,
+ }
+ }
+ // If we can't infer provider, skip setting model and let OpenCode use its default
+ }
}
body, err := json.Marshal(messageReq)
@@ -529,16 +588,23 @@ func (c *Client) PromptStream(ctx context.Context, req PromptRequest) (<-chan St
continue
}
log.Debug().Str("partType", props.Part.Type).Str("delta", props.Delta).Str("reason", props.Part.Reason).Msg("OpenCode: Processing message part")
- if props.Part.Type == "text" || props.Part.Type == "reasoning" {
- // Stream both text and reasoning content
+ if props.Part.Type == "text" {
+ // Stream text content
if props.Delta != "" {
contentBuffer.WriteString(props.Delta)
- receivedContent = true // Mark that we've received actual content
- // Frontend expects just the delta string as data
+ receivedContent = true
deltaData, _ := json.Marshal(props.Delta)
- log.Debug().Str("type", props.Part.Type).Str("delta", props.Delta).Msg("OpenCode: Sending content event")
+ log.Debug().Str("delta", props.Delta).Msg("OpenCode: Sending content event")
events <- StreamEvent{Type: "content", Data: deltaData}
}
+ } else if props.Part.Type == "reasoning" {
+ // Stream reasoning/thinking content separately
+ if props.Delta != "" {
+ receivedContent = true
+ deltaData, _ := json.Marshal(props.Delta)
+ log.Debug().Str("delta", props.Delta).Msg("OpenCode: Sending thinking event")
+ events <- StreamEvent{Type: "thinking", Data: deltaData}
+ }
} else if props.Part.Type == "tool" {
// Tool execution - translate to frontend format
status := props.Part.State.Status
@@ -599,15 +665,17 @@ func (c *Client) PromptStream(ctx context.Context, req PromptRequest) (<-chan St
case "question.asked":
// OpenCode is asking the user a question
+ // OpenCode format: id, sessionID, questions[{question, header, multiple, options[{label, description}]}]
var props struct {
ID string `json:"id"`
+ SessionID string `json:"sessionID"`
Questions []struct {
- ID string `json:"id"`
- Type string `json:"type"` // "text" or "select"
Question string `json:"question"`
+ Header string `json:"header"`
+ Multiple bool `json:"multiple"`
Options []struct {
- Label string `json:"label"`
- Value string `json:"value"`
+ Label string `json:"label"`
+ Description string `json:"description"`
} `json:"options,omitempty"`
} `json:"questions"`
}
@@ -617,10 +685,36 @@ func (c *Client) PromptStream(ctx context.Context, req PromptRequest) (<-chan St
}
log.Debug().Str("questionID", props.ID).Int("count", len(props.Questions)).Msg("OpenCode: Question asked")
+ // Transform to frontend format
+ transformedQuestions := make([]map[string]interface{}, len(props.Questions))
+ for i, q := range props.Questions {
+ // Determine type: if options exist -> select, else -> text
+ qType := "text"
+ if len(q.Options) > 0 {
+ qType = "select"
+ }
+
+ // Transform options: use label as value if value not provided
+ var options []map[string]string
+ for _, opt := range q.Options {
+ options = append(options, map[string]string{
+ "label": opt.Label,
+ "value": opt.Label, // Use label as value since OpenCode doesn't provide value
+ })
+ }
+
+ transformedQuestions[i] = map[string]interface{}{
+ "id": q.Header, // Use header as id
+ "type": qType,
+ "question": q.Question,
+ "options": options,
+ }
+ }
+
// Send question event to frontend
questionData, _ := json.Marshal(map[string]interface{}{
"question_id": props.ID,
- "questions": props.Questions,
+ "questions": transformedQuestions,
"session_id": sessionID,
})
events <- StreamEvent{Type: "question", Data: questionData}
@@ -718,6 +812,146 @@ type QuestionAnswer struct {
Value string `json:"value"` // The answer value (text or selected option)
}
+// SummarizeSession compresses context when nearing model limits
+func (c *Client) SummarizeSession(ctx context.Context, sessionID string) (map[string]interface{}, error) {
+ req, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/session/"+sessionID+"/summarize", nil)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
+ return nil, fmt.Errorf("summarize session failed: status %d", resp.StatusCode)
+ }
+
+ var result map[string]interface{}
+ if resp.ContentLength != 0 {
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return nil, err
+ }
+ }
+ if result == nil {
+ result = map[string]interface{}{"success": true}
+ }
+
+ return result, nil
+}
+
+// GetSessionDiff returns file changes made during a session
+func (c *Client) GetSessionDiff(ctx context.Context, sessionID string) (map[string]interface{}, error) {
+ req, err := http.NewRequestWithContext(ctx, "GET", c.baseURL+"/session/"+sessionID+"/diff", nil)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("get session diff failed: status %d", resp.StatusCode)
+ }
+
+ var result map[string]interface{}
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return nil, err
+ }
+
+ return result, nil
+}
+
+// ForkSession creates a branch point in the conversation
+func (c *Client) ForkSession(ctx context.Context, sessionID string) (*Session, error) {
+ req, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/session/"+sessionID+"/fork", nil)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
+ return nil, fmt.Errorf("fork session failed: status %d", resp.StatusCode)
+ }
+
+ var session Session
+ if err := json.NewDecoder(resp.Body).Decode(&session); err != nil {
+ return nil, err
+ }
+
+ return &session, nil
+}
+
+// RevertSession reverts file changes from a session
+func (c *Client) RevertSession(ctx context.Context, sessionID string) (map[string]interface{}, error) {
+ req, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/session/"+sessionID+"/revert", nil)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
+ return nil, fmt.Errorf("revert session failed: status %d", resp.StatusCode)
+ }
+
+ var result map[string]interface{}
+ if resp.ContentLength != 0 {
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return nil, err
+ }
+ }
+ if result == nil {
+ result = map[string]interface{}{"success": true}
+ }
+
+ return result, nil
+}
+
+// UnrevertSession restores previously reverted changes
+func (c *Client) UnrevertSession(ctx context.Context, sessionID string) (map[string]interface{}, error) {
+ req, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/session/"+sessionID+"/unrevert", nil)
+ if err != nil {
+ return nil, err
+ }
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
+ return nil, fmt.Errorf("unrevert session failed: status %d", resp.StatusCode)
+ }
+
+ var result map[string]interface{}
+ if resp.ContentLength != 0 {
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return nil, err
+ }
+ }
+ if result == nil {
+ result = map[string]interface{}{"success": true}
+ }
+
+ return result, nil
+}
+
// ListModels returns available models
func (c *Client) ListModels(ctx context.Context) ([]ModelInfo, error) {
req, err := http.NewRequestWithContext(ctx, "GET", c.baseURL+"/config/providers", nil)
@@ -751,3 +985,40 @@ func (c *Client) ListModels(ctx context.Context) ([]ModelInfo, error) {
return models, nil
}
+
+// inferProviderFromModel attempts to determine the provider from a model name
+// Returns empty string if provider cannot be determined
+func inferProviderFromModel(model string) string {
+ modelLower := strings.ToLower(model)
+
+ // Anthropic/Claude models
+ if strings.HasPrefix(modelLower, "claude") {
+ return "anthropic"
+ }
+
+ // OpenAI models
+ if strings.HasPrefix(modelLower, "gpt") || strings.HasPrefix(modelLower, "o1") || strings.HasPrefix(modelLower, "o3") {
+ return "openai"
+ }
+
+ // Google/Gemini models
+ if strings.HasPrefix(modelLower, "gemini") {
+ return "google"
+ }
+
+ // DeepSeek models
+ if strings.HasPrefix(modelLower, "deepseek") {
+ return "deepseek"
+ }
+
+ // Ollama/local models (common ones)
+ if strings.HasPrefix(modelLower, "llama") ||
+ strings.HasPrefix(modelLower, "mistral") ||
+ strings.HasPrefix(modelLower, "codellama") ||
+ strings.HasPrefix(modelLower, "phi") ||
+ strings.HasPrefix(modelLower, "qwen") {
+ return "ollama"
+ }
+
+ return ""
+}
diff --git a/internal/ai/opencode/client_infer_test.go b/internal/ai/opencode/client_infer_test.go
new file mode 100644
index 0000000000..2d5f223902
--- /dev/null
+++ b/internal/ai/opencode/client_infer_test.go
@@ -0,0 +1,55 @@
+package opencode
+
+import (
+ "testing"
+)
+
+func TestInferProviderFromModel(t *testing.T) {
+ tests := []struct {
+ model string
+ expected string
+ }{
+ // Anthropic/Claude models
+ {"claude-opus-4-5-20251101", "anthropic"},
+ {"claude-3-5-haiku-latest", "anthropic"},
+ {"Claude-Sonnet", "anthropic"},
+ {"CLAUDE-3", "anthropic"},
+
+ // OpenAI models
+ {"gpt-4o", "openai"},
+ {"gpt-4-turbo", "openai"},
+ {"o1-preview", "openai"},
+ {"o3-mini", "openai"},
+
+ // Google/Gemini models
+ {"gemini-2.5-flash", "google"},
+ {"gemini-pro", "google"},
+ {"Gemini-Ultra", "google"},
+
+ // DeepSeek models
+ {"deepseek-reasoner", "deepseek"},
+ {"deepseek-coder", "deepseek"},
+
+ // Ollama/local models
+ {"llama3", "ollama"},
+ {"llama-3.1-70b", "ollama"},
+ {"mistral-7b", "ollama"},
+ {"codellama-13b", "ollama"},
+ {"phi-3", "ollama"},
+ {"qwen2.5", "ollama"},
+
+ // Unknown models - should return empty string
+ {"unknown-model", ""},
+ {"random", ""},
+ {"", ""},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.model, func(t *testing.T) {
+ result := inferProviderFromModel(tt.model)
+ if result != tt.expected {
+ t.Errorf("inferProviderFromModel(%q) = %q, want %q", tt.model, result, tt.expected)
+ }
+ })
+ }
+}
diff --git a/internal/ai/opencode/service.go b/internal/ai/opencode/service.go
index 4e9e373b59..e90c37eef1 100644
--- a/internal/ai/opencode/service.go
+++ b/internal/ai/opencode/service.go
@@ -70,8 +70,11 @@ type Service struct {
mcpServer *mcp.Server
executor *mcp.PulseToolExecutor
- cfg *config.AIConfig
- started bool
+ cfg *config.AIConfig
+ stateProvider StateProvider // For real-time infrastructure context
+ agentServer AgentServer // For agent connectivity info
+ alertProvider mcp.AlertProvider // For real-time alert context
+ started bool
}
// Config holds OpenCode service configuration
@@ -115,8 +118,10 @@ func NewService(cfg Config) *Service {
executor := mcp.NewPulseToolExecutor(execCfg)
return &Service{
- cfg: cfg.AIConfig,
- executor: executor,
+ cfg: cfg.AIConfig,
+ stateProvider: cfg.StateProvider,
+ agentServer: cfg.AgentServer,
+ executor: executor,
}
}
@@ -343,11 +348,20 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
return fmt.Errorf("OpenCode not initialized")
}
+ // NOTE: Context injection disabled - let the AI use MCP tools to get context when needed
+ // The proactive context was making the AI too eager to take action on greetings
+ // infraContext := s.buildInfraContext()
+
// Stream from OpenCode
+ promptModel := req.Model
+ if promptModel != "" {
+ promptModel = convertModelToOpenCode(promptModel)
+ }
+
events, errors := client.PromptStream(ctx, PromptRequest{
Prompt: req.Prompt,
SessionID: req.SessionID,
- Model: req.Model,
+ Model: promptModel,
})
// Use bridge to transform specific events (tool_end -> approval_needed for approvals)
@@ -410,6 +424,77 @@ func (s *Service) ListSessions(ctx context.Context) ([]Session, error) {
return client.ListSessions(ctx)
}
+// ListSessionsWithTitles returns all chat sessions with generated titles from the first user message
+func (s *Service) ListSessionsWithTitles(ctx context.Context) ([]Session, error) {
+ s.mu.RLock()
+ client := s.client
+ s.mu.RUnlock()
+
+ if client == nil {
+ return nil, fmt.Errorf("OpenCode not initialized")
+ }
+
+ sessions, err := client.ListSessions(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ // Enrich each session with title from first user message
+ for i := range sessions {
+ messages, err := client.GetMessages(ctx, sessions[i].ID)
+ if err != nil {
+ log.Debug().Err(err).Str("session_id", sessions[i].ID).Msg("Failed to get messages for session")
+ continue
+ }
+
+ sessions[i].MessageCount = len(messages)
+
+ // Find first user message to use as title
+ for _, msg := range messages {
+ if msg.Role == "user" && msg.Content != "" {
+ sessions[i].Title = generateSessionTitle(msg.Content)
+ break
+ }
+ }
+ }
+
+ return sessions, nil
+}
+
+// generateSessionTitle creates a title from the first user message
+// Truncates to ~50 chars at word boundary and adds ellipsis if needed
+func generateSessionTitle(content string) string {
+ // Clean up the content - remove extra whitespace and newlines
+ content = strings.TrimSpace(content)
+ content = strings.ReplaceAll(content, "\n", " ")
+ content = strings.ReplaceAll(content, "\r", " ")
+
+ // Collapse multiple spaces
+ for strings.Contains(content, " ") {
+ content = strings.ReplaceAll(content, " ", " ")
+ }
+
+ const maxLen = 50
+
+ // Use rune count for proper Unicode handling
+ runes := []rune(content)
+ if len(runes) <= maxLen {
+ return content
+ }
+
+ // Find a good break point (space) before maxLen
+ truncated := string(runes[:maxLen])
+ lastSpace := strings.LastIndex(truncated, " ")
+
+ if lastSpace > 20 {
+ // Break at the last space if it's not too early
+ return truncated[:lastSpace] + "..."
+ }
+
+ // No good break point, just truncate
+ return truncated + "..."
+}
+
// CreateSession creates a new chat session
func (s *Service) CreateSession(ctx context.Context) (*Session, error) {
s.mu.RLock()
@@ -475,6 +560,71 @@ func (s *Service) AnswerQuestion(ctx context.Context, questionID string, answers
return client.AnswerQuestion(ctx, questionID, answers)
}
+// SummarizeSession compresses context when nearing model limits
+func (s *Service) SummarizeSession(ctx context.Context, sessionID string) (map[string]interface{}, error) {
+ s.mu.RLock()
+ client := s.client
+ s.mu.RUnlock()
+
+ if client == nil {
+ return nil, fmt.Errorf("OpenCode not initialized")
+ }
+
+ return client.SummarizeSession(ctx, sessionID)
+}
+
+// GetSessionDiff returns file changes made during a session
+func (s *Service) GetSessionDiff(ctx context.Context, sessionID string) (map[string]interface{}, error) {
+ s.mu.RLock()
+ client := s.client
+ s.mu.RUnlock()
+
+ if client == nil {
+ return nil, fmt.Errorf("OpenCode not initialized")
+ }
+
+ return client.GetSessionDiff(ctx, sessionID)
+}
+
+// ForkSession creates a branch point in the conversation
+func (s *Service) ForkSession(ctx context.Context, sessionID string) (*Session, error) {
+ s.mu.RLock()
+ client := s.client
+ s.mu.RUnlock()
+
+ if client == nil {
+ return nil, fmt.Errorf("OpenCode not initialized")
+ }
+
+ return client.ForkSession(ctx, sessionID)
+}
+
+// RevertSession reverts file changes from the session
+func (s *Service) RevertSession(ctx context.Context, sessionID string) (map[string]interface{}, error) {
+ s.mu.RLock()
+ client := s.client
+ s.mu.RUnlock()
+
+ if client == nil {
+ return nil, fmt.Errorf("OpenCode not initialized")
+ }
+
+ return client.RevertSession(ctx, sessionID)
+}
+
+// UnrevertSession restores previously reverted changes
+func (s *Service) UnrevertSession(ctx context.Context, sessionID string) (map[string]interface{}, error) {
+ s.mu.RLock()
+ client := s.client
+ s.mu.RUnlock()
+
+ if client == nil {
+ return nil, fmt.Errorf("OpenCode not initialized")
+ }
+
+ return client.UnrevertSession(ctx, sessionID)
+}
+
// GetClient returns the underlying OpenCode client for direct access
func (s *Service) GetClient() *Client {
s.mu.RLock()
@@ -517,6 +667,7 @@ func (s *Service) SetAlertProvider(provider mcp.AlertProvider) {
s.mu.Lock()
defer s.mu.Unlock()
+ s.alertProvider = provider // Store for context injection
if s.executor != nil {
s.executor.SetAlertProvider(provider)
}
@@ -630,3 +781,115 @@ func (s *Service) UpdateControlSettings(cfg *config.AIConfig) {
s.SetControlLevel(cfg.GetControlLevel())
s.SetProtectedGuests(cfg.GetProtectedGuests())
}
+
+// buildInfraContext creates a compact real-time infrastructure context string
+// This is injected into every message so the AI always has accurate infrastructure awareness
+func (s *Service) buildInfraContext() string {
+ s.mu.RLock()
+ stateProvider := s.stateProvider
+ agentServer := s.agentServer
+ s.mu.RUnlock()
+
+ if stateProvider == nil {
+ return ""
+ }
+
+ state := stateProvider.GetState()
+
+ // Build a map of connected agents for quick lookup
+ connectedAgents := make(map[string]bool)
+ if agentServer != nil {
+ for _, agent := range agentServer.GetConnectedAgents() {
+ // Key by both AgentID and Hostname for flexible matching
+ connectedAgents[agent.AgentID] = true
+ connectedAgents[agent.Hostname] = true
+ }
+ }
+
+ var sb strings.Builder
+ sb.WriteString("\n\n[CONTEXT: Infrastructure state for reference - use pulse_get_active_alerts tool to check alerts]\n")
+
+ // Group VMs and containers by node
+ nodeVMs := make(map[string][]models.VM)
+ nodeLXCs := make(map[string][]models.Container)
+ for _, vm := range state.VMs {
+ nodeVMs[vm.Node] = append(nodeVMs[vm.Node], vm)
+ }
+ for _, ct := range state.Containers {
+ nodeLXCs[ct.Node] = append(nodeLXCs[ct.Node], ct)
+ }
+
+ // Proxmox nodes
+ if len(state.Nodes) > 0 {
+ sb.WriteString("\nPROXMOX:\n")
+ for _, node := range state.Nodes {
+ canExec := connectedAgents[node.Name] || connectedAgents[node.ID]
+ execStr := "✗"
+ if canExec {
+ execStr = "✓"
+ }
+ sb.WriteString(fmt.Sprintf(" %s [%s] exec=%s\n", node.Name, node.Status, execStr))
+
+ // VMs on this node
+ if vms := nodeVMs[node.Name]; len(vms) > 0 {
+ for _, vm := range vms {
+ sb.WriteString(fmt.Sprintf(" VM %d: %s [%s]\n", vm.VMID, vm.Name, vm.Status))
+ }
+ }
+
+ // LXCs on this node
+ if lxcs := nodeLXCs[node.Name]; len(lxcs) > 0 {
+ for _, ct := range lxcs {
+ sb.WriteString(fmt.Sprintf(" LXC %d: %s [%s]\n", ct.VMID, ct.Name, ct.Status))
+ }
+ }
+ }
+ }
+
+ // Docker hosts with containers
+ if len(state.DockerHosts) > 0 {
+ sb.WriteString("\nDOCKER:\n")
+ for _, host := range state.DockerHosts {
+ canExec := connectedAgents[host.AgentID] || connectedAgents[host.Hostname]
+ execStr := "✗"
+ if canExec {
+ execStr = "✓"
+ }
+ displayName := host.Hostname
+ if host.DisplayName != "" {
+ displayName = host.DisplayName
+ }
+ sb.WriteString(fmt.Sprintf(" %s exec=%s\n", displayName, execStr))
+
+ // Containers on this host
+ running, stopped := 0, 0
+ for _, ct := range host.Containers {
+ if ct.State == "running" {
+ running++
+ } else {
+ stopped++
+ }
+ }
+ if running > 0 || stopped > 0 {
+ sb.WriteString(fmt.Sprintf(" %d running, %d stopped containers\n", running, stopped))
+ }
+ }
+ }
+
+ // Summary
+ sb.WriteString(fmt.Sprintf("\nTOTALS: %d nodes, %d VMs, %d LXCs, %d docker hosts\n",
+ len(state.Nodes), len(state.VMs), len(state.Containers), len(state.DockerHosts)))
+
+ // Execution model explanation
+ sb.WriteString(`
+[EXECUTION MODEL]
+- exec=✓ on a NODE means commands can run on that Proxmox host
+- VMs/LXCs do NOT have agents - to run commands INSIDE them:
+ * For LXC: use pulse_run_command on the NODE with command="pct exec <vmid> -- <your_command>"
+ * For VM: use pulse_run_command on the NODE with command="qm guest exec <vmid> -- <your_command>"
+ * Example: To check memory in LXC 150 on node delly, run "pct exec 150 -- ps aux" on host "delly"
+- Docker hosts with exec=✓ can run docker commands directly
+`)
+
+ return sb.String()
+}
diff --git a/internal/ai/opencode/service_test.go b/internal/ai/opencode/service_test.go
new file mode 100644
index 0000000000..295d5d2452
--- /dev/null
+++ b/internal/ai/opencode/service_test.go
@@ -0,0 +1,73 @@
+package opencode
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestGenerateSessionTitle(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ expected string
+ }{
+ {
+ name: "short message unchanged",
+ input: "How do I check disk space?",
+ expected: "How do I check disk space?",
+ },
+ {
+ name: "long message truncated at word boundary",
+ input: "I need help understanding how to monitor CPU usage across all my Proxmox nodes and containers",
+ expected: "I need help understanding how to monitor CPU...",
+ },
+ {
+ name: "message with newlines normalized",
+ input: "Hello\n\nHow are you?\nI need help",
+ expected: "Hello How are you? I need help",
+ },
+ {
+ name: "message with multiple spaces collapsed",
+ input: "Hello world with spaces",
+ expected: "Hello world with spaces",
+ },
+ {
+ name: "very long word truncated without space",
+ input: "supercalifragilisticexpialidociouslylongwordthatgoesonforeverandever",
+ expected: "supercalifragilisticexpialidociouslylongwordthatgo...",
+ },
+ {
+ name: "unicode characters counted correctly",
+ input: "こんにちは世界!これは日本語のテストです。長い文章を書いています。",
+ expected: "こんにちは世界!これは日本語のテストです。長い文章を書いています。",
+ },
+ {
+ name: "empty string",
+ input: "",
+ expected: "",
+ },
+ {
+ name: "exactly 50 characters",
+ input: "12345678901234567890123456789012345678901234567890",
+ expected: "12345678901234567890123456789012345678901234567890",
+ },
+ {
+ name: "51 characters truncated",
+ input: "123456789012345678901234567890123456789012345678901",
+ expected: "12345678901234567890123456789012345678901234567890...",
+ },
+ {
+ name: "leading/trailing whitespace trimmed",
+ input: " Hello world ",
+ expected: "Hello world",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := generateSessionTitle(tt.input)
+ assert.Equal(t, tt.expected, result)
+ })
+ }
+}
diff --git a/internal/ai/opencode/sidecar.go b/internal/ai/opencode/sidecar.go
index e462092d87..56206fe766 100644
--- a/internal/ai/opencode/sidecar.go
+++ b/internal/ai/opencode/sidecar.go
@@ -254,25 +254,11 @@ func (s *Sidecar) writeConfig() error {
var configParts []string
configParts = append(configParts, ` "$schema": "https://opencode.ai/config.json"`)
- // Inject System Instructions
+ // Inject System Instructions - kept minimal since tool descriptions contain detailed guidance
instructions := ` "instructions": [
- "You are Pulse's AI assistant for infrastructure monitoring and management.",
- "You have access to pulse_* MCP tools. ALWAYS use them for infrastructure questions:",
- "- pulse_get_infrastructure_state: Get all VMs, containers, hosts",
- "- pulse_get_active_alerts: Get current alerts and warnings",
- "- pulse_get_metrics_history: Get CPU/memory/disk history for resources",
- "- pulse_get_resource_details: Get details for a specific VM/container",
- "- pulse_get_baselines: Get learned normal behavior",
- "- pulse_get_patterns: Get detected patterns and predictions",
- "- pulse_get_disk_health: Get SMART data and disk status",
- "- pulse_get_storage: Get storage pool information",
- "- pulse_get_agent_scope: Inspect agent scope and profile settings",
- "- pulse_set_agent_scope: Safely update unified agent scope via profiles",
- "- pulse_run_command: Execute commands on managed hosts (only when control level allows)",
- "When asked about infrastructure, VMs, containers, alerts, metrics, or system status, ALWAYS use pulse_* tools.",
- "Use pulse_set_agent_scope for agent module changes instead of running shell commands.",
- "Do NOT use webfetch for infrastructure questions - use the MCP tools.",
- "Be concise and direct. Focus on actionable insights."
+ "You are Pulse's infrastructure assistant. Be concise and direct.",
+ "Read tool descriptions carefully - they explain what each tool returns and when to use it.",
+ "For status questions, one tool call is usually enough. Trust the data returned."
]`
configParts = append(configParts, instructions)
diff --git a/internal/ai/service.go b/internal/ai/service.go
index dfa22ff3ca..5fbed3915c 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -944,7 +944,8 @@ func (s *Service) LoadConfig() error {
log.Info().
Str("provider", selectedProvider).
Str("model", selectedModel).
- Bool("autonomous_mode", cfg.AutonomousMode).
+ Str("control_level", cfg.GetControlLevel()).
+ Bool("autonomous", cfg.IsAutonomous()).
Msg("AI service initialized")
return nil
@@ -1062,7 +1063,7 @@ func (s *Service) GetDebugContext(req ExecuteRequest) map[string]interface{} {
func (s *Service) IsAutonomous() bool {
s.mu.RLock()
defer s.mu.RUnlock()
- if s.cfg == nil || !s.cfg.AutonomousMode {
+ if s.cfg == nil || !s.cfg.IsAutonomous() {
return false
}
// Autonomous mode requires Pro license with ai_autofix feature
diff --git a/internal/config/ai.go b/internal/config/ai.go
index 1b305ce324..acbdb25afa 100644
--- a/internal/config/ai.go
+++ b/internal/config/ai.go
@@ -501,9 +501,15 @@ func (c *AIConfig) GetRequestTimeout() time.Duration {
return 300 * time.Second // 5 minutes default
}
-// GetControlLevel returns the AI control level, defaulting to read_only if not set
+// GetControlLevel returns the AI control level, defaulting to read_only if not set.
+// For backwards compatibility, if ControlLevel is empty but legacy AutonomousMode is true,
+// returns autonomous to preserve existing behavior.
func (c *AIConfig) GetControlLevel() string {
if c.ControlLevel == "" {
+ // Legacy migration: honor old autonomous_mode field if set
+ if c.AutonomousMode {
+ return ControlLevelAutonomous
+ }
return ControlLevelReadOnly
}
return c.ControlLevel
@@ -515,6 +521,11 @@ func (c *AIConfig) IsControlEnabled() bool {
return level != ControlLevelReadOnly
}
+// IsAutonomous returns true if AI is configured for autonomous operation (no approval needed)
+func (c *AIConfig) IsAutonomous() bool {
+ return c.GetControlLevel() == ControlLevelAutonomous
+}
+
// IsValidControlLevel checks if a control level string is valid
func IsValidControlLevel(level string) bool {
switch level {