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): Add native chat service with streaming and tool execution

rcourtman5ff4f97a0dbd
diff --git a/internal/ai/chat/agentic.go b/internal/ai/chat/agentic.go
new file mode 100644
index 0000000000..bdbec4e226
--- /dev/null
+++ b/internal/ai/chat/agentic.go
@@ -0,0 +1,426 @@
+package chat
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
+ "github.com/rs/zerolog/log"
+)
+
+// AgenticLoop handles the tool-calling loop with streaming
+type AgenticLoop struct {
+ provider providers.StreamingProvider
+ executor *tools.PulseToolExecutor
+ tools []providers.Tool
+ systemPrompt string
+ maxTurns int
+
+ // State for ongoing executions
+ mu sync.Mutex
+ aborted map[string]bool // sessionID -> aborted
+ pendingQs map[string]chan []QuestionAnswer // questionID -> answer channel
+}
+
+// NewAgenticLoop creates a new agentic loop
+func NewAgenticLoop(provider providers.StreamingProvider, executor *tools.PulseToolExecutor, systemPrompt string) *AgenticLoop {
+ // Convert MCP tools to provider format
+ mcpTools := executor.ListTools()
+ providerTools := ConvertMCPToolsToProvider(mcpTools)
+
+ return &AgenticLoop{
+ provider: provider,
+ executor: executor,
+ tools: providerTools,
+ systemPrompt: systemPrompt,
+ maxTurns: MaxAgenticTurns,
+ aborted: make(map[string]bool),
+ pendingQs: make(map[string]chan []QuestionAnswer),
+ }
+}
+
+// UpdateTools refreshes the tool list from the executor
+func (a *AgenticLoop) UpdateTools() {
+ mcpTools := a.executor.ListTools()
+ a.tools = ConvertMCPToolsToProvider(mcpTools)
+}
+
+// Execute runs the agentic loop with streaming
+func (a *AgenticLoop) Execute(ctx context.Context, sessionID string, messages []Message, callback StreamCallback) ([]Message, error) {
+ // Track this session for potential abort
+ a.mu.Lock()
+ a.aborted[sessionID] = false
+ a.mu.Unlock()
+ defer func() {
+ a.mu.Lock()
+ delete(a.aborted, sessionID)
+ a.mu.Unlock()
+ }()
+
+ // Convert our messages to provider format
+ providerMessages := convertToProviderMessages(messages)
+
+ var resultMessages []Message
+ turn := 0
+
+ for turn < a.maxTurns {
+ // Check if aborted
+ a.mu.Lock()
+ if a.aborted[sessionID] {
+ a.mu.Unlock()
+ return resultMessages, fmt.Errorf("session aborted")
+ }
+ a.mu.Unlock()
+
+ // Check context
+ select {
+ case <-ctx.Done():
+ return resultMessages, ctx.Err()
+ default:
+ }
+
+ log.Debug().
+ Int("turn", turn).
+ Int("messages", len(providerMessages)).
+ Int("tools", len(a.tools)).
+ Msg("Agentic loop turn")
+
+ // Build the request
+ req := providers.ChatRequest{
+ Messages: providerMessages,
+ System: a.systemPrompt,
+ Tools: a.tools,
+ }
+
+ // Collect streaming response
+ var contentBuilder strings.Builder
+ var thinkingBuilder strings.Builder
+ var toolCalls []providers.ToolCall
+
+ err := a.provider.ChatStream(ctx, req, func(event providers.StreamEvent) {
+ switch event.Type {
+ case "content":
+ if data, ok := event.Data.(providers.ContentEvent); ok {
+ contentBuilder.WriteString(data.Text)
+ // Forward to callback - send plain string as frontend expects
+ jsonData, _ := json.Marshal(data.Text)
+ callback(StreamEvent{Type: "content", Data: jsonData})
+ }
+
+ case "thinking":
+ if data, ok := event.Data.(providers.ThinkingEvent); ok {
+ thinkingBuilder.WriteString(data.Text)
+ // Forward to callback - send plain string as frontend expects
+ jsonData, _ := json.Marshal(data.Text)
+ callback(StreamEvent{Type: "thinking", Data: jsonData})
+ }
+
+ case "tool_start":
+ if data, ok := event.Data.(providers.ToolStartEvent); ok {
+ // Convert input to JSON string for frontend
+ inputStr := "{}"
+ if data.Input != nil {
+ if inputBytes, err := json.Marshal(data.Input); err == nil {
+ inputStr = string(inputBytes)
+ }
+ }
+ jsonData, _ := json.Marshal(ToolStartData{
+ ID: data.ID,
+ Name: data.Name,
+ Input: inputStr,
+ })
+ callback(StreamEvent{Type: "tool_start", Data: jsonData})
+ }
+
+ case "done":
+ if data, ok := event.Data.(providers.DoneEvent); ok {
+ toolCalls = data.ToolCalls
+ }
+
+ case "error":
+ if data, ok := event.Data.(providers.ErrorEvent); ok {
+ jsonData, _ := json.Marshal(ErrorData{Message: data.Message})
+ callback(StreamEvent{Type: "error", Data: jsonData})
+ }
+ }
+ })
+
+ if err != nil {
+ return resultMessages, fmt.Errorf("provider error: %w", err)
+ }
+
+ // Create assistant message
+ assistantMsg := Message{
+ ID: uuid.New().String(),
+ Role: "assistant",
+ Content: contentBuilder.String(),
+ ReasoningContent: thinkingBuilder.String(),
+ Timestamp: time.Now(),
+ }
+
+ if len(toolCalls) > 0 {
+ assistantMsg.ToolCalls = make([]ToolCall, len(toolCalls))
+ for i, tc := range toolCalls {
+ assistantMsg.ToolCalls[i] = ToolCall{
+ ID: tc.ID,
+ Name: tc.Name,
+ Input: tc.Input,
+ }
+ }
+ }
+
+ resultMessages = append(resultMessages, assistantMsg)
+
+ // Convert to provider format for next turn
+ providerAssistant := providers.Message{
+ Role: "assistant",
+ Content: assistantMsg.Content,
+ ReasoningContent: assistantMsg.ReasoningContent,
+ }
+ for _, tc := range toolCalls {
+ providerAssistant.ToolCalls = append(providerAssistant.ToolCalls, providers.ToolCall{
+ ID: tc.ID,
+ Name: tc.Name,
+ Input: tc.Input,
+ })
+ }
+ providerMessages = append(providerMessages, providerAssistant)
+
+ // If no tool calls, we're done
+ if len(toolCalls) == 0 {
+ log.Debug().Msg("Agentic loop complete - no tool calls")
+ return resultMessages, nil
+ }
+
+ // Execute tool calls
+ for _, tc := range toolCalls {
+ // Check for abort
+ a.mu.Lock()
+ if a.aborted[sessionID] {
+ a.mu.Unlock()
+ return resultMessages, fmt.Errorf("session aborted")
+ }
+ a.mu.Unlock()
+
+ log.Debug().
+ Str("tool", tc.Name).
+ Str("id", tc.ID).
+ Msg("Executing tool")
+
+ // Execute the tool
+ result, err := a.executor.ExecuteTool(ctx, tc.Name, tc.Input)
+
+ var resultText string
+ var isError bool
+
+ if err != nil {
+ resultText = fmt.Sprintf("Error: %v", err)
+ isError = true
+ } else {
+ resultText = FormatToolResult(result)
+ isError = result.IsError
+ }
+
+ // Check if this is an approval request
+ if strings.HasPrefix(resultText, "APPROVAL_REQUIRED:") {
+ // Parse approval request
+ approvalJSON := strings.TrimPrefix(resultText, "APPROVAL_REQUIRED:")
+ approvalJSON = strings.TrimSpace(approvalJSON)
+
+ var approvalData struct {
+ ApprovalID string `json:"approval_id"`
+ Command string `json:"command"`
+ Risk string `json:"risk"`
+ Description string `json:"description"`
+ }
+ if err := json.Unmarshal([]byte(approvalJSON), &approvalData); err != nil {
+ log.Error().Err(err).Str("data", approvalJSON).Msg("Failed to parse approval request")
+ resultText = "Error: failed to parse approval request"
+ isError = true
+ } else {
+ // Send approval_needed event
+ jsonData, _ := json.Marshal(ApprovalNeededData{
+ ApprovalID: approvalData.ApprovalID,
+ ToolID: tc.ID,
+ ToolName: tc.Name,
+ Command: approvalData.Command,
+ RunOnHost: true, // Control commands run on host
+ TargetHost: "", // Will be filled from approval context if available
+ Risk: approvalData.Risk,
+ Description: approvalData.Description,
+ })
+ callback(StreamEvent{Type: "approval_needed", Data: jsonData})
+
+ // Wait for approval decision (poll with timeout)
+ store := approval.GetStore()
+ if store != nil {
+ approvalCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
+ decision, waitErr := waitForApprovalDecision(approvalCtx, store, approvalData.ApprovalID)
+ cancel()
+
+ if waitErr != nil {
+ resultText = fmt.Sprintf("Approval timeout or error: %v", waitErr)
+ isError = true
+ } else if decision.Status == approval.StatusApproved {
+ // Re-execute the tool with approval granted
+ // Add approval_id to input so tool knows this is pre-approved
+ inputWithApproval := make(map[string]interface{})
+ for k, v := range tc.Input {
+ inputWithApproval[k] = v
+ }
+ inputWithApproval["_approval_id"] = approvalData.ApprovalID
+ result, err = a.executor.ExecuteTool(ctx, tc.Name, inputWithApproval)
+ if err != nil {
+ resultText = fmt.Sprintf("Error after approval: %v", err)
+ isError = true
+ } else {
+ resultText = FormatToolResult(result)
+ isError = result.IsError
+ }
+ } else {
+ resultText = fmt.Sprintf("Command denied: %s", decision.DenyReason)
+ isError = false
+ }
+ } else {
+ resultText = "Approval system not available"
+ isError = true
+ }
+ }
+ }
+
+ // Send tool_end event
+ // Convert input to JSON string for frontend display
+ inputStr := ""
+ if tc.Input != nil {
+ if inputBytes, err := json.Marshal(tc.Input); err == nil {
+ inputStr = string(inputBytes)
+ }
+ }
+ jsonData, _ := json.Marshal(ToolEndData{
+ ID: tc.ID,
+ Name: tc.Name,
+ Input: inputStr,
+ Output: resultText,
+ Success: !isError,
+ })
+ callback(StreamEvent{Type: "tool_end", Data: jsonData})
+
+ // Create tool result message
+ toolResultMsg := Message{
+ ID: uuid.New().String(),
+ Role: "user", // Tool results are sent as user messages
+ Timestamp: time.Now(),
+ ToolResult: &ToolResult{
+ ToolUseID: tc.ID,
+ Content: resultText,
+ IsError: isError,
+ },
+ }
+ resultMessages = append(resultMessages, toolResultMsg)
+
+ // Add to provider messages for next turn
+ providerMessages = append(providerMessages, providers.Message{
+ Role: "user",
+ ToolResult: &providers.ToolResult{
+ ToolUseID: tc.ID,
+ Content: resultText,
+ IsError: isError,
+ },
+ })
+ }
+
+ turn++
+ }
+
+ log.Warn().Int("max_turns", a.maxTurns).Msg("Agentic loop hit max turns limit")
+ return resultMessages, nil
+}
+
+// Abort aborts an ongoing session
+func (a *AgenticLoop) Abort(sessionID string) {
+ a.mu.Lock()
+ a.aborted[sessionID] = true
+ a.mu.Unlock()
+}
+
+// AnswerQuestion provides an answer to a pending question
+func (a *AgenticLoop) AnswerQuestion(questionID string, answers []QuestionAnswer) error {
+ a.mu.Lock()
+ ch, exists := a.pendingQs[questionID]
+ a.mu.Unlock()
+
+ if !exists {
+ return fmt.Errorf("no pending question with ID: %s", questionID)
+ }
+
+ // Non-blocking send
+ select {
+ case ch <- answers:
+ return nil
+ default:
+ return fmt.Errorf("question already answered: %s", questionID)
+ }
+}
+
+// waitForApprovalDecision polls for an approval decision
+func waitForApprovalDecision(ctx context.Context, store *approval.Store, approvalID string) (*approval.ApprovalRequest, error) {
+ ticker := time.NewTicker(500 * time.Millisecond)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-ticker.C:
+ req, ok := store.GetApproval(approvalID)
+ if !ok {
+ return nil, fmt.Errorf("approval request not found: %s", approvalID)
+ }
+ if req.Status != approval.StatusPending {
+ return req, nil
+ }
+ }
+ }
+}
+
+// convertToProviderMessages converts our messages to provider format
+func convertToProviderMessages(messages []Message) []providers.Message {
+ result := make([]providers.Message, 0, len(messages))
+
+ for _, m := range messages {
+ pm := providers.Message{
+ Role: m.Role,
+ Content: m.Content,
+ ReasoningContent: m.ReasoningContent,
+ }
+
+ if len(m.ToolCalls) > 0 {
+ for _, tc := range m.ToolCalls {
+ pm.ToolCalls = append(pm.ToolCalls, providers.ToolCall{
+ ID: tc.ID,
+ Name: tc.Name,
+ Input: tc.Input,
+ })
+ }
+ }
+
+ if m.ToolResult != nil {
+ pm.ToolResult = &providers.ToolResult{
+ ToolUseID: m.ToolResult.ToolUseID,
+ Content: m.ToolResult.Content,
+ IsError: m.ToolResult.IsError,
+ }
+ }
+
+ result = append(result, pm)
+ }
+
+ return result
+}
diff --git a/internal/ai/chat/patrol.go b/internal/ai/chat/patrol.go
new file mode 100644
index 0000000000..a71fd3f117
--- /dev/null
+++ b/internal/ai/chat/patrol.go
@@ -0,0 +1,415 @@
+package chat
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "regexp"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/rs/zerolog/log"
+)
+
+// PatrolFinding represents a finding from AI patrol analysis
+type PatrolFinding struct {
+ ID string `json:"id"`
+ Key string `json:"key"`
+ Severity string `json:"severity"`
+ Category string `json:"category"`
+ ResourceID string `json:"resource_id"`
+ ResourceName string `json:"resource_name"`
+ ResourceType string `json:"resource_type"`
+ Title string `json:"title"`
+ Description string `json:"description"`
+ Recommendation string `json:"recommendation"`
+ Evidence string `json:"evidence"`
+ Source string `json:"source"`
+ DetectedAt time.Time `json:"detected_at"`
+ LastSeenAt time.Time `json:"last_seen_at"`
+}
+
+// FindingsStore interface for storing patrol findings
+type FindingsStore interface {
+ Add(finding *PatrolFinding) bool // Returns true if finding is new
+ GetActive() []*PatrolFinding
+ GetDismissed() []*PatrolFinding
+}
+
+// PatrolStreamCallback is called for patrol streaming updates
+type PatrolStreamCallback func(event PatrolStreamEvent)
+
+// PatrolStreamEvent represents a streaming update from patrol
+type PatrolStreamEvent struct {
+ Type string `json:"type"` // "start", "content", "thinking", "tool_use", "complete", "error"
+ Content string `json:"content,omitempty"`
+ Phase string `json:"phase,omitempty"`
+}
+
+// PatrolResult contains the results of a patrol run
+type PatrolResult struct {
+ Findings []*PatrolFinding
+ NewFindings int
+ RawResponse string
+ InputTokens int
+ OutputTokens int
+ Duration time.Duration
+ Error error
+}
+
+// PatrolService runs AI patrol analysis
+type PatrolService struct {
+ mu sync.RWMutex
+
+ service *Service // Chat service
+ findingsStore FindingsStore // For storing findings
+ sessionID string // Dedicated patrol session
+ running bool // Whether a patrol is currently running
+ lastRun time.Time // Last patrol run time
+ lastResult *PatrolResult // Last patrol result
+
+ // Streaming support
+ streamMu sync.RWMutex
+ subscribers map[chan PatrolStreamEvent]struct{}
+ currentOutput strings.Builder
+}
+
+// NewPatrolService creates a new patrol service
+func NewPatrolService(service *Service) *PatrolService {
+ return &PatrolService{
+ service: service,
+ subscribers: make(map[chan PatrolStreamEvent]struct{}),
+ }
+}
+
+// SetFindingsStore sets the findings store for persisting patrol results
+func (p *PatrolService) SetFindingsStore(store FindingsStore) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.findingsStore = store
+}
+
+// IsRunning returns whether a patrol is currently executing
+func (p *PatrolService) IsRunning() bool {
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+ return p.running
+}
+
+// GetLastResult returns the most recent patrol result
+func (p *PatrolService) GetLastResult() *PatrolResult {
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+ return p.lastResult
+}
+
+// Subscribe returns a channel for receiving patrol stream events
+func (p *PatrolService) Subscribe() chan PatrolStreamEvent {
+ ch := make(chan PatrolStreamEvent, 100)
+ p.streamMu.Lock()
+ p.subscribers[ch] = struct{}{}
+ p.streamMu.Unlock()
+ return ch
+}
+
+// Unsubscribe removes a subscriber channel
+func (p *PatrolService) Unsubscribe(ch chan PatrolStreamEvent) {
+ p.streamMu.Lock()
+ delete(p.subscribers, ch)
+ p.streamMu.Unlock()
+ close(ch)
+}
+
+// broadcast sends an event to all subscribers
+func (p *PatrolService) broadcast(event PatrolStreamEvent) {
+ p.streamMu.RLock()
+ defer p.streamMu.RUnlock()
+
+ for ch := range p.subscribers {
+ select {
+ case ch <- event:
+ default:
+ // Channel full, skip
+ }
+ }
+}
+
+// RunPatrol executes a patrol analysis
+func (p *PatrolService) RunPatrol(ctx context.Context) error {
+ _, err := p.RunPatrolWithResult(ctx)
+ return err
+}
+
+// RunPatrolWithResult executes a patrol analysis and returns detailed results
+func (p *PatrolService) RunPatrolWithResult(ctx context.Context) (*PatrolResult, error) {
+ p.mu.Lock()
+ if p.running {
+ p.mu.Unlock()
+ return nil, fmt.Errorf("patrol already running")
+ }
+ p.running = true
+ p.mu.Unlock()
+
+ defer func() {
+ p.mu.Lock()
+ p.running = false
+ p.mu.Unlock()
+ }()
+
+ start := time.Now()
+ result := &PatrolResult{}
+
+ // Check service is available
+ if p.service == nil || !p.service.IsRunning() {
+ result.Error = fmt.Errorf("AI service not available")
+ return result, result.Error
+ }
+
+ // Build patrol prompt
+ prompt := p.buildPatrolPrompt()
+
+ log.Info().Msg("AI Patrol: Starting infrastructure analysis")
+ p.broadcast(PatrolStreamEvent{Type: "start", Phase: "Starting patrol analysis"})
+
+ // Clear output buffer
+ p.streamMu.Lock()
+ p.currentOutput.Reset()
+ p.streamMu.Unlock()
+
+ // Execute via chat service streaming
+ var responseBuffer strings.Builder
+
+ err := p.service.ExecuteStream(ctx, ExecuteRequest{
+ Prompt: prompt,
+ SessionID: p.sessionID,
+ }, func(event StreamEvent) {
+ switch event.Type {
+ case "content":
+ var contentEvent ContentData
+ if json.Unmarshal(event.Data, &contentEvent) == nil && contentEvent.Text != "" {
+ responseBuffer.WriteString(contentEvent.Text)
+ p.streamMu.Lock()
+ p.currentOutput.WriteString(contentEvent.Text)
+ p.streamMu.Unlock()
+ p.broadcast(PatrolStreamEvent{Type: "content", Content: contentEvent.Text})
+ }
+ case "thinking":
+ var thinkingEvent ThinkingData
+ if json.Unmarshal(event.Data, &thinkingEvent) == nil && thinkingEvent.Text != "" {
+ p.broadcast(PatrolStreamEvent{Type: "thinking", Content: thinkingEvent.Text})
+ }
+ case "tool_start":
+ p.broadcast(PatrolStreamEvent{Type: "tool_use", Phase: "Using tools to gather context"})
+ }
+ })
+
+ if err != nil {
+ result.Error = err
+ result.Duration = time.Since(start)
+ p.broadcast(PatrolStreamEvent{Type: "error", Content: err.Error()})
+ log.Error().Err(err).Msg("AI Patrol: Analysis failed")
+ return result, err
+ }
+
+ result.RawResponse = responseBuffer.String()
+ result.Duration = time.Since(start)
+
+ // Parse findings from response
+ findings := p.parseFindings(result.RawResponse)
+ result.Findings = findings
+
+ // Store findings
+ p.mu.RLock()
+ store := p.findingsStore
+ p.mu.RUnlock()
+
+ if store != nil {
+ for _, f := range findings {
+ if store.Add(f) {
+ result.NewFindings++
+ }
+ }
+ } else {
+ result.NewFindings = len(findings)
+ }
+
+ // Save result
+ p.mu.Lock()
+ p.lastRun = time.Now()
+ p.lastResult = result
+ p.mu.Unlock()
+
+ p.broadcast(PatrolStreamEvent{Type: "complete", Phase: "Patrol complete"})
+
+ log.Info().
+ Int("findings", len(findings)).
+ Int("new_findings", result.NewFindings).
+ Dur("duration", result.Duration).
+ Msg("AI Patrol: Analysis complete")
+
+ return result, nil
+}
+
+// buildPatrolPrompt creates the prompt for patrol analysis
+func (p *PatrolService) buildPatrolPrompt() string {
+ return `You are performing a scheduled infrastructure patrol for Pulse, a Proxmox monitoring system.
+
+## Your Task
+Analyze the current infrastructure state and identify issues that require human attention. Use the available tools to gather context.
+
+## Available Tools
+Use these tools to gather information:
+- pulse_get_topology: Get current state of all monitored infrastructure
+- pulse_get_metrics: Get metrics for trend analysis
+- pulse_get_active_alerts: Get currently active alerts
+- pulse_get_findings: Get existing patrol findings
+
+## Steps
+1. First call pulse_get_topology to see what's being monitored
+2. Check pulse_get_active_alerts for any ongoing issues
+3. Review pulse_get_findings to see previously identified issues
+4. For any resources that look concerning, use pulse_get_metrics for trend analysis
+
+## Output Format
+For each issue found, output in this EXACT format:
+
+[FINDING]
+KEY: <stable-issue-key>
+SEVERITY: critical|warning|watch|info
+CATEGORY: performance|reliability|security|capacity|configuration
+RESOURCE: <resource-name>
+RESOURCE_TYPE: node|vm|container|docker_container|storage|host
+TITLE: <brief title>
+DESCRIPTION: <detailed description>
+RECOMMENDATION: <actionable recommendation>
+EVIDENCE: <supporting data>
+[/FINDING]
+
+## Severity Guidelines (be conservative)
+- CRITICAL: Service down, data loss imminent, disk >95%, node offline
+- WARNING: Disk >85%, memory >90% sustained, backup failed >48h
+- WATCH: Trends approaching thresholds within 7 days
+- INFO: Minor config issues only
+
+## DO NOT Report
+- Stopped VMs/containers (unless they crashed with autostart enabled)
+- Minor fluctuations from baseline
+- Resources simply "busier than usual" but not near limits
+
+If everything is healthy, output NO findings. An empty report is the best report.
+
+Begin your patrol now.`
+}
+
+// parseFindings extracts findings from the AI response
+func (p *PatrolService) parseFindings(response string) []*PatrolFinding {
+ var findings []*PatrolFinding
+
+ findingRe := regexp.MustCompile(`(?s)\[FINDING\](.*?)\[/FINDING\]`)
+ matches := findingRe.FindAllStringSubmatch(response, -1)
+
+ for _, match := range matches {
+ if len(match) < 2 {
+ continue
+ }
+ block := match[1]
+
+ finding := p.parseFindingBlock(block)
+ if finding != nil {
+ findings = append(findings, finding)
+ }
+ }
+
+ return findings
+}
+
+// parseFindingBlock parses a single finding block
+func (p *PatrolService) parseFindingBlock(block string) *PatrolFinding {
+ extractField := func(name string) string {
+ re := regexp.MustCompile(`(?i)` + name + `:\s*(.+?)(?:\n|$)`)
+ match := re.FindStringSubmatch(block)
+ if len(match) >= 2 {
+ return strings.TrimSpace(match[1])
+ }
+ return ""
+ }
+
+ key := extractField("KEY")
+ severity := strings.ToLower(extractField("SEVERITY"))
+ category := strings.ToLower(extractField("CATEGORY"))
+ resource := extractField("RESOURCE")
+ resourceType := strings.ToLower(extractField("RESOURCE_TYPE"))
+ title := extractField("TITLE")
+ description := extractField("DESCRIPTION")
+ recommendation := extractField("RECOMMENDATION")
+ evidence := extractField("EVIDENCE")
+
+ if key == "" || title == "" {
+ return nil
+ }
+
+ validSeverities := map[string]bool{"critical": true, "warning": true, "watch": true, "info": true}
+ if !validSeverities[severity] {
+ severity = "info"
+ }
+
+ validCategories := map[string]bool{"performance": true, "reliability": true, "security": true, "capacity": true, "configuration": true}
+ if !validCategories[category] {
+ category = "configuration"
+ }
+
+ id := generateFindingID(resource, category, key)
+
+ now := time.Now()
+ return &PatrolFinding{
+ ID: id,
+ Key: key,
+ Severity: severity,
+ Category: category,
+ ResourceID: resource,
+ ResourceName: resource,
+ ResourceType: resourceType,
+ Title: title,
+ Description: description,
+ Recommendation: recommendation,
+ Evidence: evidence,
+ Source: "ai-patrol",
+ DetectedAt: now,
+ LastSeenAt: now,
+ }
+}
+
+// generateFindingID creates a stable ID for a finding
+func generateFindingID(resourceID, category, key string) string {
+ input := fmt.Sprintf("%s:%s:%s", resourceID, category, key)
+ hash := sha256.Sum256([]byte(input))
+ return fmt.Sprintf("%x", hash[:8])
+}
+
+// CreatePatrolSession creates a dedicated session for patrol
+func (p *PatrolService) CreatePatrolSession(ctx context.Context) error {
+ if p.service == nil || !p.service.IsRunning() {
+ return fmt.Errorf("AI service not available")
+ }
+
+ session, err := p.service.CreateSession(ctx)
+ if err != nil {
+ return fmt.Errorf("failed to create patrol session: %w", err)
+ }
+
+ p.mu.Lock()
+ p.sessionID = session.ID
+ p.mu.Unlock()
+
+ log.Info().Str("session_id", session.ID).Msg("AI Patrol: Created dedicated session")
+ return nil
+}
+
+// GetSessionID returns the current patrol session ID
+func (p *PatrolService) GetSessionID() string {
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+ return p.sessionID
+}
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
new file mode 100644
index 0000000000..9c68e2e88d
--- /dev/null
+++ b/internal/ai/chat/service.go
@@ -0,0 +1,620 @@
+package chat
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rs/zerolog/log"
+)
+
+// StateProvider provides access to infrastructure state
+type StateProvider interface {
+ GetState() models.StateSnapshot
+}
+
+// CommandPolicy evaluates command security
+type CommandPolicy interface {
+ Evaluate(command string) agentexec.PolicyDecision
+}
+
+// AgentServer executes commands on agents
+type AgentServer interface {
+ GetConnectedAgents() []agentexec.ConnectedAgent
+ ExecuteCommand(ctx context.Context, agentID string, cmd agentexec.ExecuteCommandPayload) (*agentexec.CommandResultPayload, error)
+}
+
+// MCP provider type aliases for external use
+type (
+ MCPAlertProvider = tools.AlertProvider
+ MCPFindingsProvider = tools.FindingsProvider
+ MCPBaselineProvider = tools.BaselineProvider
+ MCPPatternProvider = tools.PatternProvider
+ MCPMetricsHistoryProvider = tools.MetricsHistoryProvider
+ MCPBackupProvider = tools.BackupProvider
+ MCPStorageProvider = tools.StorageProvider
+ MCPDiskHealthProvider = tools.DiskHealthProvider
+ MCPUpdatesProvider = tools.UpdatesProvider
+ AgentProfileManager = tools.AgentProfileManager
+ FindingsManager = tools.FindingsManager
+ MetadataUpdater = tools.MetadataUpdater
+)
+
+// Config holds service configuration
+type Config struct {
+ AIConfig *config.AIConfig
+ StateProvider StateProvider
+ Policy CommandPolicy
+ AgentServer AgentServer
+ DataDir string
+}
+
+// Service provides direct AI chat without external sidecar
+type Service struct {
+ mu sync.RWMutex
+
+ cfg *config.AIConfig
+ stateProvider StateProvider
+ agentServer AgentServer
+ executor *tools.PulseToolExecutor
+ sessions *SessionStore
+ agenticLoop *AgenticLoop
+ started bool
+}
+
+// NewService creates a new chat service
+func NewService(cfg Config) *Service {
+ // Create tool executor
+ var stateProvider tools.StateProvider
+ var policy tools.CommandPolicy
+ var agentServer tools.AgentServer
+
+ if cfg.StateProvider != nil {
+ stateProvider = &stateProviderAdapter{cfg.StateProvider}
+ }
+ if cfg.Policy != nil {
+ policy = &commandPolicyAdapter{cfg.Policy}
+ }
+ if cfg.AgentServer != nil {
+ agentServer = &agentServerAdapter{cfg.AgentServer}
+ }
+
+ execCfg := tools.ExecutorConfig{
+ StateProvider: stateProvider,
+ Policy: policy,
+ AgentServer: agentServer,
+ }
+
+ if cfg.AIConfig != nil {
+ execCfg.ControlLevel = tools.ControlLevel(cfg.AIConfig.GetControlLevel())
+ execCfg.ProtectedGuests = cfg.AIConfig.GetProtectedGuests()
+ }
+
+ executor := tools.NewPulseToolExecutor(execCfg)
+
+ return &Service{
+ cfg: cfg.AIConfig,
+ stateProvider: cfg.StateProvider,
+ agentServer: cfg.AgentServer,
+ executor: executor,
+ }
+}
+
+// Adapter types
+type stateProviderAdapter struct {
+ sp StateProvider
+}
+
+func (a *stateProviderAdapter) GetState() models.StateSnapshot {
+ return a.sp.GetState()
+}
+
+type commandPolicyAdapter struct {
+ p CommandPolicy
+}
+
+func (a *commandPolicyAdapter) Evaluate(command string) agentexec.PolicyDecision {
+ return a.p.Evaluate(command)
+}
+
+type agentServerAdapter struct {
+ s AgentServer
+}
+
+func (a *agentServerAdapter) GetConnectedAgents() []agentexec.ConnectedAgent {
+ return a.s.GetConnectedAgents()
+}
+
+func (a *agentServerAdapter) ExecuteCommand(ctx context.Context, agentID string, cmd agentexec.ExecuteCommandPayload) (*agentexec.CommandResultPayload, error) {
+ return a.s.ExecuteCommand(ctx, agentID, cmd)
+}
+
+// Start initializes the service
+func (s *Service) Start(ctx context.Context) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if s.started {
+ return nil
+ }
+
+ if s.cfg == nil {
+ return fmt.Errorf("AI config is nil")
+ }
+
+ // Create session store
+ dataDir := s.cfg.OpenCodeDataDir
+ if dataDir == "" {
+ dataDir = "/tmp/pulse-ai"
+ }
+
+ store, err := NewSessionStore(dataDir)
+ if err != nil {
+ return fmt.Errorf("failed to create session store: %w", err)
+ }
+ s.sessions = store
+
+ // Create provider
+ provider, err := s.createProvider()
+ if err != nil {
+ return fmt.Errorf("failed to create provider: %w", err)
+ }
+
+ // Create agentic loop
+ systemPrompt := s.buildSystemPrompt()
+ s.agenticLoop = NewAgenticLoop(provider, s.executor, systemPrompt)
+
+ s.started = true
+ log.Info().
+ Str("model", s.cfg.GetChatModel()).
+ Str("data_dir", dataDir).
+ Msg("Pulse AI (direct) started")
+
+ return nil
+}
+
+// Stop stops the service
+func (s *Service) Stop(ctx context.Context) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ s.started = false
+ log.Info().Msg("Pulse AI (direct) stopped")
+ return nil
+}
+
+// Restart restarts the service with new config
+func (s *Service) Restart(ctx context.Context, newCfg *config.AIConfig) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if !s.started {
+ return fmt.Errorf("service not started")
+ }
+
+ if newCfg != nil {
+ s.cfg = newCfg
+ }
+
+ // Update executor settings
+ if s.executor != nil && s.cfg != nil {
+ s.executor.SetControlLevel(tools.ControlLevel(s.cfg.GetControlLevel()))
+ s.executor.SetProtectedGuests(s.cfg.GetProtectedGuests())
+ }
+
+ // Recreate provider with new settings
+ provider, err := s.createProvider()
+ if err != nil {
+ return fmt.Errorf("failed to create provider: %w", err)
+ }
+
+ // Update agentic loop
+ systemPrompt := s.buildSystemPrompt()
+ s.agenticLoop = NewAgenticLoop(provider, s.executor, systemPrompt)
+
+ log.Info().
+ Str("model", s.cfg.GetChatModel()).
+ Msg("Pulse AI restarted with new config")
+
+ return nil
+}
+
+// IsRunning returns whether the service is running
+func (s *Service) IsRunning() bool {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return s.started
+}
+
+// ExecuteStream sends a prompt and streams the response
+func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callback StreamCallback) error {
+ s.mu.RLock()
+ if !s.started {
+ s.mu.RUnlock()
+ return fmt.Errorf("service not started")
+ }
+ sessions := s.sessions
+ agenticLoop := s.agenticLoop
+ s.mu.RUnlock()
+
+ // Ensure session exists
+ session, err := sessions.EnsureSession(req.SessionID)
+ if err != nil {
+ return fmt.Errorf("failed to ensure session: %w", err)
+ }
+
+ // Add user message
+ userMsg := Message{
+ ID: uuid.New().String(),
+ Role: "user",
+ Content: req.Prompt,
+ Timestamp: time.Now(),
+ }
+ if err := sessions.AddMessage(session.ID, userMsg); err != nil {
+ log.Warn().Err(err).Msg("Failed to save user message")
+ }
+
+ // Get existing messages for context
+ messages, err := sessions.GetMessages(session.ID)
+ if err != nil {
+ return fmt.Errorf("failed to get messages: %w", err)
+ }
+
+ // Run agentic loop
+ resultMessages, err := agenticLoop.Execute(ctx, session.ID, messages, callback)
+ if err != nil {
+ // Still save any messages we got
+ for _, msg := range resultMessages {
+ if saveErr := sessions.AddMessage(session.ID, msg); saveErr != nil {
+ log.Warn().Err(saveErr).Msg("Failed to save message after error")
+ }
+ }
+ return err
+ }
+
+ // Save result messages
+ for _, msg := range resultMessages {
+ // Skip user messages (already saved)
+ if msg.Role == "user" && msg.ToolResult == nil {
+ continue
+ }
+ if err := sessions.AddMessage(session.ID, msg); err != nil {
+ log.Warn().Err(err).Msg("Failed to save message")
+ }
+ }
+
+ // Send done event
+ doneData, _ := json.Marshal(DoneData{SessionID: session.ID})
+ callback(StreamEvent{Type: "done", Data: doneData})
+
+ return nil
+}
+
+// ListSessions returns all sessions
+func (s *Service) ListSessions(ctx context.Context) ([]Session, error) {
+ s.mu.RLock()
+ sessions := s.sessions
+ s.mu.RUnlock()
+
+ if sessions == nil {
+ return nil, fmt.Errorf("service not started")
+ }
+
+ return sessions.List()
+}
+
+// CreateSession creates a new session
+func (s *Service) CreateSession(ctx context.Context) (*Session, error) {
+ s.mu.RLock()
+ sessions := s.sessions
+ s.mu.RUnlock()
+
+ if sessions == nil {
+ return nil, fmt.Errorf("service not started")
+ }
+
+ return sessions.Create()
+}
+
+// DeleteSession deletes a session
+func (s *Service) DeleteSession(ctx context.Context, sessionID string) error {
+ s.mu.RLock()
+ sessions := s.sessions
+ s.mu.RUnlock()
+
+ if sessions == nil {
+ return fmt.Errorf("service not started")
+ }
+
+ return sessions.Delete(sessionID)
+}
+
+// GetMessages returns messages for a session
+func (s *Service) GetMessages(ctx context.Context, sessionID string) ([]Message, error) {
+ s.mu.RLock()
+ sessions := s.sessions
+ s.mu.RUnlock()
+
+ if sessions == nil {
+ return nil, fmt.Errorf("service not started")
+ }
+
+ return sessions.GetMessages(sessionID)
+}
+
+// AbortSession aborts an ongoing session
+func (s *Service) AbortSession(ctx context.Context, sessionID string) error {
+ s.mu.RLock()
+ agenticLoop := s.agenticLoop
+ s.mu.RUnlock()
+
+ if agenticLoop == nil {
+ return fmt.Errorf("service not started")
+ }
+
+ agenticLoop.Abort(sessionID)
+ return nil
+}
+
+// AnswerQuestion provides answers to a pending question
+func (s *Service) AnswerQuestion(ctx context.Context, questionID string, answers []QuestionAnswer) error {
+ s.mu.RLock()
+ agenticLoop := s.agenticLoop
+ s.mu.RUnlock()
+
+ if agenticLoop == nil {
+ return fmt.Errorf("service not started")
+ }
+
+ return agenticLoop.AnswerQuestion(questionID, answers)
+}
+
+// Stub methods for features not yet implemented
+
+// SummarizeSession compresses context
+func (s *Service) SummarizeSession(ctx context.Context, sessionID string) (map[string]interface{}, error) {
+ return map[string]interface{}{"status": "not_implemented"}, nil
+}
+
+// GetSessionDiff returns file changes
+func (s *Service) GetSessionDiff(ctx context.Context, sessionID string) (map[string]interface{}, error) {
+ return map[string]interface{}{"status": "not_implemented"}, nil
+}
+
+// ForkSession creates a branch
+func (s *Service) ForkSession(ctx context.Context, sessionID string) (*Session, error) {
+ return nil, fmt.Errorf("not implemented")
+}
+
+// RevertSession reverts changes
+func (s *Service) RevertSession(ctx context.Context, sessionID string) (map[string]interface{}, error) {
+ return map[string]interface{}{"status": "not_implemented"}, nil
+}
+
+// UnrevertSession restores reverted changes
+func (s *Service) UnrevertSession(ctx context.Context, sessionID string) (map[string]interface{}, error) {
+ return map[string]interface{}{"status": "not_implemented"}, nil
+}
+
+// GetBaseURL returns empty since there's no sidecar
+func (s *Service) GetBaseURL() string {
+ return ""
+}
+
+// Provider setter methods
+
+func (s *Service) SetAlertProvider(provider MCPAlertProvider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.executor != nil {
+ s.executor.SetAlertProvider(provider)
+ }
+}
+
+func (s *Service) SetFindingsProvider(provider MCPFindingsProvider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.executor != nil {
+ s.executor.SetFindingsProvider(provider)
+ }
+}
+
+func (s *Service) SetBaselineProvider(provider MCPBaselineProvider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.executor != nil {
+ s.executor.SetBaselineProvider(provider)
+ }
+}
+
+func (s *Service) SetPatternProvider(provider MCPPatternProvider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.executor != nil {
+ s.executor.SetPatternProvider(provider)
+ }
+}
+
+func (s *Service) SetMetricsHistory(provider MCPMetricsHistoryProvider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.executor != nil {
+ s.executor.SetMetricsHistory(provider)
+ }
+}
+
+func (s *Service) SetBackupProvider(provider MCPBackupProvider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.executor != nil {
+ s.executor.SetBackupProvider(provider)
+ }
+}
+
+func (s *Service) SetStorageProvider(provider MCPStorageProvider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.executor != nil {
+ s.executor.SetStorageProvider(provider)
+ }
+}
+
+func (s *Service) SetDiskHealthProvider(provider MCPDiskHealthProvider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.executor != nil {
+ s.executor.SetDiskHealthProvider(provider)
+ }
+}
+
+func (s *Service) SetUpdatesProvider(provider MCPUpdatesProvider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.executor != nil {
+ s.executor.SetUpdatesProvider(provider)
+ }
+}
+
+func (s *Service) SetAgentProfileManager(manager AgentProfileManager) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.executor != nil {
+ s.executor.SetAgentProfileManager(manager)
+ }
+}
+
+func (s *Service) SetFindingsManager(manager FindingsManager) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.executor != nil {
+ s.executor.SetFindingsManager(manager)
+ }
+}
+
+func (s *Service) SetMetadataUpdater(updater MetadataUpdater) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.executor != nil {
+ s.executor.SetMetadataUpdater(updater)
+ }
+}
+
+func (s *Service) UpdateControlSettings(cfg *config.AIConfig) {
+ if cfg == nil {
+ return
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.executor != nil {
+ s.executor.SetControlLevel(tools.ControlLevel(cfg.GetControlLevel()))
+ s.executor.SetProtectedGuests(cfg.GetProtectedGuests())
+ }
+}
+
+// createProvider creates an AI provider based on config
+func (s *Service) createProvider() (providers.StreamingProvider, error) {
+ if s.cfg == nil {
+ return nil, fmt.Errorf("no AI config")
+ }
+
+ chatModel := s.cfg.GetChatModel()
+ if chatModel == "" {
+ return nil, fmt.Errorf("no chat model configured")
+ }
+
+ // Parse provider:model format
+ parts := strings.SplitN(chatModel, ":", 2)
+ if len(parts) != 2 {
+ return nil, fmt.Errorf("invalid model format: %s (expected provider:model)", chatModel)
+ }
+ providerName := parts[0]
+ modelName := parts[1]
+
+ timeout := 5 * time.Minute
+
+ switch providerName {
+ case "anthropic":
+ if s.cfg.AnthropicAPIKey == "" {
+ return nil, fmt.Errorf("Anthropic API key not configured")
+ }
+ return providers.NewAnthropicClient(s.cfg.AnthropicAPIKey, modelName, timeout), nil
+
+ case "openai":
+ if s.cfg.OpenAIAPIKey == "" {
+ return nil, fmt.Errorf("OpenAI API key not configured")
+ }
+ return providers.NewOpenAIClient(s.cfg.OpenAIAPIKey, modelName, "", timeout), nil
+
+ case "deepseek":
+ if s.cfg.DeepSeekAPIKey == "" {
+ return nil, fmt.Errorf("DeepSeek API key not configured")
+ }
+ return providers.NewOpenAIClient(s.cfg.DeepSeekAPIKey, modelName, "https://api.deepseek.com", timeout), nil
+
+ case "gemini":
+ if s.cfg.GeminiAPIKey == "" {
+ return nil, fmt.Errorf("Gemini API key not configured")
+ }
+ return providers.NewGeminiClient(s.cfg.GeminiAPIKey, modelName, "", timeout), nil
+
+ case "ollama":
+ baseURL := s.cfg.OllamaBaseURL
+ if baseURL == "" {
+ baseURL = "http://localhost:11434"
+ }
+ return providers.NewOllamaClient(modelName, baseURL, timeout), nil
+
+ default:
+ return nil, fmt.Errorf("unsupported provider: %s", providerName)
+ }
+}
+
+// buildSystemPrompt builds the system prompt for the AI
+func (s *Service) buildSystemPrompt() string {
+ return `You are Pulse AI, an intelligent assistant for infrastructure monitoring and management.
+
+You have access to tools that let you:
+- Query infrastructure state (VMs, containers, nodes)
+- Get metrics and performance data
+- Check alerts and findings
+- Execute commands on hosts (with approval)
+- Manage Docker containers
+- Update resource metadata
+
+When users ask about their infrastructure:
+1. Use the appropriate query tools to get current state
+2. Provide clear, accurate answers based on the data
+3. Suggest actions when appropriate
+4. For control actions, explain what will happen before executing
+
+Be concise but thorough. Focus on actionable information.
+Trust the data from your tools - it's updated in real-time.`
+}
+
+// Execute provides non-streaming execution (for compatibility)
+func (s *Service) Execute(ctx context.Context, req ExecuteRequest) (map[string]interface{}, error) {
+ var lastContent string
+ err := s.ExecuteStream(ctx, req, func(event StreamEvent) {
+ if event.Type == "content" {
+ var data ContentData
+ if err := json.Unmarshal(event.Data, &data); err == nil {
+ lastContent += data.Text
+ }
+ }
+ })
+ if err != nil {
+ return nil, err
+ }
+ return map[string]interface{}{
+ "content": lastContent,
+ }, nil
+}
diff --git a/internal/ai/chat/session.go b/internal/ai/chat/session.go
new file mode 100644
index 0000000000..16b8635f64
--- /dev/null
+++ b/internal/ai/chat/session.go
@@ -0,0 +1,308 @@
+package chat
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/rs/zerolog/log"
+)
+
+// SessionStore manages chat sessions persisted as JSON files
+type SessionStore struct {
+ mu sync.RWMutex
+ dataDir string
+}
+
+// sessionData is the on-disk format for a session
+type sessionData struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ Messages []Message `json:"messages"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+}
+
+// NewSessionStore creates a new session store
+func NewSessionStore(dataDir string) (*SessionStore, error) {
+ sessionsDir := filepath.Join(dataDir, "ai_sessions")
+ if err := os.MkdirAll(sessionsDir, 0700); err != nil {
+ return nil, fmt.Errorf("failed to create sessions directory: %w", err)
+ }
+
+ return &SessionStore{
+ dataDir: sessionsDir,
+ }, nil
+}
+
+// sessionPath returns the file path for a session
+func (s *SessionStore) sessionPath(id string) string {
+ return filepath.Join(s.dataDir, id+".json")
+}
+
+// List returns all sessions, sorted by updated_at descending
+func (s *SessionStore) List() ([]Session, error) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ entries, err := os.ReadDir(s.dataDir)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read sessions directory: %w", err)
+ }
+
+ var sessions []Session
+ for _, entry := range entries {
+ if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {
+ continue
+ }
+
+ data, err := s.readSession(strings.TrimSuffix(entry.Name(), ".json"))
+ if err != nil {
+ log.Warn().Err(err).Str("file", entry.Name()).Msg("Failed to read session file")
+ continue
+ }
+
+ sessions = append(sessions, Session{
+ ID: data.ID,
+ Title: data.Title,
+ CreatedAt: data.CreatedAt,
+ UpdatedAt: data.UpdatedAt,
+ MessageCount: len(data.Messages),
+ })
+ }
+
+ // Sort by updated_at descending (newest first)
+ sort.Slice(sessions, func(i, j int) bool {
+ return sessions[i].UpdatedAt.After(sessions[j].UpdatedAt)
+ })
+
+ return sessions, nil
+}
+
+// Create creates a new session
+func (s *SessionStore) Create() (*Session, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ now := time.Now()
+ data := sessionData{
+ ID: uuid.New().String(),
+ Title: "",
+ Messages: []Message{},
+ CreatedAt: now,
+ UpdatedAt: now,
+ }
+
+ if err := s.writeSession(data); err != nil {
+ return nil, err
+ }
+
+ return &Session{
+ ID: data.ID,
+ Title: data.Title,
+ CreatedAt: data.CreatedAt,
+ UpdatedAt: data.UpdatedAt,
+ }, nil
+}
+
+// Get retrieves a session by ID
+func (s *SessionStore) Get(id string) (*Session, error) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ data, err := s.readSession(id)
+ if err != nil {
+ return nil, err
+ }
+
+ return &Session{
+ ID: data.ID,
+ Title: data.Title,
+ CreatedAt: data.CreatedAt,
+ UpdatedAt: data.UpdatedAt,
+ MessageCount: len(data.Messages),
+ }, nil
+}
+
+// Delete deletes a session
+func (s *SessionStore) Delete(id string) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ path := s.sessionPath(id)
+ if err := os.Remove(path); err != nil {
+ if os.IsNotExist(err) {
+ return fmt.Errorf("session not found: %s", id)
+ }
+ return fmt.Errorf("failed to delete session: %w", err)
+ }
+
+ return nil
+}
+
+// GetMessages retrieves all messages for a session
+func (s *SessionStore) GetMessages(id string) ([]Message, error) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ data, err := s.readSession(id)
+ if err != nil {
+ return nil, err
+ }
+
+ return data.Messages, nil
+}
+
+// AddMessage adds a message to a session
+func (s *SessionStore) AddMessage(id string, msg Message) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ data, err := s.readSession(id)
+ if err != nil {
+ return err
+ }
+
+ // Generate message ID if not set
+ if msg.ID == "" {
+ msg.ID = uuid.New().String()
+ }
+ if msg.Timestamp.IsZero() {
+ msg.Timestamp = time.Now()
+ }
+
+ data.Messages = append(data.Messages, msg)
+ data.UpdatedAt = time.Now()
+
+ // Auto-generate title from first user message if not set
+ if data.Title == "" && msg.Role == "user" && msg.Content != "" {
+ data.Title = generateTitle(msg.Content)
+ }
+
+ return s.writeSession(*data)
+}
+
+// UpdateLastMessage updates the last message in a session (for streaming updates)
+func (s *SessionStore) UpdateLastMessage(id string, msg Message) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ data, err := s.readSession(id)
+ if err != nil {
+ return err
+ }
+
+ if len(data.Messages) == 0 {
+ return fmt.Errorf("no messages to update")
+ }
+
+ data.Messages[len(data.Messages)-1] = msg
+ data.UpdatedAt = time.Now()
+
+ return s.writeSession(*data)
+}
+
+// readSession reads a session from disk (caller must hold lock)
+func (s *SessionStore) readSession(id string) (*sessionData, error) {
+ path := s.sessionPath(id)
+ file, err := os.ReadFile(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, fmt.Errorf("session not found: %s", id)
+ }
+ return nil, fmt.Errorf("failed to read session: %w", err)
+ }
+
+ var data sessionData
+ if err := json.Unmarshal(file, &data); err != nil {
+ return nil, fmt.Errorf("failed to parse session: %w", err)
+ }
+
+ return &data, nil
+}
+
+// writeSession writes a session to disk (caller must hold lock)
+func (s *SessionStore) writeSession(data sessionData) error {
+ file, err := json.MarshalIndent(data, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal session: %w", err)
+ }
+
+ path := s.sessionPath(data.ID)
+ if err := os.WriteFile(path, file, 0600); err != nil {
+ return fmt.Errorf("failed to write session: %w", err)
+ }
+
+ return nil
+}
+
+// generateTitle creates a session title from the first user message
+func generateTitle(content string) string {
+ // Clean up the content
+ 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
+
+ runes := []rune(content)
+ if len(runes) <= maxLen {
+ return content
+ }
+
+ // Find a good break point
+ truncated := string(runes[:maxLen])
+ lastSpace := strings.LastIndex(truncated, " ")
+
+ if lastSpace > 20 {
+ return truncated[:lastSpace] + "..."
+ }
+
+ return truncated + "..."
+}
+
+// EnsureSession ensures a session exists, creating one if needed
+func (s *SessionStore) EnsureSession(id string) (*Session, error) {
+ if id == "" {
+ return s.Create()
+ }
+
+ session, err := s.Get(id)
+ if err != nil {
+ // Session doesn't exist, create it with the specified ID
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ now := time.Now()
+ data := sessionData{
+ ID: id,
+ Title: "",
+ Messages: []Message{},
+ CreatedAt: now,
+ UpdatedAt: now,
+ }
+
+ if err := s.writeSession(data); err != nil {
+ return nil, err
+ }
+
+ return &Session{
+ ID: data.ID,
+ CreatedAt: data.CreatedAt,
+ UpdatedAt: data.UpdatedAt,
+ }, nil
+ }
+
+ return session, nil
+}
diff --git a/internal/ai/chat/tools.go b/internal/ai/chat/tools.go
new file mode 100644
index 0000000000..ae553cad72
--- /dev/null
+++ b/internal/ai/chat/tools.go
@@ -0,0 +1,79 @@
+package chat
+
+import (
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
+)
+
+// ConvertMCPToolsToProvider converts MCP tool definitions to provider tool format
+func ConvertMCPToolsToProvider(mcpTools []tools.Tool) []providers.Tool {
+ result := make([]providers.Tool, 0, len(mcpTools))
+
+ for _, t := range mcpTools {
+ // Build the input schema in the format expected by providers
+ inputSchema := make(map[string]interface{})
+ inputSchema["type"] = "object"
+
+ // Convert properties
+ if len(t.InputSchema.Properties) > 0 {
+ props := make(map[string]interface{})
+ for name, prop := range t.InputSchema.Properties {
+ propDef := map[string]interface{}{
+ "type": prop.Type,
+ }
+ if prop.Description != "" {
+ propDef["description"] = prop.Description
+ }
+ if len(prop.Enum) > 0 {
+ propDef["enum"] = prop.Enum
+ }
+ if prop.Default != nil {
+ propDef["default"] = prop.Default
+ }
+ props[name] = propDef
+ }
+ inputSchema["properties"] = props
+ }
+
+ // Add required fields
+ if len(t.InputSchema.Required) > 0 {
+ inputSchema["required"] = t.InputSchema.Required
+ }
+
+ result = append(result, providers.Tool{
+ Name: t.Name,
+ Description: t.Description,
+ InputSchema: inputSchema,
+ })
+ }
+
+ return result
+}
+
+// ConvertProviderToolCallToMCP converts a provider tool call to MCP format
+func ConvertProviderToolCallToMCP(tc providers.ToolCall) tools.CallToolParams {
+ return tools.CallToolParams{
+ Name: tc.Name,
+ Arguments: tc.Input,
+ }
+}
+
+// FormatToolResult formats a tool result for display
+func FormatToolResult(result tools.CallToolResult) string {
+ if len(result.Content) == 0 {
+ return ""
+ }
+
+ // Combine all text content
+ var text string
+ for _, c := range result.Content {
+ if c.Type == "text" && c.Text != "" {
+ if text != "" {
+ text += "\n"
+ }
+ text += c.Text
+ }
+ }
+
+ return text
+}
diff --git a/internal/ai/chat/types.go b/internal/ai/chat/types.go
new file mode 100644
index 0000000000..b86e65b49b
--- /dev/null
+++ b/internal/ai/chat/types.go
@@ -0,0 +1,144 @@
+// Package chat provides direct AI chat integration without external sidecar processes
+package chat
+
+import (
+ "encoding/json"
+ "time"
+)
+
+// Session represents a chat session
+type Session struct {
+ ID string `json:"id"`
+ Title string `json:"title,omitempty"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+ MessageCount int `json:"message_count,omitempty"`
+}
+
+// Message represents a chat message
+type Message struct {
+ ID string `json:"id"`
+ Role string `json:"role"` // "user", "assistant", "system"
+ Content string `json:"content"`
+ ReasoningContent string `json:"reasoning_content,omitempty"` // For extended thinking
+ ToolCalls []ToolCall `json:"tool_calls,omitempty"`
+ ToolResult *ToolResult `json:"tool_result,omitempty"`
+ Timestamp time.Time `json:"timestamp"`
+}
+
+// ToolCall represents a tool invocation
+type ToolCall struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Input map[string]interface{} `json:"input"`
+}
+
+// ToolResult represents the result of a tool execution
+type ToolResult struct {
+ ToolUseID string `json:"tool_use_id"`
+ Content string `json:"content"`
+ IsError bool `json:"is_error,omitempty"`
+}
+
+// StreamEvent represents a streaming event sent to the frontend
+type StreamEvent struct {
+ Type string `json:"type"`
+ Data json.RawMessage `json:"data,omitempty"`
+}
+
+// StreamCallback is called for each streaming event
+type StreamCallback func(event StreamEvent)
+
+// ExecuteRequest represents a chat execution request
+type ExecuteRequest struct {
+ Prompt string `json:"prompt"`
+ SessionID string `json:"session_id,omitempty"`
+ Model string `json:"model,omitempty"`
+}
+
+// QuestionAnswer represents a user's answer to a question
+type QuestionAnswer struct {
+ ID string `json:"id"`
+ Value string `json:"value"`
+}
+
+// ContentData is the data for "content" events
+type ContentData struct {
+ Text string `json:"text"`
+}
+
+// ThinkingData is the data for "thinking" events (extended thinking/reasoning)
+type ThinkingData struct {
+ Text string `json:"text"`
+}
+
+// ToolStartData is the data for "tool_start" events
+type ToolStartData struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Input string `json:"input"` // JSON string of input parameters
+}
+
+// ToolEndData is the data for "tool_end" events
+type ToolEndData struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Input string `json:"input,omitempty"`
+ Output string `json:"output,omitempty"`
+ Success bool `json:"success"`
+}
+
+// ApprovalNeededData is the data for "approval_needed" events
+type ApprovalNeededData struct {
+ ApprovalID string `json:"approval_id"`
+ ToolID string `json:"tool_id"`
+ ToolName string `json:"tool_name"`
+ Command string `json:"command"`
+ RunOnHost bool `json:"run_on_host"`
+ TargetHost string `json:"target_host,omitempty"`
+ Risk string `json:"risk,omitempty"`
+ Description string `json:"description,omitempty"`
+}
+
+// QuestionData is the data for "question" events
+type QuestionData struct {
+ QuestionID string `json:"question_id"`
+ Questions []Question `json:"questions"`
+}
+
+// Question represents a question from the AI to the user
+type Question struct {
+ ID string `json:"id"`
+ Question string `json:"question"`
+ Header string `json:"header,omitempty"`
+ Options []QuestionOption `json:"options,omitempty"`
+}
+
+// QuestionOption represents an option for a question
+type QuestionOption struct {
+ Label string `json:"label"`
+ Description string `json:"description,omitempty"`
+}
+
+// ErrorData is the data for "error" events
+type ErrorData struct {
+ Message string `json:"message"`
+}
+
+// DoneData is the data for "done" events
+type DoneData struct {
+ SessionID string `json:"session_id,omitempty"`
+ InputTokens int `json:"input_tokens,omitempty"`
+ OutputTokens int `json:"output_tokens,omitempty"`
+}
+
+// Control level constants
+const (
+ ControlLevelReadOnly = "read_only"
+ ControlLevelSuggest = "suggest"
+ ControlLevelControlled = "controlled"
+ ControlLevelAutonomous = "autonomous"
+)
+
+// Max turns for the agentic loop to prevent infinite loops
+const MaxAgenticTurns = 20