ai

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 8, 2026 License: MIT Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const EventBackgroundAnalysis = "ai.background"

EventBackgroundAnalysis is emitted when a background AI run completes.

Variables

This section is empty.

Functions

func BuildChatPrompt added in v0.2.0

func BuildChatPrompt(language string, snap *metrics.SystemSnapshot, alerts []anomaly.Alert, includeTree, includePorts bool, history []chatTurn, userMessage string) string

BuildChatPrompt assembles the multi-turn chat prompt using the same snapshot context as Analyze plus a short in-memory conversation window.

func BuildPrompt

func BuildPrompt(language string, snap *metrics.SystemSnapshot, alerts []anomaly.Alert, includeTree, includePorts bool, userQuestion string) string

BuildPrompt assembles the user message that we send to the LLM.

func SystemPrompt

func SystemPrompt(_ string) string

SystemPrompt returns the system prompt for the requested language. Only English is supported; the argument is kept for forward compatibility with older callers that still pass a language hint.

Types

type Advisor

type Advisor struct {
	// contains filtered or unexported fields
}

Advisor wraps one or more LLM provider backends with caching and rate limiting. It implements the server.AIAdvisor interface (Enabled / Status / Analyze).

Currently supported providers:

  • "anthropic" -> Anthropic Messages API ( /v1/messages )
  • "openai" -> any OpenAI-compatible /v1/chat/completions endpoint (OpenAI, OpenRouter, Groq, DeepSeek, Together, Mistral, Ollama, LM Studio, ...)

The endpoint, model, api_key and extra_headers fields can all be overridden in the config so the user can point this at any provider without code changes.

func NewAdvisor

func NewAdvisor(cfg *config.Config, store *storage.Store, alertSource func() []anomaly.Alert, emitter *event.Emitter) *Advisor

NewAdvisor builds a new advisor. alertSource is a closure that returns the current active alerts for the prompt context.

func (*Advisor) Analyze

func (a *Advisor) Analyze(ctx context.Context, userQuestion string) (*AnalyzeResult, error)

Analyze runs an LLM call. The user-supplied question is appended to a snapshot+alerts context. Cached responses are returned without making an HTTP call. The returned AnalyzeResult carries both the prose answer (with any <actions> block stripped) and the parsed structured actions.

func (*Advisor) BackgroundState

func (a *Advisor) BackgroundState() BackgroundState

BackgroundState returns the scheduler's current status plus recent runs.

func (*Advisor) Chat added in v0.2.0

func (a *Advisor) Chat(ctx context.Context, userMessage string) (*AnalyzeResult, error)

Chat runs a multi-turn AI exchange against the current system snapshot. Conversation history is kept in-memory and trimmed to the last 10 messages.

func (*Advisor) Enabled

func (a *Advisor) Enabled() bool

Enabled reports whether the advisor is configured to run.

func (*Advisor) SetConfig

func (a *Advisor) SetConfig(cfg *config.Config)

SetConfig hot-swaps the active config.

func (*Advisor) Start added in v0.2.0

func (a *Advisor) Start(ctx context.Context)

Start binds the advisor's background work to the application lifecycle.

func (*Advisor) Status

func (a *Advisor) Status() map[string]any

Status returns a JSON-friendly status snapshot.

type AnalyzeResult

type AnalyzeResult struct {
	Answer  string       `json:"answer"`
	Actions []Suggestion `json:"actions,omitempty"`
	Cached  bool         `json:"cached,omitempty"`
}

AnalyzeResult is what the advisor hands back: the visible answer stripped of the raw <actions> block, plus the parsed structured actions.

type AutoPolicy

type AutoPolicy struct {
	Status              string `json:"status"` // disabled | blocked | needs_repeat | dry_run_eligible
	Reason              string `json:"reason,omitempty"`
	RepeatCount         int    `json:"repeat_count,omitempty"`
	RequiredRepeatCount int    `json:"required_repeat_count,omitempty"`
}

AutoPolicy explains whether a suggestion would qualify for future background auto-execution. Phase 2 is still dry-run only: we surface deterministic eligibility, but do not execute automatically yet.

type BackgroundBudget

type BackgroundBudget struct {
	CyclesLastHour          int       `json:"cycles_last_hour"`
	MaxCyclesPerHour        int       `json:"max_cycles_per_hour"`
	ReservedTokensToday     int       `json:"reserved_tokens_today"`
	MaxReservedTokensPerDay int       `json:"max_reserved_tokens_per_day"`
	MinIntervalSeconds      int       `json:"min_interval_seconds"`
	CooldownUntil           time.Time `json:"cooldown_until,omitempty"`
}

BackgroundBudget reports the scheduler's active guardrails.

type BackgroundRun

