ai

package
v0.4.0-beta.1 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SessionStatusReady            = "ready"
	SessionStatusAwaitingApproval = "awaiting_approval"
	SessionScopeSystem            = "system"
	SessionScopeDeployment        = "deployment"
)
View Source
const (
	SuggestionKindExec          = "exec"
	SuggestionKindServiceAction = "service_action"
)

Variables

View Source
var ErrAgentNotFound = fmt.Errorf("agent not found")
View Source
var ErrDisabled = errors.New("ai is not enabled")

ErrDisabled is returned by New when no provider is configured. The caller treats it as "feature off", not as a failure.

View Source
var ErrSessionNotFound = fmt.Errorf("session not found")

Functions

func BuildSessionPrompt

func BuildSessionPrompt(scope, deployment, docsURL string) string

BuildSessionPrompt returns the system prompt for an interactive session, optionally scoped to one deployment and referencing the docs site.

func IntentKeys

func IntentKeys() []string

func MessagesToAgents

func MessagesToAgents(messages []Message) []agents.Message

MessagesToAgents converts the stored transcript to the library's message type. Display and Hidden are UI-only and dropped here: the model sees Content.

func TruncateHead

func TruncateHead(s string, max int) string

Types

type Agent

type Agent struct {
	Name         string `json:"name" yaml:"-"`
	Description  string `json:"description" yaml:"description"`
	Scope        string `json:"scope" yaml:"scope"`
	Deployment   string `json:"deployment,omitempty" yaml:"deployment"`
	Instructions string `json:"-" yaml:"-"`
}

Agent is an agent definition: a flat markdown file with YAML frontmatter for metadata and a body of instructions. The runtime executes it through the shared tool set; the file is the whole definition, so it can be read, edited, and versioned like any other deployment file.

func ParseAgent

func ParseAgent(name, content string) (*Agent, error)

ParseAgent reads an agent definition. Frontmatter is optional; a bare markdown file is a system-scoped agent whose whole content is the instructions.

type AgentStore

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

AgentStore reads agent definitions from a flat directory of markdown files, one agent per file, named by the file's basename.

func NewAgentStore

func NewAgentStore(deploymentsPath string) *AgentStore

func (*AgentStore) Delete

func (st *AgentStore) Delete(name string) error

Delete removes an agent definition.

func (*AgentStore) Dir

func (st *AgentStore) Dir() string

Dir is the directory agent definition files live in.

func (*AgentStore) Get

func (st *AgentStore) Get(name string) (*Agent, error)

Get loads one agent by name.

func (*AgentStore) List

func (st *AgentStore) List() ([]*Agent, error)

List returns every valid agent, sorted by name. A file that fails to parse is skipped rather than breaking the listing.

func (*AgentStore) Raw

func (st *AgentStore) Raw(name string) (string, error)

Raw returns the file content of one agent, for editing.

func (*AgentStore) Write

func (st *AgentStore) Write(name, content string) (*Agent, error)

Write validates and stores an agent definition. Invalid definitions are rejected rather than written, so the directory only ever holds runnable agents.

type CapturingEngine

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

CapturingEngine adapts a Provider to the library's Engine. It records the model each response reports, which the runner does not otherwise surface, so a session can still note which model answered.

func NewCapturingEngine

func NewCapturingEngine(p Provider) *CapturingEngine

func (*CapturingEngine) Complete

func (e *CapturingEngine) Complete(ctx context.Context, req agents.Request) (*agents.Response, error)

func (*CapturingEngine) LastModel

func (e *CapturingEngine) LastModel() string

LastModel is the model of the most recent response, or "" if none.

type DisplayToolStep

type DisplayToolStep struct {
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
	Result    string `json:"result,omitempty"`
}

DisplayMessages projects the transcript into UI-facing turns, dropping the system prompt and pairing tool calls with their results.

type DisplayTurn

type DisplayTurn struct {
	Role      string            `json:"role"`
	Content   string            `json:"content,omitempty"`
	ToolSteps []DisplayToolStep `json:"tool_steps,omitempty"`
}

type Intent

type Intent struct {
	Key              string
	Task             string
	AllowSuggestions bool
}

Intent selects what the model is asked to do with the gathered context. Adding a capability is adding an entry here; the pipeline, endpoints and UI do not change.

func GetIntent

func GetIntent(key string) (Intent, bool)

type Message

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
	// Display, when set, is what the UI shows for this turn instead of
	// Content. Used to send bulky context (logs, output) to the model
	// while showing the operator a short label. Never sent to the
	// provider.
	Display string `json:"display,omitempty"`
	// Hidden marks a turn the UI must not show at all: prompts composed
	// by the product (e.g. "analyze these logs") rather than typed by
	// the operator. The model still sees Content.
	Hidden bool `json:"hidden,omitempty"`
	// ToolCalls is set on an assistant message that wants tools run.
	ToolCalls []ToolCall `json:"tool_calls,omitempty"`
	// ToolCallID and Name identify a role:"tool" result message.
	ToolCallID string `json:"tool_call_id,omitempty"`
	Name       string `json:"name,omitempty"`
}

func BuildAssistMessages

func BuildAssistMessages(intent Intent, scopeLabel string, sections []Section, question, docsURL string) []Message

BuildAssistMessages assembles the chat for an analysis. Sections must already be redacted. The newest end of long sections survives truncation since it matters most.

func MessageFromAgents

func MessageFromAgents(m agents.Message) Message

MessageFromAgents converts a message the runner appended back to the stored type. Runner-created messages (assistant and tool turns) carry no UI fields.

type Provider

type Provider interface {
	Name() string
	Complete(ctx context.Context, req Request) (*Response, error)
}

Provider is the model-agnostic boundary: everything above this interface (handlers, prompts, redaction) is provider-neutral, and new backends plug in behind it without touching callers.

func New

func New(cfg *config.AIConfig) (Provider, error)

type Redactor

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

Redactor removes known secret values and credential-shaped assignments from text before it leaves the host.

func NewRedactor

func NewRedactor(secrets []string) *Redactor

func (*Redactor) Redact

func (r *Redactor) Redact(text string) (string, int)

type Request

type Request struct {
	Messages    []Message
	Tools       []Tool
	MaxTokens   int
	Temperature float64
}

type Response

type Response struct {
	Content   string     `json:"content"`
	ToolCalls []ToolCall `json:"tool_calls,omitempty"`
	Model     string     `json:"model"`
	Usage     Usage      `json:"usage"`
}

type Section

type Section struct {
	Label   string
	Content string
	Format  string
}

Section is one labeled piece of gathered context, already redacted.

type Session

type Session struct {
	ID         string `json:"id"`
	Scope      string `json:"scope"`
	Deployment string `json:"deployment,omitempty"`
	// Agent names the agent definition this session is a run of, when it was
	// started from one rather than typed by an operator.
	Agent     string            `json:"agent,omitempty"`
	AutoRun   bool              `json:"auto_run"`
	Status    string            `json:"status"`
	Model     string            `json:"model,omitempty"`
	CreatedBy SessionActor      `json:"created_by"`
	Messages  []Message         `json:"messages"`
	Pending   []ToolCall        `json:"pending,omitempty"`
	Suggested []SuggestedAction `json:"suggested_actions"`
	CreatedAt time.Time         `json:"created_at"`
	UpdatedAt time.Time         `json:"updated_at"`
}

Session is one ongoing AI conversation. It owns the full model transcript (including tool calls and results) plus the derived state the UI needs. Stored as a flat JSON file, true to FlatRun.

func NewSession

func NewSession(scope, deployment string, autoRun bool, actor SessionActor, systemPrompt string) *Session

func (*Session) AddAssistantMessage

func (s *Session) AddAssistantMessage(content string, toolCalls []ToolCall)

func (*Session) AddToolResult

func (s *Session) AddToolResult(call ToolCall, result string)

func (*Session) AddUserMessage

func (s *Session) AddUserMessage(content, display string, hidden bool)

AddUserMessage records a user turn. When display differs from content, the model sees content (e.g. message plus embedded logs) while the UI shows display (e.g. a short label).

func (*Session) DisplayMessages

func (s *Session) DisplayMessages() []DisplayTurn

func (*Session) MaxToolSteps

func (s *Session) MaxToolSteps() int

MaxToolSteps is the per-turn cap on consecutive tool rounds, so a misbehaving model cannot loop forever.

func (*Session) Summary

func (s *Session) Summary() SessionSummary

Summary is the session without its transcript, for a list view.

func (*Session) Title

func (s *Session) Title() string

Title derives a short label from the first visible user turn, so a saved session is recognizable in a list. Falls back to the scope.

type SessionActor

type SessionActor struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

type SessionStore

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

func NewSessionStore

func NewSessionStore(deploymentsPath string) *SessionStore

func (*SessionStore) Delete

func (st *SessionStore) Delete(id string) error

func (*SessionStore) Get

func (st *SessionStore) Get(id string) (*Session, error)

func (*SessionStore) List

func (st *SessionStore) List() ([]SessionSummary, error)

List returns a summary of every stored session, most recently updated first.

func (*SessionStore) PruneOlderThan

func (st *SessionStore) PruneOlderThan(cutoff time.Time) int

PruneOlderThan removes sessions whose last update predates the cutoff, keeping the flat-file directory from growing without bound.

func (*SessionStore) Save

func (st *SessionStore) Save(sess *Session) error

type SessionSummary

type SessionSummary struct {
	ID         string       `json:"id"`
	Scope      string       `json:"scope"`
	Deployment string       `json:"deployment,omitempty"`
	Agent      string       `json:"agent,omitempty"`
	Status     string       `json:"status"`
	Title      string       `json:"title"`
	CreatedBy  SessionActor `json:"created_by"`
	CreatedAt  time.Time    `json:"created_at"`
	UpdatedAt  time.Time    `json:"updated_at"`
}

SessionSummary is the lightweight view of a session for a list, without the full transcript.

type SuggestedAction

type SuggestedAction struct {
	Kind    string `json:"kind"`
	Service string `json:"service,omitempty"`
	Action  string `json:"action,omitempty"`
	Command string `json:"command,omitempty"`
	Title   string `json:"title"`
	Reason  string `json:"reason,omitempty"`
}

SuggestedAction is a machine-actionable proposal extracted from a model response. It is never executed by the agent on its own; the client decides to run it through the normal, guarded APIs.

func ParseSuggestions

func ParseSuggestions(content string) (string, []SuggestedAction)

ParseSuggestions extracts the fenced suggestions block from a model response, returning the response without the block and the valid actions found in it. Malformed blocks and invalid entries are dropped; diagnosis text is never lost over a bad suggestion.

type Tool

type Tool struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Parameters  map[string]interface{} `json:"parameters"`
}

Tool is a function the model may call. Parameters is a JSON Schema object describing the arguments.

type ToolCall

type ToolCall struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
}

ToolCall is one tool invocation requested by the model. Arguments is a JSON object string as produced by the model.

func ToolCallsFromAgents

func ToolCallsFromAgents(calls []agents.ToolCall) []ToolCall

ToolCallsFromAgents converts the runner's tool calls to the stored type.

type Usage

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
}

Jump to

Keyboard shortcuts

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