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
// Package chat provides direct AI chat integration without external sidecar processes
package chat
import (
"encoding/json"
"sort"
"strings"
"sync"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
)
// 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"`
System bool `json:"system,omitempty"`
HandoffSummary *SessionHandoffSummary `json:"handoff_summary,omitempty"`
}
// IsSystemSessionID reports whether a session ID belongs to a Pulse-owned
// background run (Patrol detection, Patrol eval, or a Patrol investigation)
// rather than a user conversation. These sessions are forensic logs: they
// stay listable and inspectable, but clients should not offer them as
// resumable chats.
func IsSystemSessionID(id string) bool {
id = strings.TrimSpace(id)
return id == "patrol-main" || id == "patrol-eval" || strings.HasPrefix(id, "investigation-")
}
// SessionHandoffSummary is the browser-safe public summary of private
// session-scoped model handoff metadata. It intentionally omits model-only
// context text and raw remediation details.
type SessionHandoffSummary struct {
Kind string `json:"kind,omitempty"`
FindingID string `json:"finding_id,omitempty"`
RunID string `json:"run_id,omitempty"`
RunType string `json:"run_type,omitempty"`
RunStatus string `json:"run_status,omitempty"`
RuntimeFailure bool `json:"runtime_failure,omitempty"`
HasModelContext bool `json:"has_model_context"`
ResourceCount int `json:"resource_count,omitempty"`
PrimaryResource *HandoffResource `json:"primary_resource,omitempty"`
ActionCount int `json:"action_count,omitempty"`
RequiresApproval bool `json:"requires_approval,omitempty"`
LastKnownApprovalStatus string `json:"last_known_approval_status,omitempty"`
LastKnownActionState string `json:"last_known_action_state,omitempty"`
LastKnownActionRisk string `json:"last_known_action_risk,omitempty"`
UpdatedAt *time.Time `json:"updated_at,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"`
ToolResult *ToolResult `json:"tool_result,omitempty"`
Model string `json:"model,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
func EmptyMessage() Message {
return Message{}.NormalizeCollections()
}
func (m Message) NormalizeCollections() Message {
if m.ToolCalls == nil {
m.ToolCalls = []ToolCall{}
} else {
toolCalls := make([]ToolCall, len(m.ToolCalls))
for i := range m.ToolCalls {
toolCalls[i] = m.ToolCalls[i].NormalizeCollections()
}
m.ToolCalls = toolCalls
}
if m.ToolResult != nil {
toolResult := *m.ToolResult
m.ToolResult = &toolResult
}
return m
}
// ClientSafe returns the browser/API-facing view of a stored chat message.
// Runtime history may retain provider reasoning for model continuity, but
// user-facing history must not serialize hidden reasoning or raw tool-call text.
func (m Message) ClientSafe() Message {
m = m.NormalizeCollections()
if strings.EqualFold(m.Role, "assistant") {
m.Content = cleanToolCallArtifacts(m.Content)
}
m.ReasoningContent = ""
return m
}
// ToolCall is the canonical result-bearing product transcript call.
type ToolCall = agentcapabilities.TranscriptToolCall
func EmptyToolCall() ToolCall {
return ToolCall{}.NormalizeCollections()
}
// ToolCallFromProvider stores a provider-facing tool call in the richer
// Assistant transcript shape used for in-app history.
func ToolCallFromProvider(tc agentcapabilities.ProviderToolCall) ToolCall {
tc = tc.NormalizeCollections()
return ToolCall{
ID: tc.ID,
Name: tc.Name,
// The durable transcript routes through the canonical exposure
// projector: proposal params live only transiently for provider
// continuation and validation; the action audit is their
// canonical durable home.
Input: agentcapabilities.RedactToolCallArgumentsForExposure(tc.Name, tc.Input),
ThoughtSignature: tc.ThoughtSignature,
}.NormalizeCollections()
}
// ToolResult represents the result of a tool execution. It aliases the shared
// Pulse Intelligence provider-result shape so stored Assistant transcripts and
// provider turns do not drift on tool result JSON.
type ToolResult = agentcapabilities.ProviderToolResult
// StreamEvent represents a streaming event sent to the frontend
type StreamEvent struct {
Type string `json:"type"`
Data json.RawMessage `json:"data,omitempty"`
}
// ClientSafe returns the browser/API-facing view of a stream event. Provider
// reasoning may be retained inside the runtime, but raw thinking deltas must
// not cross the client boundary.
func (e StreamEvent) ClientSafe() (StreamEvent, bool) {
switch strings.ToLower(strings.TrimSpace(e.Type)) {
case "thinking":
return StreamEvent{}, false
case "content":
if len(e.Data) == 0 {
return e, true
}
var data ContentData
if err := json.Unmarshal(e.Data, &data); err != nil {
return e, true
}
data.Text = cleanToolCallArtifacts(data.Text)
if data.Text == "" {
return StreamEvent{}, false
}
jsonData, err := json.Marshal(data)
if err != nil {
return StreamEvent{}, false
}
e.Data = jsonData
return e, true
default:
return e, true
}
}
// StreamCallback is called for each streaming event
type StreamCallback func(event StreamEvent)
// StructuredMention represents a resource explicitly tagged by the user via @ mention.
// The frontend resolves these from the autocomplete and sends them alongside the prompt,
// so the backend doesn't need to re-derive resource identity from text.
type StructuredMention struct {
ID string `json:"id"` // e.g. "system-container:pve-node:123", "app-container:truenas-main:nextcloud", legacy "docker:docker-host-1:container", "agent:host-1"
Name string `json:"name"` // Display name, e.g. "ntfy"
Type string `json:"type"` // "vm", "system-container", "app-container", "node", "agent"
Node string `json:"node,omitempty"` // Proxmox node or parent host
}
// HandoffResource represents an explicit product-originated resource handoff.
// Unlike model-only handoff text, this is used only to seed session-scoped
// resource validation from canonical unified-resource registrations.
type HandoffResource struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Type string `json:"type,omitempty"`
Node string `json:"node,omitempty"`
}
// HandoffAction represents a product-originated action reference.
// It is context for review only: it carries no command text and grants no
// authority to approve, execute, or replay a remediation.
type HandoffAction struct {
FindingID string `json:"finding_id,omitempty"`
RecordID string `json:"record_id,omitempty"`
ApprovalID string `json:"approval_id,omitempty"`
ApprovalStatus string `json:"approval_status,omitempty"`
ApprovalRequestedAt string `json:"approval_requested_at,omitempty"`
ApprovalExpiresAt string `json:"approval_expires_at,omitempty"`
ApprovalDecidedAt string `json:"approval_decided_at,omitempty"`
ApprovalConsumed bool `json:"approval_consumed,omitempty"`
ActionID string `json:"action_id,omitempty"`
ActionState string `json:"action_state,omitempty"`
ActionUpdatedAt string `json:"action_updated_at,omitempty"`
ActionRequestedBy string `json:"action_requested_by,omitempty"`
ActionCapability string `json:"action_capability,omitempty"`
ActionApprovalPolicy string `json:"action_approval_policy,omitempty"`
ActionRequiresApproval bool `json:"action_requires_approval,omitempty"`
ActionPlanExpiresAt string `json:"action_plan_expires_at,omitempty"`
ActionPlanMessage string `json:"action_plan_message,omitempty"`
ActionPreflight string `json:"action_preflight,omitempty"`
ActionDryRunSummary string `json:"action_dry_run_summary,omitempty"`
ActionResult string `json:"action_result,omitempty"`
FixID string `json:"fix_id,omitempty"`
Description string `json:"description,omitempty"`
RiskLevel string `json:"risk_level,omitempty"`
Destructive bool `json:"destructive,omitempty"`
TargetHost string `json:"target_host,omitempty"`
TargetResourceID string `json:"target_resource_id,omitempty"`
TargetResourceName string `json:"target_resource_name,omitempty"`
TargetResourceType string `json:"target_resource_type,omitempty"`
TargetNode string `json:"target_node,omitempty"`
}
// HandoffMetadata carries browser-safe identity for a product-originated
// model-only handoff. It must not include model context text, command payloads,
// remediation details, or provider/runtime error detail.
type HandoffMetadata struct {
Kind string `json:"kind,omitempty"`
RunID string `json:"run_id,omitempty"`
RunType string `json:"run_type,omitempty"`
RunStatus string `json:"run_status,omitempty"`
RuntimeFailure bool `json:"runtime_failure,omitempty"`
}
// ExecuteRequest represents a chat execution request
type ExecuteRequest struct {
Prompt string `json:"prompt"`
SessionID string `json:"session_id,omitempty"`
Model string `json:"model,omitempty"`
Mentions []StructuredMention `json:"mentions,omitempty"`
FindingID string `json:"finding_id,omitempty"` // Pre-populate finding context for "Discuss" flow
HandoffContext string `json:"handoff_context,omitempty"` // Model-only context for scoped handoffs; not persisted as user-authored text.
HandoffResources []HandoffResource `json:"handoff_resources,omitempty"` // Product-originated resources to seed governed session validation.
HandoffActions []HandoffAction `json:"handoff_actions,omitempty"` // Product-originated approval/action references for model-only review context.
HandoffMetadata HandoffMetadata `json:"handoff_metadata,omitempty"` // Browser-safe identity for restoring saved product handoffs.
MaxTurns int `json:"max_turns,omitempty"` // Override max agentic turns (0 = use default)
AutonomousMode *bool `json:"autonomous_mode,omitempty"` // Per-request autonomous override (nil = use service default)
// HasExecuteAuthority is injected by the authenticated server boundary.
// It is never accepted from provider/model JSON.
HasExecuteAuthority bool `json:"-"`
// SuppressSessionEvent is set by HTTP streaming callers that have already
// emitted the browser-visible session event before expensive handoff or
// provider setup work.
SuppressSessionEvent bool `json:"-"`
}
// 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"`
}
// WorkflowStateData is the data for "workflow_state" events.
type WorkflowStateData struct {
Phase string `json:"phase"` // investigate | clarify | plan | approve | execute | verify | complete
Message string `json:"message"` // Human-readable status text for the UI
State string `json:"state,omitempty"` // Backend workflow state, when available
Tool string `json:"tool,omitempty"` // Tool associated with this transition
Provider string `json:"provider,omitempty"` // Provider selected for this workflow step
Model string `json:"model,omitempty"` // Model route selected for this workflow step
Attempt int `json:"attempt,omitempty"` // One-based attempt number for transient provider retries
MaxAttempts int `json:"max_attempts,omitempty"` // Maximum attempts available for the current provider request
RetryAfterMS int64 `json:"retry_after_ms,omitempty"` // Milliseconds until the next provider attempt starts
}
// SessionData is the data for "session" events emitted once the backend has
// created or resolved the durable chat session for a stream.
type SessionData struct {
ID string `json:"id"`
}
// 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
RawInput string `json:"raw_input,omitempty"` // Unmodified JSON input
Phase string `json:"phase,omitempty"` // pending | running | waiting
Message string `json:"message,omitempty"` // Compact user-facing status text
}
// ToolProgressData is the data for "tool_progress" events.
// It mutates an existing pending tool row as execution starts or advances.
type ToolProgressData struct {
ID string `json:"id"`
Name string `json:"name"`
Input string `json:"input,omitempty"`
RawInput string `json:"raw_input,omitempty"`
Phase string `json:"phase,omitempty"` // pending | running | waiting
Message string `json:"message,omitempty"` // Compact user-facing status text
}
// ToolCancelData is the data for "tool_cancel" events.
// It marks a pending tool row as skipped when a model-selected call is consumed
// by an internal policy boundary instead of becoming user-visible execution.
type ToolCancelData struct {
ID string `json:"id"`
Name string `json:"name"`
Reason string `json:"reason,omitempty"`
}
// ToolEndData is the data for "tool_end" events
type ToolEndData struct {
ID string `json:"id"`
Name string `json:"name"`
Input string `json:"input,omitempty"`
RawInput string `json:"raw_input,omitempty"`
Output string `json:"output,omitempty"`
Success bool `json:"success"`
}
// ApprovalPlanData aliases the shared approval-marker plan subset. The
// browser event shape stays in chat, but the marker payload contract lives in
// agentcapabilities so tool producers and chat consumers cannot drift.
type ApprovalPlanData = agentcapabilities.ApprovalPlanData
// ApprovalContextConfidenceData aliases the shared approval-marker confidence
// payload.
type ApprovalContextConfidenceData = agentcapabilities.ApprovalContextConfidenceData
// ApprovalPreflightData aliases the shared approval-marker preflight payload.
type ApprovalPreflightData = agentcapabilities.ApprovalPreflightData
// 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"`
TargetType string `json:"target_type,omitempty"`
TargetID string `json:"target_id,omitempty"`
Risk string `json:"risk,omitempty"`
Description string `json:"description,omitempty"`
AuditID string `json:"audit_id,omitempty"`
Plan *ApprovalPlanData `json:"plan,omitempty"`
ContextConfidence *ApprovalContextConfidenceData `json:"context_confidence,omitempty"`
Preflight *ApprovalPreflightData `json:"preflight,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"`
Model string `json:"model,omitempty"`
InputTokens int `json:"input_tokens,omitempty"`
OutputTokens int `json:"output_tokens,omitempty"`
// ContextLimitTokens is the active model's context window, so the client
// can show how full the turn's context was without a model table of its own.
ContextLimitTokens int `json:"context_limit_tokens,omitempty"`
// SessionCostUSD is the estimated cumulative spend for this session
// (turns, compaction, title calls) summed from the cost ledger. Omitted
// when any of the session's models has no known pricing (e.g. local
// Ollama), so the client never shows a partial figure.
SessionCostUSD float64 `json:"session_cost_usd,omitempty"`
}
// Control level constants
const (
ControlLevelReadOnly = string(tools.ControlLevelReadOnly)
ControlLevelControlled = string(tools.ControlLevelControlled)
ControlLevelAutonomous = string(tools.ControlLevelAutonomous)
)
// ResolvedResource represents a resource that has been authoritatively resolved
// through pulse_query. This is the source of truth that
// the model cannot override - action tools must reference these IDs.
//
// This type implements tools.ResolvedResourceInfo interface.
type ResolvedResource struct {
// === Structured Identity (primary) ===
// Kind is the resource type: "node", "vm", "system-container", "app-container", "docker-host", "k8s-pod", etc.
Kind string `json:"kind"`
// ProviderUID is the stable identifier from the provider (container ID, VMID, pod UID).
// This is the primary identifier - names are aliases.
ProviderUID string `json:"provider_uid"`
// Scope defines the context/location of this resource
Scope ResourceScope `json:"scope"`
// Aliases are user-friendly names that resolve to this resource.
// e.g., ["jellyfin", "@jellyfin", "media-server/jellyfin"]
Aliases []string `json:"aliases"`
// === Derived/Display Fields ===
// ResourceID is the canonical string identifier, derived from Kind:ProviderUID
// Format: "{kind}:{provider_uid}" e.g., "app-container:abc123def456"
// For backwards compatibility, falls back to "{kind}:{name}" if no ProviderUID
ResourceID string `json:"resource_id"`
// Name is the primary display name (first alias, typically)
Name string `json:"name"`
// ResourceType is kept for backwards compatibility (same as Kind)
ResourceType string `json:"resource_type"`
// DisplayPath is the human-readable location string
// e.g., "docker:jellyfin @ lxc:media-server @ node:pve-node"
DisplayPath string `json:"display_path,omitempty"`
// LocationChain is the hierarchical path (for backwards compatibility)
// Example: ["node:pve-node", "lxc:media-server", "docker:jellyfin"]
LocationChain []string `json:"location_chain"`
// === Executor Paths ===
// ReachableVia lists executors that can reach this resource and what actions each supports.
// This replaces the single TargetHost/AgentID/Adapter fields for multi-path routing.
ReachableVia []ExecutorPath `json:"reachable_via,omitempty"`
// Legacy routing fields (for backwards compatibility, derived from first ReachableVia)
TargetHost string `json:"target_host"` // Where commands should be sent
AgentID string `json:"agent_id"` // Agent that handles this resource
Adapter string `json:"adapter"` // "direct", "pct", "qm", "docker"
// === Resource-specific fields ===
// Proxmox-specific
VMID int `json:"vmid,omitempty"`
Node string `json:"node,omitempty"`
// AllowedActions is the union of all actions from ReachableVia (for quick checks)
AllowedActions []string `json:"allowed_actions"`
// Timestamps
ResolvedAt time.Time `json:"resolved_at"`
}
// ResourceScope defines where a resource exists in the infrastructure hierarchy.
type ResourceScope struct {
// HostUID is the stable ID of the host/node this resource runs on
HostUID string `json:"host_uid,omitempty"`
// HostName is the display name of the host
HostName string `json:"host_name,omitempty"`
// ParentUID is the stable ID of the parent resource (e.g., LXC container for nested Docker)
ParentUID string `json:"parent_uid,omitempty"`
// ParentKind is the type of parent resource
ParentKind string `json:"parent_kind,omitempty"`
// ClusterUID for Kubernetes resources
ClusterUID string `json:"cluster_uid,omitempty"`
// Namespace for Kubernetes resources
Namespace string `json:"namespace,omitempty"`
}
// ExecutorPath describes how to reach a resource through a specific executor.
type ExecutorPath struct {
// ExecutorID identifies the agent/executor that can reach this resource
ExecutorID string `json:"executor_id"`
// Adapter is the execution method: "direct", "pct", "qm", "docker", "kubectl"
Adapter string `json:"adapter"`
// Actions this executor can perform on the resource
Actions []string `json:"actions"`
// Priority for executor selection (higher = preferred)
Priority int `json:"priority"`
}
// Implement tools.ResolvedResourceInfo interface
func (r *ResolvedResource) GetResourceID() string { return r.ResourceID }
func (r *ResolvedResource) GetResourceType() string { return r.ResourceType }
func (r *ResolvedResource) GetTargetHost() string { return r.TargetHost }
func (r *ResolvedResource) GetAgentID() string { return r.AgentID }
func (r *ResolvedResource) GetAdapter() string { return r.Adapter }
func (r *ResolvedResource) GetVMID() int { return r.VMID }
func (r *ResolvedResource) GetNode() string { return r.Node }
func (r *ResolvedResource) GetAllowedActions() []string { return r.AllowedActions }
func (r *ResolvedResource) GetProviderUID() string { return r.ProviderUID }
func (r *ResolvedResource) GetKind() string { return r.Kind }
func (r *ResolvedResource) GetAliases() []string { return r.Aliases }
// HasAlias checks if the resource has a specific alias (case-insensitive)
func (r *ResolvedResource) HasAlias(name string) bool {
nameLower := strings.ToLower(name)
for _, alias := range r.Aliases {
if strings.ToLower(alias) == nameLower {
return true
}
}
return strings.ToLower(r.Name) == nameLower
}
// GetBestExecutor returns the highest-priority executor path that supports the given action
func (r *ResolvedResource) GetBestExecutor(action string) *ExecutorPath {
var best *ExecutorPath
for i := range r.ReachableVia {
path := &r.ReachableVia[i]
for _, a := range path.Actions {
if a == action || a == "*" {
if best == nil || path.Priority > best.Priority {
best = path
}
break
}
}
}
return best
}
// Default values for TTL and size caps
const (
DefaultResolvedContextTTL = 45 * time.Minute // Sliding window TTL
DefaultResolvedContextMaxEntries = 500 // Max resources per session
)
// ResolvedContext holds all resolved resources for a session.
// This is the authoritative context that action tools validate against.
// The model cannot fabricate or mutate these - they only come from
// successful query/discovery tool executions.
//
// Features:
// - TTL: Resources expire after DefaultResolvedContextTTL of inactivity (sliding window)
// - LRU eviction: When MaxEntries is reached, least recently used resources are evicted
// - Pinning: Resources can be pinned to prevent eviction (e.g., primary targets)
//
// This type implements tools.ResolvedContextProvider interface.
type ResolvedContext struct {
// mu protects all map fields from concurrent access during parallel tool execution.
mu sync.RWMutex `json:"-"`
SessionID string `json:"session_id"`
// Resources stores each resolved resource once, keyed by registry identity.
// Legacy name-keyed JSON is normalized when the derived indexes are rebuilt.
Resources map[string]*ResolvedResource `json:"resources"`
// ResourcesByID provides lookup by canonical ResourceID
ResourcesByID map[string]*ResolvedResource `json:"-"` // Not persisted, rebuilt on load
// ResourcesByAlias provides lookup by any alias (case-insensitive)
ResourcesByAlias map[string]*ResolvedResource `json:"-"` // Not persisted, rebuilt on load
// LRU tracking: maps ResourceID to last access time (used for TTL and LRU eviction)
lastAccessed map[string]time.Time `json:"-"`
// Explicit access tracking: maps ResourceID to time of explicit user access
// This is SEPARATE from lastAccessed and is ONLY set via MarkExplicitAccess.
// Used for routing validation to detect "user referenced this resource this turn".
// Key distinction: lastAccessed tracks all access (add, get, lookup);
// explicitlyAccessed tracks only explicit user intent (get, @mention).
explicitlyAccessed map[string]time.Time `json:"-"`
// Pinned resources that won't be evicted (by ResourceID)
pinned map[string]bool `json:"-"`
// Configuration
ttl time.Duration `json:"-"`
maxEntries int `json:"-"`
CreatedAt time.Time `json:"created_at"`
LastUpdated time.Time `json:"last_updated"`
}
// NewResolvedContext creates a new empty resolved context for a session
func NewResolvedContext(sessionID string) *ResolvedContext {
return &ResolvedContext{
SessionID: sessionID,
Resources: make(map[string]*ResolvedResource),
ResourcesByID: make(map[string]*ResolvedResource),
ResourcesByAlias: make(map[string]*ResolvedResource),
lastAccessed: make(map[string]time.Time),
explicitlyAccessed: make(map[string]time.Time),
pinned: make(map[string]bool),
ttl: DefaultResolvedContextTTL,
maxEntries: DefaultResolvedContextMaxEntries,
CreatedAt: time.Now(),
LastUpdated: time.Now(),
}
}
// NewResolvedContextWithConfig creates a new resolved context with custom TTL and size limits
func NewResolvedContextWithConfig(sessionID string, ttl time.Duration, maxEntries int) *ResolvedContext {
ctx := NewResolvedContext(sessionID)
if ttl > 0 {
ctx.ttl = ttl
}
if maxEntries > 0 {
ctx.maxEntries = maxEntries
}
return ctx
}
// touch updates the last access time for a resource (LRU tracking)
func (rc *ResolvedContext) touch(resourceID string) {
if rc.lastAccessed == nil {
rc.lastAccessed = make(map[string]time.Time)
}
rc.lastAccessed[resourceID] = time.Now()
}
// evictExpired removes resources that haven't been accessed within the TTL
func (rc *ResolvedContext) evictExpired() {
rc.ensureResourceIndexes()
if rc.ttl == 0 {
return
}
cutoff := time.Now().Add(-rc.ttl)
var toEvict []string
for resourceID, lastAccess := range rc.lastAccessed {
if lastAccess.Before(cutoff) && !rc.pinned[resourceID] {
toEvict = append(toEvict, resourceID)
}
}
for _, resourceID := range toEvict {
rc.removeByID(resourceID)
}
// Also prune expired explicit access entries to prevent memory creep
rc.pruneExpiredExplicitAccess()
}
// pruneExpiredExplicitAccess removes explicit access entries older than RecentAccessWindow.
// This prevents the explicitlyAccessed map from growing indefinitely in long sessions.
// Note: Uses tools.RecentAccessWindow (30s) as the cutoff, not the general TTL.
func (rc *ResolvedContext) pruneExpiredExplicitAccess() {
if rc.explicitlyAccessed == nil {
return
}
cutoff := time.Now().Add(-tools.RecentAccessWindow)
for resourceID, accessTime := range rc.explicitlyAccessed {
if accessTime.Before(cutoff) {
delete(rc.explicitlyAccessed, resourceID)
}
}
}
// evictOverflow removes least recently used resources when over capacity
func (rc *ResolvedContext) evictOverflow() {
if rc.maxEntries == 0 {
return
}
// Count unique resources (by ID)
uniqueCount := len(rc.ResourcesByID)
if uniqueCount <= rc.maxEntries {
return
}
// Find LRU candidates (not pinned)
type lruEntry struct {
resourceID string
lastAccess time.Time
}
var candidates []lruEntry
for resourceID, lastAccess := range rc.lastAccessed {
if !rc.pinned[resourceID] {
candidates = append(candidates, lruEntry{resourceID, lastAccess})
}
}
// Sort by last access time (oldest first)
for i := 0; i < len(candidates)-1; i++ {
for j := i + 1; j < len(candidates); j++ {
if candidates[j].lastAccess.Before(candidates[i].lastAccess) {
candidates[i], candidates[j] = candidates[j], candidates[i]
}
}
}
// Evict oldest until under capacity
toEvict := uniqueCount - rc.maxEntries
for i := 0; i < toEvict && i < len(candidates); i++ {
rc.removeByID(candidates[i].resourceID)
}
}
// removeByID removes a resource and all its aliases from the context
func (rc *ResolvedContext) removeByID(resourceID string) {
delete(rc.ResourcesByID, resourceID)
delete(rc.Resources, resourceID)
delete(rc.lastAccessed, resourceID)
delete(rc.explicitlyAccessed, resourceID)
delete(rc.pinned, resourceID)
rc.rebuildAliasIndex()
}
// rebuildAliasIndex keeps only unambiguous aliases. A nil entry reserves a
// duplicated label until one of its distinct owners leaves the context.
func (rc *ResolvedContext) rebuildAliasIndex() {
rc.ResourcesByAlias = make(map[string]*ResolvedResource)
for _, res := range rc.ResourcesByID {
if res == nil {
continue
}
for _, alias := range append(append([]string(nil), res.Aliases...), res.Name) {
key := strings.ToLower(strings.TrimSpace(alias))
if key == "" {
continue
}
previous, exists := rc.ResourcesByAlias[key]
if exists && (previous == nil || previous.ResourceID != res.ResourceID) {
rc.ResourcesByAlias[key] = nil
} else {
rc.ResourcesByAlias[key] = res
}
}
}
}
// ensureResourceIndexes restores derived indexes from old and current JSON.
func (rc *ResolvedContext) ensureResourceIndexes() {
if rc.ResourcesByID != nil {
return
}
old := rc.Resources
rc.Resources = make(map[string]*ResolvedResource)
rc.ResourcesByID = make(map[string]*ResolvedResource)
for key, res := range old {
if res == nil {
continue
}
if res.ResourceID == "" {
res.ResourceID = key
}
if res.Name == "" {
res.Name = key
}
rc.Resources[res.ResourceID] = res
rc.ResourcesByID[res.ResourceID] = res
rc.touch(res.ResourceID)
}
rc.rebuildAliasIndex()
}
// PinResource marks a resource as pinned (won't be evicted)
func (rc *ResolvedContext) PinResource(resourceID string) {
rc.mu.Lock()
defer rc.mu.Unlock()
if rc.pinned == nil {
rc.pinned = make(map[string]bool)
}
rc.pinned[resourceID] = true
}
// UnpinResource removes the pinned status from a resource
func (rc *ResolvedContext) UnpinResource(resourceID string) {
rc.mu.Lock()
defer rc.mu.Unlock()
delete(rc.pinned, resourceID)
}
// IsPinned returns whether a resource is pinned
func (rc *ResolvedContext) IsPinned(resourceID string) bool {
rc.mu.RLock()
defer rc.mu.RUnlock()
return rc.pinned[resourceID]
}
// Clear removes all resources from the context (respects pinned)
func (rc *ResolvedContext) Clear(keepPinned bool) {
rc.mu.Lock()
defer rc.mu.Unlock()
rc.ensureResourceIndexes()
if !keepPinned {
rc.Resources = make(map[string]*ResolvedResource)
rc.ResourcesByID = make(map[string]*ResolvedResource)
rc.ResourcesByAlias = make(map[string]*ResolvedResource)
rc.lastAccessed = make(map[string]time.Time)
rc.pinned = make(map[string]bool)
return
}
// Keep only pinned resources
var toKeep []string
for resourceID := range rc.pinned {
if rc.pinned[resourceID] {
toKeep = append(toKeep, resourceID)
}
}
// Rebuild with only pinned resources
oldByID := rc.ResourcesByID
rc.Resources = make(map[string]*ResolvedResource)
rc.ResourcesByID = make(map[string]*ResolvedResource)
rc.ResourcesByAlias = make(map[string]*ResolvedResource)
newLastAccessed := make(map[string]time.Time)
for _, resourceID := range toKeep {
if res, ok := oldByID[resourceID]; ok {
rc.Resources[resourceID] = res
rc.ResourcesByID[resourceID] = res
if lastAccess, ok := rc.lastAccessed[resourceID]; ok {
newLastAccessed[resourceID] = lastAccess
}
}
}
rc.lastAccessed = newLastAccessed
rc.rebuildAliasIndex()
}
// Stats returns statistics about the context
func (rc *ResolvedContext) Stats() ResolvedContextStats {
rc.mu.RLock()
defer rc.mu.RUnlock()
uniqueCount := len(rc.ResourcesByID)
pinnedCount := 0
for _, isPinned := range rc.pinned {
if isPinned {
pinnedCount++
}
}
return ResolvedContextStats{
UniqueResources: uniqueCount,
TotalAliases: len(rc.ResourcesByAlias),
PinnedResources: pinnedCount,
MaxEntries: rc.maxEntries,
TTL: rc.ttl,
}
}
// ResolvedContextStats provides statistics about a resolved context
type ResolvedContextStats struct {
UniqueResources int `json:"unique_resources"`
TotalAliases int `json:"total_aliases"`
PinnedResources int `json:"pinned_resources"`
MaxEntries int `json:"max_entries"`
TTL time.Duration `json:"ttl"`
}
// HasAnyResources implements tools.ResolvedContextProvider interface.
// Returns true if at least one resource has been discovered in this session.
func (rc *ResolvedContext) HasAnyResources() bool {
rc.mu.RLock()
defer rc.mu.RUnlock()
return len(rc.ResourcesByID) > 0
}
// WasRecentlyAccessed checks if a resource was EXPLICITLY accessed within the given time window.
// This uses the separate explicitlyAccessed tracking (set only via MarkExplicitAccess),
// NOT the general lastAccessed (which is set on every add/get for LRU purposes).
//
// This distinction is critical for routing validation:
// - Bulk discovery adds resources (sets lastAccessed) but should NOT trigger routing blocks
// - Explicit get/select sets explicitlyAccessed, indicating user intent to target that resource
func (rc *ResolvedContext) WasRecentlyAccessed(resourceID string, window time.Duration) bool {
rc.mu.RLock()
defer rc.mu.RUnlock()
if rc.explicitlyAccessed == nil {
return false
}
explicitAccess, ok := rc.explicitlyAccessed[resourceID]
if !ok {
return false
}
return time.Since(explicitAccess) <= window
}
// GetRecentlyAccessedResources returns resources that were EXPLICITLY accessed within the given time window.
// Uses explicitlyAccessed (not lastAccessed) to avoid false positives from bulk discovery.
// Returns a slice of resource IDs.
func (rc *ResolvedContext) GetRecentlyAccessedResources(window time.Duration) []string {
rc.mu.RLock()
defer rc.mu.RUnlock()
if rc.explicitlyAccessed == nil {
return nil
}
var recent []string
cutoff := time.Now().Add(-window)
for resourceID, explicitAccess := range rc.explicitlyAccessed {
if explicitAccess.After(cutoff) {
recent = append(recent, resourceID)
}
}
return recent
}
// GetRecentlyAccessedResourcesSorted returns recently accessed resources ordered by most recent access.
// If max <= 0, all recent resources are returned.
func (rc *ResolvedContext) GetRecentlyAccessedResourcesSorted(window time.Duration, max int) []string {
rc.mu.RLock()
defer rc.mu.RUnlock()
if rc.explicitlyAccessed == nil {
return nil
}
cutoff := time.Now().Add(-window)
type recentResource struct {
id string
ts time.Time
}
var recent []recentResource
for resourceID, explicitAccess := range rc.explicitlyAccessed {
if explicitAccess.After(cutoff) {
if _, ok := rc.ResourcesByID[resourceID]; ok {
recent = append(recent, recentResource{id: resourceID, ts: explicitAccess})
}
}
}
sort.Slice(recent, func(i, j int) bool {
return recent[i].ts.After(recent[j].ts)
})
if max > 0 && len(recent) > max {
recent = recent[:max]
}
ids := make([]string, len(recent))
for i, res := range recent {
ids[i] = res.id
}
return ids
}
// AddResource adds a resolved resource to the context (internal use).
// NOTE: This does NOT mark the resource as "recently accessed" for routing validation.
// Use MarkExplicitAccess() when the user explicitly selects/queries a single resource.
// This separation prevents bulk discovery operations from poisoning routing validation.
func (rc *ResolvedContext) AddResource(name string, res *ResolvedResource) {
rc.mu.Lock()
defer rc.mu.Unlock()
rc.addResourceInternal(name, res, false)
}
// AddResourceWithExplicitAccess adds a resource AND marks it as recently accessed.
// Use this for single-resource operations where user intent is clear (e.g., pulse_query get).
func (rc *ResolvedContext) AddResourceWithExplicitAccess(name string, res *ResolvedResource) {
rc.mu.Lock()
defer rc.mu.Unlock()
rc.addResourceInternal(name, res, true)
}
// addResourceInternal is the shared implementation for adding resources.
func (rc *ResolvedContext) addResourceInternal(name string, res *ResolvedResource, markExplicitAccess bool) {
// Initialize maps if needed (e.g., after JSON deserialization)
if rc.Resources == nil {
rc.Resources = make(map[string]*ResolvedResource)
}
if rc.ResourcesByID == nil {
rc.ensureResourceIndexes()
}
if rc.ResourcesByAlias == nil {
rc.ResourcesByAlias = make(map[string]*ResolvedResource)
}
if rc.lastAccessed == nil {
rc.lastAccessed = make(map[string]time.Time)
}
if rc.explicitlyAccessed == nil {
rc.explicitlyAccessed = make(map[string]time.Time)
}
if rc.pinned == nil {
rc.pinned = make(map[string]bool)
}
if rc.maxEntries == 0 {
rc.maxEntries = DefaultResolvedContextMaxEntries
}
if rc.ttl == 0 {
rc.ttl = DefaultResolvedContextTTL
}
// Evict expired and overflow before adding
rc.evictExpired()
if res == nil {
return
}
if res.ResourceID == "" {
res.ResourceID = name
}
if name != "" && name != res.Name {
res.Aliases = append(res.Aliases, name)
}
rc.Resources[res.ResourceID] = res
rc.ResourcesByID[res.ResourceID] = res
rc.rebuildAliasIndex()
// Always update lastAccessed for LRU/TTL tracking
rc.touch(res.ResourceID)
// Only mark explicit access if requested (single-resource operations)
// This prevents bulk discovery from poisoning routing validation
if markExplicitAccess {
rc.explicitlyAccessed[res.ResourceID] = time.Now()
}
// Evict overflow after adding
rc.evictOverflow()
rc.LastUpdated = time.Now()
}
// MarkExplicitAccess marks a resource as explicitly accessed for routing validation.
//
// IMPORTANT: This method should ONLY be called from user-intent codepaths:
//
// ✅ User @mention resolution (service.go - prefetcher mentions)
// ✅ Single-resource pulse_query get (tools_query.go - registerResolvedResourceWithExplicitAccess)
// ✅ Explicit user selection of a specific resource
//
// DO NOT call from:
//
// ❌ Bulk discovery/search operations (pulse_query search, list)
// ❌ Background topology refresh
// ❌ Periodic prefetch scans
// ❌ Low-level discovery registration helpers
//
// This sets the explicitlyAccessed timestamp (separate from lastAccessed used for LRU).
// The routing validation (WasRecentlyAccessed) checks explicitlyAccessed, not lastAccessed.
//
// If this is called incorrectly from bulk operations, routing validation will produce
// false positives, blocking legitimate host operations.
func (rc *ResolvedContext) MarkExplicitAccess(resourceID string) {
rc.mu.Lock()
defer rc.mu.Unlock()
if rc.explicitlyAccessed == nil {
rc.explicitlyAccessed = make(map[string]time.Time)
}
rc.explicitlyAccessed[resourceID] = time.Now()
}
// AddResolvedResource implements tools.ResolvedContextProvider interface.
// Called by query/discovery tools to register discovered resources.
func (rc *ResolvedContext) AddResolvedResource(reg tools.ResourceRegistration) {
rc.mu.Lock()
defer rc.mu.Unlock()
resourceID := reg.ResolvedID()
// Build display path from location chain
var displayPath string
if len(reg.LocationChain) > 0 {
displayPath = strings.Join(reg.LocationChain, " @ ")
}
// Collect all allowed actions from executors
actionSet := make(map[string]bool)
var reachableVia []ExecutorPath
for _, exec := range reg.Executors {
for _, action := range exec.Actions {
actionSet[action] = true
}
reachableVia = append(reachableVia, ExecutorPath{
ExecutorID: exec.ExecutorID,
Adapter: exec.Adapter,
Actions: exec.Actions,
Priority: exec.Priority,
})
}
var allowedActions []string
for action := range actionSet {
allowedActions = append(allowedActions, action)
}
// Get legacy routing from first/best executor
var targetHost, agentID, adapter string
if len(reg.Executors) > 0 {
best := reg.Executors[0]
for _, exec := range reg.Executors[1:] {
if exec.Priority > best.Priority {
best = exec
}
}
targetHost = best.ExecutorID
agentID = best.ExecutorID
adapter = best.Adapter
}
// Build aliases list, ensuring name is included
aliases := reg.Aliases
if len(aliases) == 0 {
aliases = []string{reg.Name}
} else {
// Ensure name is in aliases
hasName := false
for _, a := range aliases {
if strings.EqualFold(a, reg.Name) {
hasName = true
break
}
}
if !hasName {
aliases = append([]string{reg.Name}, aliases...)
}
}
res := &ResolvedResource{
// Structured identity
Kind: reg.Kind,
ProviderUID: reg.ProviderUID,
Scope: ResourceScope{
HostUID: reg.HostUID,
HostName: reg.HostName,
ParentUID: reg.ParentUID,
ParentKind: reg.ParentKind,
ClusterUID: reg.ClusterUID,
Namespace: reg.Namespace,
},
Aliases: aliases,
// Derived/display
ResourceID: resourceID,
Name: reg.Name,
ResourceType: reg.Kind, // backwards compat
DisplayPath: displayPath,
LocationChain: reg.LocationChain,
// Executor paths
ReachableVia: reachableVia,
// Legacy routing
TargetHost: targetHost,
AgentID: agentID,
Adapter: adapter,
// Resource-specific
VMID: reg.VMID,
Node: reg.Node,
// Actions
AllowedActions: allowedActions,
// Timestamps
ResolvedAt: time.Now(),
}
rc.addResourceInternal(reg.Name, res, false)
}
// GetResource retrieves a resource by name (case-insensitive)
// Updates LRU tracking on access.
func (rc *ResolvedContext) GetResource(name string) (*ResolvedResource, bool) {
rc.mu.Lock()
defer rc.mu.Unlock()
return rc.getResourceInternal(name)
}
// getResourceInternal is the lock-free implementation of GetResource.
func (rc *ResolvedContext) getResourceInternal(name string) (*ResolvedResource, bool) {
// Evict expired on access
rc.evictExpired()
// Try exact match first
if res, ok := rc.Resources[name]; ok {
rc.touch(res.ResourceID)
return res, true
}
// Try alias index
if res, ok := rc.ResourcesByAlias[strings.ToLower(strings.TrimSpace(name))]; ok && res != nil {
rc.touch(res.ResourceID)
return res, true
}
return nil, false
}
// GetResourceByID retrieves a resource by its canonical ResourceID (internal use)
// Updates LRU tracking on access.
func (rc *ResolvedContext) GetResourceByID(resourceID string) (*ResolvedResource, bool) {
rc.mu.Lock()
defer rc.mu.Unlock()
return rc.getResourceByIDInternal(resourceID)
}
// getResourceByIDInternal is the lock-free implementation of GetResourceByID.
func (rc *ResolvedContext) getResourceByIDInternal(resourceID string) (*ResolvedResource, bool) {
// Evict expired on access
rc.evictExpired()
res, ok := rc.ResourcesByID[resourceID]
if ok {
rc.touch(resourceID)
}
return res, ok
}
// GetResolvedResourceByID implements tools.ResolvedContextProvider interface.
// Updates LRU tracking on access.
func (rc *ResolvedContext) GetResolvedResourceByID(resourceID string) (tools.ResolvedResourceInfo, bool) {
rc.mu.Lock()
defer rc.mu.Unlock()
// Evict expired on access
rc.evictExpired()
res, ok := rc.ResourcesByID[resourceID]
if !ok {
return nil, false
}
rc.touch(resourceID)
return res, true
}
// GetResolvedResourceByAlias implements tools.ResolvedContextProvider interface.
// Retrieves a resource by any of its aliases (case-insensitive).
// Updates LRU tracking on access.
func (rc *ResolvedContext) GetResolvedResourceByAlias(alias string) (tools.ResolvedResourceInfo, bool) {
rc.mu.Lock()
defer rc.mu.Unlock()
// Evict expired on access
rc.evictExpired()
res, ok := rc.ResourcesByAlias[strings.ToLower(strings.TrimSpace(alias))]
if !ok || res == nil {
return nil, false
}
rc.touch(res.ResourceID)
return res, true
}
// ListResolvedResources returns every live resource the session has resolved,
// ordered by canonical ID. It does not touch LRU state: enumeration is
// evidence gathering for the advertised-action gate, not user access.
func (rc *ResolvedContext) ListResolvedResources() []tools.ResolvedResourceInfo {
rc.mu.Lock()
defer rc.mu.Unlock()
rc.evictExpired()
ids := make([]string, 0, len(rc.ResourcesByID))
for id, res := range rc.ResourcesByID {
if res != nil {
ids = append(ids, id)
}
}
sort.Strings(ids)
resources := make([]tools.ResolvedResourceInfo, 0, len(ids))
for _, id := range ids {
resources = append(resources, rc.ResourcesByID[id])
}
return resources
}
// ValidateResourceID checks if a resource ID exists in this context
// and returns the resource if valid
func (rc *ResolvedContext) ValidateResourceID(resourceID string) (*ResolvedResource, error) {
rc.mu.Lock()
defer rc.mu.Unlock()
return rc.validateResourceIDInternal(resourceID)
}
// validateResourceIDInternal is the lock-free implementation of ValidateResourceID.
func (rc *ResolvedContext) validateResourceIDInternal(resourceID string) (*ResolvedResource, error) {
res, ok := rc.getResourceByIDInternal(resourceID)
if !ok {
return nil, &ResourceNotResolvedError{ResourceID: resourceID}
}
return res, nil
}
// ValidateAction checks if an action is allowed for a resource (internal use)
func (rc *ResolvedContext) ValidateAction(resourceID, action string) error {
rc.mu.Lock()
defer rc.mu.Unlock()
return rc.validateActionInternal(resourceID, action)
}
// validateActionInternal is the lock-free implementation of ValidateAction.
func (rc *ResolvedContext) validateActionInternal(resourceID, action string) error {
res, err := rc.validateResourceIDInternal(resourceID)
if err != nil {
return err
}
// If no actions specified, allow all (backwards compatibility)
if len(res.AllowedActions) == 0 {
return nil
}
for _, allowed := range res.AllowedActions {
if allowed == action || allowed == "*" {
return nil
}
}
return &ActionNotAllowedError{
ResourceID: resourceID,
Action: action,
Allowed: res.AllowedActions,
}
}
// ValidateResourceForAction implements tools.ResolvedContextProvider interface.
// Returns the resource if valid, error if not found or action not allowed.
func (rc *ResolvedContext) ValidateResourceForAction(resourceID, action string) (tools.ResolvedResourceInfo, error) {
rc.mu.Lock()
defer rc.mu.Unlock()
if err := rc.validateActionInternal(resourceID, action); err != nil {
return nil, err
}
res, _ := rc.getResourceByIDInternal(resourceID)
return res, nil
}
// ResourceNotResolvedError indicates a resource ID wasn't found in the context
type ResourceNotResolvedError struct {
ResourceID string
}
func (e *ResourceNotResolvedError) Error() string {
return "resource not resolved: " + e.ResourceID + " - resource discovery is required before this action"
}
// ActionNotAllowedError indicates an action isn't permitted for a resource
type ActionNotAllowedError struct {
ResourceID string
Action string
Allowed []string
}
func (e *ActionNotAllowedError) Error() string {
return "action '" + e.Action + "' not allowed for resource " + e.ResourceID
}
// Max turns for the agentic loop to prevent infinite loops
const (
MaxAgenticTurns = 20
DefaultStatelessContext = false
MaxContextMessagesLimit = 40
// MaxToolResultCharsLimit caps tool results sent to the LLM.
// With context compaction in place, this safety net rarely fires.
// 16K chars (~4K tokens) is sufficient for any single tool result.
// The UI shows full results regardless of this limit.
MaxToolResultCharsLimit = 16000
)
var (
StatelessContext = DefaultStatelessContext
)