type BackgroundRun struct {
	Trigger        string       `json:"trigger"`
	AlertID        string       `json:"alert_id,omitempty"`
	AlertType      string       `json:"alert_type,omitempty"`
	AlertTitle     string       `json:"alert_title,omitempty"`
	AlertPID       uint32       `json:"alert_pid,omitempty"`
	AlertProcess   string       `json:"alert_process,omitempty"`
	StartedAt      time.Time    `json:"started_at"`
	FinishedAt     time.Time    `json:"finished_at"`
	ReservedTokens int          `json:"reserved_tokens"`
	Cached         bool         `json:"cached"`
	Error          string       `json:"error,omitempty"`
	Answer         string       `json:"answer,omitempty"`
	Actions        []Suggestion `json:"actions,omitempty"`
	AutoCandidates int          `json:"auto_candidates,omitempty"`
}

BackgroundRun records one completed background analysis cycle.

type BackgroundState

type BackgroundState struct {
	Enabled               bool             `json:"enabled"`
	Configured            bool             `json:"configured"`
	AutoAnalyzeOnCritical bool             `json:"auto_analyze_on_critical"`
	AutoActionEnabled     bool             `json:"auto_action_enabled"`
	AutoActionDryRun      bool             `json:"auto_action_dry_run"`
	InFlight              bool             `json:"in_flight"`
	LastEventAt           time.Time        `json:"last_event_at,omitempty"`
	LastSkipReason        string           `json:"last_skip_reason,omitempty"`
	LastError             string           `json:"last_error,omitempty"`
	LastRun               *BackgroundRun   `json:"last_run,omitempty"`
	RecentRuns            []BackgroundRun  `json:"recent_runs,omitempty"`
	Budget                BackgroundBudget `json:"budget"`
}

BackgroundState is the JSON shape returned by /api/v1/ai/watch.

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

Cache is a small in-memory TTL cache keyed by prompt hash.

func NewCache

func NewCache(ttl time.Duration, maxSize int) *Cache

func (*Cache) Get

func (c *Cache) Get(prompt string) (string, bool)

Get returns the cached answer for `prompt` if present and unexpired.

func (*Cache) Set

func (c *Cache) Set(prompt, answer string)

Set stores an answer in the cache, evicting oldest when at capacity.

func (*Cache) Size

func (c *Cache) Size() int

Size returns current cache occupancy.

type RuleSuggestion

type RuleSuggestion struct {
	Name            string  `json:"name"`
	Enabled         bool    `json:"enabled"`
	Match           string  `json:"match"`
	Metric          string  `json:"metric"`
	Op              string  `json:"op"`
	Threshold       float64 `json:"threshold"`
	For             int     `json:"for,omitempty"`
	ForSeconds      int     `json:"for_seconds,omitempty"`
	Action          string  `json:"action"`
	Cooldown        int     `json:"cooldown,omitempty"`
	CooldownSeconds int     `json:"cooldown_seconds,omitempty"`
}

RuleSuggestion is the wire shape for a rule proposed by the LLM. We keep durations as plain seconds ints (not Go time.Duration) so JSON encoding matches the rules API the dashboard already speaks. We also accept both `for`/`cooldown` and `for_seconds`/`cooldown_seconds` because the model picks whichever it thinks looks "nicer" despite the prompt telling it to use the explicit *_seconds form.

type Suggestion

type Suggestion struct {
	ID     string          `json:"id"`               // stable hash so the UI can dedupe
	Type   string          `json:"type"`             // kill | suspend | protect | ignore | add_rule
	PID    uint32          `json:"pid,omitempty"`    // required for kill/suspend
	Name   string          `json:"name,omitempty"`   // executable name (used by protect/ignore)
	Reason string          `json:"reason,omitempty"` // free-form, <=80 chars
	Rule   *RuleSuggestion `json:"rule,omitempty"`   // populated for add_rule suggestions
	Policy *AutoPolicy     `json:"policy,omitempty"` // background auto-action evaluation
}

Suggestion is one concrete operation the LLM proposes. The dashboard renders these as approve-buttons; nothing executes until the user clicks.

type TokenBucket

type TokenBucket struct {
	// contains filtered or unexported fields
}

TokenBucket is a minimal per-minute rate limiter.

func NewTokenBucket

func NewTokenBucket(perMinute int) *TokenBucket

func (*TokenBucket) Available

func (tb *TokenBucket) Available() int

Available reports current bucket level.

func (*TokenBucket) Take

func (tb *TokenBucket) Take() bool

Take consumes a token if available; returns false if not.

type TokenUsage added in v0.3.0

type TokenUsage struct {
	Prompt     uint64
	Completion uint64
	Total      uint64
}

TokenUsage holds token counts from a provider response.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL