config

package
v0.0.0-beta Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2026 License: MIT Imports: 37 Imported by: 0

Documentation

Overview

Package config manages agent configuration including modes, systems, providers, and agent definitions.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DenyError

func DenyError(pattern string) error

DenyError returns a formatted denial error for the given pattern.

func DiscoverPlugins

func DiscoverPlugins(root folder.Folder) (files.Files, error)

DiscoverPlugins walks root recursively, collecting plugin.yaml files. When a plugin.yaml is found, its directory is not descended further (SkipDir), which prevents scanning vendor/ or nested plugin trees. Hidden directories (. prefix) and vendor/ directories are skipped entirely.

func ExtractToolDetail

func ExtractToolDetail(toolName string, args map[string]any) string

ExtractToolDetail returns the primary argument detail for a tool call. For Bash: the command string. For file-operating tools: the path/file_path argument. Returns "" if no detail is available.

func New

func New(opts Options, parts ...Part) (Config, Paths, error)

New creates a Config by loading the requested parts from standard locations. When no parts are given, nothing is loaded — callers must declare what they need. Use AllParts() to load everything (equivalent to the old monolithic behavior).

func PackNames

func PackNames(pp StringCollection[Plugin]) []string

PackNames returns a sorted slice of unique pack directory names.

func Populate

func Populate(body string, args ...string) string

Populate performs argument substitution on a command body. Positional placeholders ($1, $2, ...) are replaced in reverse order to prevent $1 from clobbering $12. $ARGUMENTS is replaced with the full joined argument string.

func ResolvePluginDir

func ResolvePluginDir(home string) string

ResolvePluginDir returns the plugin directory for a given config home. It peeks at {home}/config/features/plugins.yaml for a "dir" field. Falls back to {home}/plugins when unset or unreadable.

func SaveToolApproval

func SaveToolApproval(configDir, pattern string) error

SaveToolApproval appends a tool auto-approval pattern to the rules file at configDir/config/rules/approvals.yaml. Creates the directory and file if they don't exist. Deduplicates entries. Uses advisory file locking for concurrent-instance safety.

func ToAnyMap

func ToAnyMap(m map[string]string) map[string]any

ToAnyMap converts a map[string]string to map[string]any. Used at the boundary between CLI parsing (which produces string maps) and TemplateData.Vars (which requires map[string]any for sprig compatibility).

Types

type Agent

type Agent struct {
	// Metadata contains agent configuration details.
	Metadata AgentMetadata
	// Prompt is the agent's prompt template.
	Prompt prompts.Prompt
}

Agent represents the configuration and prompt of an agent.

func ResolveDefault

func ResolveDefault(agents Collection[Agent], homes []string) (*Agent, error)

ResolveDefault finds the default agent using the following precedence:

  1. The agent with Default: true (error if multiple).
  2. The first non-hidden agent (alphabetical via Names).
  3. Error if no agents are available.

func (Agent) HasProvider

func (a Agent) HasProvider(providers []string) bool

HasProvider returns true if the agent's provider is in the given list (case-insensitive), or if the agent has no provider configured.

func (Agent) IsDefault

func (a Agent) IsDefault() bool

IsDefault returns true if the agent is marked as the default, for use as a Filter predicate.

func (Agent) IsSubagent

func (a Agent) IsSubagent() bool

IsSubagent returns true if the agent is available for the Task tool, for use as a Filter predicate.

func (Agent) Name

func (a Agent) Name() string

Name returns the agent's name, satisfying the Namer interface.

func (Agent) Visible

func (a Agent) Visible() bool

Visible returns true if the agent is not hidden, for use as a Filter predicate.

type AgentMetadata

type AgentMetadata struct {
	// Name is the unique identifier for the agent.
	Name string `validate:"required"`
	// Description explains the agent's purpose.
	Description string
	// Model specifies which AI model to use.
	Model Model `validate:"required"`
	// Tools defines tool availability for this agent.
	Tools Tools
	// Hooks controls which hooks are active for this agent.
	Hooks HookFilter
	// System is the name of the system prompt to use.
	System string
	// Mode is the operational mode for this agent.
	Mode string
	// Hide excludes this agent from UI listing and cycling.
	Hide *bool
	// Default marks this agent as the default when --agent is not specified.
	// Only one loaded agent may have Default: true (error if multiple).
	Default *bool `yaml:"default"`
	// Subagent marks this agent as available for the Task tool (subagent delegation).
	Subagent *bool `yaml:"subagent"`
	// AgentsMd controls which AGENTS.md files are injected into this agent's prompt.
	// Values: "" or "all" (default), "global", "local", "none".
	AgentsMd AgentsMdFilter `yaml:"agentsmd" validate:"omitempty,oneof=all global local none"`
	// Thinking controls how thinking blocks from prior turns are handled.
	Thinking thinking.Strategy
	// Files lists paths to load into the system prompt at BuildAgent() time.
	// Paths are expanded as Go templates before reading (e.g., {{ .Config.Source }}/file.md).
	// Relative paths are resolved against the config home directory.
	Files []string
	// SourceHome is the config home directory this agent was loaded from.
	// Set during Load() by matching the agent file's path against the homes list.
	SourceHome string `yaml:"-"`
	// Features holds per-agent feature overrides. Non-zero values are merged
	// on top of global feature defaults at agent resolution time.
	Features Features
	// Inherit lists parent agent names for config inheritance.
	Inherit []string `yaml:"inherit"`
	// Fallback lists agent names to try when this agent's provider fails.
	// Ordered: first entry is tried first. Evaluated only on the primary agent —
	// fallback agents' own fallback lists are ignored.
	Fallback []string `yaml:"fallback"`
	// ResponseFormat constrains LLM responses to a specific format (nil = unconstrained text).
	ResponseFormat *responseformat.ResponseFormat `yaml:"response_format"`
}

AgentMetadata holds the YAML-decoded configuration for an agent.

func (AgentMetadata) IsDefault

func (m AgentMetadata) IsDefault() bool

IsDefault returns true if the agent is marked as the default.

func (AgentMetadata) IsHidden

func (m AgentMetadata) IsHidden() bool

IsHidden returns true if the agent is excluded from UI listing.

func (AgentMetadata) IsSubagent

func (m AgentMetadata) IsSubagent() bool

IsSubagent returns true if the agent is available for the Task tool.

type AgentsMd

type AgentsMd struct {
	// Prompt is the content of the AGENTS.md file.
	Prompt prompts.Prompt
	// Type identifies whether this is a global or local configuration.
	Type Type
}

AgentsMd represents an AGENTS.md configuration file with its scope.

type AgentsMdFilter

type AgentsMdFilter string

AgentsMdFilter controls which AGENTS.md scopes are injected into an agent's prompt.

const (
	// AgentsMdAll injects all AGENTS.md files (default when field is empty).
	AgentsMdAll AgentsMdFilter = ""
	// AgentsMdGlobal injects only global-scoped AGENTS.md files.
	AgentsMdGlobal AgentsMdFilter = "global"
	// AgentsMdLocal injects only local-scoped AGENTS.md files.
	AgentsMdLocal AgentsMdFilter = "local"
	// AgentsMdNone skips all AGENTS.md injection.
	AgentsMdNone AgentsMdFilter = "none"
)

func (AgentsMdFilter) Includes

func (f AgentsMdFilter) Includes(t Type) bool

Includes returns whether the given AGENTS.md scope passes this filter.

type AgentsMds

type AgentsMds map[file.File]AgentsMd

AgentsMds maps files to their corresponding AgentsMd configurations.

func (*AgentsMds) Load

func (a *AgentsMds) Load(files files.Files, globalHome string) error

Load populates the AgentsMds map from the given files. globalHome is the path to ~/.aura (or "") — files under it are tagged Global, others Local.

type ApprovalRules

type ApprovalRules struct {
	Project Approvals
	Global  Approvals
}

ApprovalRules holds merged approval patterns with provenance (project vs global).

func (*ApprovalRules) Load

func (r *ApprovalRules) Load(ff files.Files, globalHome string) error

Load populates approval rules from the discovered rules files. Files under globalHome are tagged Global, others Project.

type Approvals

type Approvals struct {
	ToolAuto []string `yaml:"tool_auto"`
}

Approvals holds approval patterns loaded from a single rules file.

type BashTruncation

type BashTruncation struct {
	// MaxOutputBytes caps the number of bytes captured from stdout/stderr during execution.
	// Prevents OOM from unbounded output (e.g., binary dumps, base64).
	// nil = apply default (1MB), 0 = disabled (no byte cap), N = cap at N bytes.
	MaxOutputBytes *int `yaml:"max_output_bytes"`
	// MaxLines is the line count threshold above which output is truncated.
	// nil = disabled (no truncation), 0 = exit-code only, N = truncate after N lines.
	MaxLines *int `yaml:"max_lines"`
	// HeadLines is the number of lines kept from the beginning.
	HeadLines *int `yaml:"head_lines"`
	// TailLines is the number of lines kept from the end.
	TailLines *int `yaml:"tail_lines"`
}

BashTruncation holds configuration for Bash tool output truncation. Output exceeding MaxLines is middle-truncated: first HeadLines + last TailLines, with full output saved to a temp file. Pointer fields distinguish "not set" (nil → apply default) from explicit zero (0 → truncate all output, exit-code only).

type CLIOverrides

type CLIOverrides struct {
	MaxSteps    *int // --max-steps (nil = not set, use config default)
	TokenBudget *int // --token-budget (nil = not set, use config default)
}

CLIOverrides holds CLI flag values that must survive per-turn config reloads. Pointer fields distinguish "not set" (nil) from "set to zero value".

type Capability

type Capability string

Capability represents a provider-level capability.

const (
	CapChat       Capability = "chat"
	CapEmbed      Capability = "embed"
	CapRerank     Capability = "rerank"
	CapTranscribe Capability = "transcribe"
	CapSynthesize Capability = "synthesize"
)

type Collection

type Collection[T Namer] map[file.File]T

Collection is a file-keyed collection of config entities. Used for Agents, Modes, Skills, CustomCommands, Systems.

func (Collection[T]) Apply

func (c Collection[T]) Apply(fn func(*T))

Apply calls fn on each entity, writing the result back (mutates in-place).

func (Collection[T]) Filter

func (c Collection[T]) Filter(fn func(T) bool) Collection[T]

Filter returns a new collection containing only entities matching the predicate.

func (Collection[T]) Get

func (c Collection[T]) Get(name string) *T

Get retrieves an entity by name (case-insensitive), returning nil if not found.

func (Collection[T]) GetWithKey

func (c Collection[T]) GetWithKey(name string) (file.File, *T)

GetWithKey retrieves an entity by name (case-insensitive), returning both the source file key and a pointer to the entity. Returns zero file and nil if not found.

func (Collection[T]) Names

func (c Collection[T]) Names() []string

Names returns a sorted list of all entity names.

func (Collection[T]) RemoveIf

func (c Collection[T]) RemoveIf(fn func(T) bool)

RemoveIf deletes all entries matching the predicate (mutates in-place).

func (Collection[T]) Values

func (c Collection[T]) Values() []T

Values returns all entities sorted by Name().

type Compaction

type Compaction struct {
	// Threshold is the context window fill percentage that triggers automatic compaction.
	Threshold float64 `yaml:"threshold"`
	// MaxTokens is an absolute token count that triggers compaction when exceeded.
	// Takes priority over Threshold — when set, percentage mode is not used.
	MaxTokens int `yaml:"max_tokens"`
	// TrimThreshold is the fill percentage at which duplicate synthetic messages are removed.
	TrimThreshold float64 `yaml:"trim_threshold"`
	// TrimMaxTokens is an absolute token count that triggers synthetic trimming when exceeded.
	// Takes priority over TrimThreshold — when set, percentage mode is not used.
	TrimMaxTokens int `yaml:"trim_max_tokens"`
	// KeepLastMessages is the number of recent messages preserved during compaction.
	KeepLastMessages int `yaml:"keep_last_messages"`
	// Agent is the name of the agent to use for compaction (empty = current provider).
	Agent string `yaml:"agent"`
	// Prompt overrides the compaction agent: use the current agent's model with this
	// named system prompt (from prompts/) instead of delegating to a dedicated agent.
	// When set, Agent is ignored. This is the "self-compact" signal.
	Prompt string `yaml:"prompt"`
	// ToolResultMaxLen is the max character length for tool results in the compaction transcript.
	ToolResultMaxLen int `yaml:"tool_result_max_length"`
	// TruncationRetries is the sequence of progressively lower tool result lengths tried
	// when compaction fails. The initial attempt uses ToolResultMaxLen; these are the retries.
	TruncationRetries []int `yaml:"truncation_retries"`
	// Chunks is the number of chunks to split the compactable history into.
	// 1 = single-pass (current behavior). >1 = sequential chunked compaction
	// where each chunk's summary feeds into the next.
	Chunks int `yaml:"chunks"`
	// Prune controls tool result pruning to keep context lean.
	Prune Prune `yaml:"prune"`
}

Compaction holds configuration for context compaction.

func (*Compaction) ApplyDefaults

func (c *Compaction) ApplyDefaults() error

ApplyDefaults sets sane defaults for zero-valued fields.

type Config

type Config struct {
	Providers StringCollection[Provider]
	// Systems contains all loaded system prompts.
	Systems Collection[System]
	// Modes contains all loaded operational modes.
	Modes Collection[Mode]
	// Agents contains all loaded agent configurations.
	Agents Collection[Agent]
	// AgentsMd contains all loaded AGENTS.md workspace instructions.
	AgentsMd AgentsMds
	// MCPs contains all loaded MCP server configurations.
	MCPs StringCollection[mcp.Server]
	// Features holds feature-level configuration (compaction, title, thinking).
	Features Features
	// Commands contains all loaded custom slash commands.
	Commands Collection[CustomCommand]
	// Skills contains all loaded LLM-invocable skill definitions.
	Skills Collection[Skill]
	// ToolDefs holds unified tool definitions loaded from .aura/config/tools/**/*.yaml.
	// Entries are text-only overrides for tool descriptions, usage, examples, and metadata (disabled, condition, parallel).
	ToolDefs ToolDefs
	// Hooks holds user-configurable shell hooks loaded from .aura/config/hooks/**/*.yaml.
	Hooks Hooks
	// LSPServers holds LSP server configurations loaded from .aura/config/lsp/**/*.yaml.
	LSPServers LSPServers
	// Tasks holds scheduled task definitions loaded from .aura/config/tasks/**/*.yaml.
	Tasks task.Tasks
	// Plugins holds plugin definitions loaded from .aura/plugins/*/plugin.yaml.
	Plugins StringCollection[Plugin]
	// ApprovalRules holds persisted bash approval patterns from config/rules/**/*.yaml.
	ApprovalRules ApprovalRules
}

Config holds loaded configuration from YAML files. Immutable after config.New() returns. Path context lives in Paths; CLI flags and computed state live in Runtime.

func (Config) BuildAgent

func (c Config) BuildAgent(agent, mode, system string, data TemplateData, paths Paths, rt *Runtime) (prompts.Prompt, Model, tool.Tools, tool.Tools, error)

BuildAgent assembles the prompt and tools for an agent with the specified mode and system prompt. Empty mode means no mode (no mode prompt or mode-specific tools). Empty system means use the agent's configured system prompt (or the default compositor if none). Callers are responsible for resolving defaults before calling this.

The data parameter provides template context (model metadata, agent/mode names) to all prompt templates. The system prompt acts as a compositor that controls the inclusion order of agent, files, workspace, and mode components via {{ template "X" . }} and {{ include .TemplateName $ }} directives.

func (Config) CollectEnabled

func (c Config) CollectEnabled(agent, mode string, rt *Runtime) []string

CollectEnabled gathers all enabled-tool patterns across global, agent, mode, and extra (task-level) filters. Used by opt-in filtering to decide which opt-in tools were explicitly requested.

func (Config) EffectiveRestrictions

func (c Config) EffectiveRestrictions() Restrictions

EffectiveRestrictions returns the merged sandbox restrictions from the already-merged features. All layers (global, agent, mode, task) are merged by rebuildState() before this is called.

func (Config) EffectiveToolPolicy

func (c Config) EffectiveToolPolicy(agent, mode string) ToolPolicy

EffectiveToolPolicy returns the merged tool policy for a given agent and mode. Combines agent-level and mode-level tool policies additively (union for auto, confirm, and deny), then merges persisted approval rules from config/rules/**/*.yaml.

func (Config) FilteredHooks

func (c Config) FilteredHooks(agent, mode string) Hooks

FilteredHooks returns hooks filtered by the agent's and mode's hook filter settings.

func (Config) GlobalFilter

func (c Config) GlobalFilter(rt *Runtime) (include, exclude []string)

GlobalFilter returns the resolved global include/exclude patterns. CLI flags (rt.IncludeTools/ExcludeTools) take precedence; config (Features.ToolExecution.Enabled/Disabled) is the fallback. When rt is nil, only config-level patterns are returned.

func (Config) MCPFilter

func (c Config) MCPFilter(rt *Runtime) (include, exclude []string)

MCPFilter returns the resolved global include/exclude patterns for MCP servers. CLI flags (rt.IncludeMCPs/ExcludeMCPs) take precedence; config (Features.MCP.Enabled/Disabled) is the fallback. When rt is nil, only config-level patterns are returned.

func (Config) ReadAutoload

func (c Config) ReadAutoload(path string, paths Paths) (string, error)

ReadAutoload reads a file path declared in agent frontmatter. Relative paths are resolved against the config home directory.

func (*Config) ResolveFeatures

func (c *Config) ResolveFeatures(globalFeatures Features, agentName, modeName string) (Features, error)

ResolveFeatures computes the effective features for a specific agent+mode by merging global features with agent and mode overrides. Same merge chain as rebuildState().

func (Config) Summary

func (c Config) Summary(homes []string) Summary

Summary builds a Summary from the loaded config for display by --print.

func (Config) Tools

func (c Config) Tools(agent, mode string, rt *Runtime) (tool.Tools, tool.Tools, error)

Tools returns the filtered tool set for the specified agent and mode combination, split into eager (included in request.Tools) and deferred (listed in system prompt index, loadable via LoadTools). When no tools are deferred, deferred is nil.

func (Config) ToolsWithTrace

func (c Config) ToolsWithTrace(agent, mode string, rt *Runtime) ([]ToolTrace, error)

ToolsWithTrace mirrors the Tools() filtering pipeline but captures the reason each tool was included or excluded at each stage.

func (Config) Validate

func (c Config) Validate(loaded map[Part]struct{}) error

Validate checks loaded config items for missing required fields and invalid values. Only parts present in the loaded set are validated.

func (Config) ValidateCrossRefs

func (c Config) ValidateCrossRefs(loaded map[Part]struct{}) error

ValidateCrossRefs checks that all name-based references between config entities resolve to existing entries. Only checks cross-refs where both source and target parts are loaded.

func (Config) ValidateFeatureCrossRefs

func (c Config) ValidateFeatureCrossRefs(owner string, f Features, loaded map[Part]struct{}) error

ValidateFeatureCrossRefs checks all agent/prompt name references within a Features struct. owner identifies the source for error messages: "" for global, agent name for agents, or 'task "name"' for tasks. Checks are gated on whether the target part is loaded.

type ConfigPaths

type ConfigPaths struct {
	Global  string // ~/.aura (always)
	Project string // write home (last --config entry)
	Source  string // per-file, the config home this agent was loaded from
}

ConfigPaths holds config directory paths for template consumption. Templates use {{ .Config.Global }}, {{ .Config.Project }}, {{ .Config.Source }}.

type CustomCommand

type CustomCommand struct {
	Metadata struct {
		Name        string `validate:"required"`
		Description string
		Hints       string // Argument hint text shown as ghost text in TUI (e.g. "<file> [options]").
	}
	Body string
}

CustomCommand represents a user-defined slash command loaded from a Markdown file.

func (CustomCommand) Name

func (c CustomCommand) Name() string

Name returns the command's identifier.

type DeferredToolIndex

type DeferredToolIndex struct {
	BuiltIn []string            // non-MCP tool names
	Servers map[string][]string // server name → short tool names
}

DeferredToolIndex groups deferred tools by source for system prompt rendering.

func NewDeferredToolIndex

func NewDeferredToolIndex(tools tool.Tools) DeferredToolIndex

NewDeferredToolIndex classifies deferred tools into built-in and per-server groups.

func (DeferredToolIndex) Render

func (d DeferredToolIndex) Render() string

Render returns a system prompt block listing all deferred tools. Returns empty string if the index is empty.

type Embeddings

type Embeddings struct {
	// Agent is the name of the agent to use for embedding.
	Agent string `yaml:"agent"`
	// MaxResults is the default number of results to return.
	MaxResults int `yaml:"max_results"`
	// Gitignore is additional gitignore patterns for file filtering.
	// Combined with .gitignore at project root if it exists.
	Gitignore string `yaml:"gitignore"`
	// Offload enables explicit model load/unload for the embedding model.
	// When true, the embed model is preloaded before indexing and unloaded after query embedding
	// to free VRAM for subsequent pipeline stages (e.g., reranking).
	Offload bool `yaml:"offload"`
	// Chunking holds chunking parameters.
	Chunking SemanticChunking `yaml:"chunking"`
	// Reranking holds reranking configuration.
	Reranking SemanticReranking `yaml:"reranking"`
}

Embeddings holds configuration for embedding-based search and reranking.

func (*Embeddings) ApplyDefaults

func (s *Embeddings) ApplyDefaults() error

ApplyDefaults sets sane defaults for zero-valued fields.

type Estimation

type Estimation struct {
	// Method selects the estimation algorithm: "rough", "tiktoken", "rough+tiktoken", "native".
	// "rough" = chars/divisor, "tiktoken" = tiktoken encoding, "rough+tiktoken" = max of both,
	// "native" = provider-specific tokenization (llamacpp /tokenize, ollama /api/generate).
	Method string `yaml:"method" validate:"omitempty,oneof=rough tiktoken rough+tiktoken native"`
	// Divisor is the chars-per-token divisor for rough estimation (default 4).
	Divisor int `yaml:"divisor"`
	// Encoding is the tiktoken encoding name (default "cl100k_base").
	Encoding string `yaml:"encoding"`
}

Estimation holds configuration for token estimation methods.

func (*Estimation) ApplyDefaults

func (e *Estimation) ApplyDefaults() error

ApplyDefaults sets sane defaults for zero-valued fields.

func (Estimation) NewEstimator

func (e Estimation) NewEstimator() (*tokens.Estimator, error)

NewEstimator creates a cached Estimator from this configuration.

type Features

type Features struct {
	Compaction    Compaction     `yaml:"compaction"`
	Title         Title          `yaml:"title"`
	Thinking      Thinking       `yaml:"thinking"`
	Vision        Vision         `yaml:"vision"`
	Embeddings    Embeddings     `yaml:"embeddings"`
	ToolExecution ToolExecution  `yaml:"tools"`
	STT           STT            `yaml:"stt"`
	TTS           TTS            `yaml:"tts"`
	Sandbox       SandboxFeature `yaml:"sandbox"`
	Subagent      Subagent       `yaml:"subagent"`
	PluginConfig  PluginConfig   `yaml:"plugins"`
	MCP           MCPFeature     `yaml:"mcp"`
	Estimation    Estimation     `yaml:"estimation"`
	Guardrail     Guardrail      `yaml:"guardrail"`
}

Features holds all feature-level configuration, loaded from .aura/config/features/*.yaml. Each YAML file uses a top-level key matching a feature name (compaction, title, thinking, vision, tools). YAML tags match the keys used in feature files and agent frontmatter overrides.

func (*Features) DecodeKey

func (f *Features) DecodeKey(key string, node *yaml.Node) error

DecodeKey dispatches a YAML node to the correct struct field based on the top-level key.

func (*Features) Load

func (f *Features) Load(ff files.Files) error

Load populates Features from YAML files. Each file may contain one or more top-level keys that dispatch to the corresponding struct field.

func (*Features) MergeFrom

func (f *Features) MergeFrom(overlay Features) error

MergeFrom applies non-zero fields from overlay on top of the receiver. Zero-valued overlay fields fall through to the receiver's existing value. Pointer fields (e.g. *int in BashTruncation) use nil = no override.

func (Features) SummaryDisplay

func (f Features) SummaryDisplay() string

SummaryDisplay renders a one-line-per-feature summary for the --print output.

type FileEntry

type FileEntry struct {
	Name         string // display name (e.g., "docs/rules.txt")
	TemplateName string // registered template name (e.g., "file:docs/rules.txt")
}

FileEntry represents an autoloaded file registered as a named template. Used in composition: {{ range .Files }}{{ include .TemplateName $ }}{{ end }}.

type Files

type Files struct {
	Providers files.Files
	Modes     files.Files
	Agents    files.Files
	Prompts   files.Files
	AgentsMd  files.Files
	MCP       files.Files
	Features  files.Files
	Commands  files.Files
	Skills    files.Files
	Tools     files.Files
	Hooks     files.Files
	Tasks     files.Files
	LSP       files.Files
	Plugins   files.Files
	Rules     files.Files
}

Files holds the different configuration files used by Aura.

func (*Files) Load

func (fs *Files) Load(cwd, launchDir string, homes ...string) error

Load discovers and loads all configuration files from the specified directories. Multiple homes are processed in order (e.g. global then project); later entries override earlier ones via name-based dedup in each type's Load method. Files with ".example." in their basename are excluded — they serve as reference documentation only.

type Guardrail

type Guardrail struct {
	// Mode controls what happens when the guardrail flags something.
	//   "block" — reject the tool call / message
	//   "log"   — show info note inline, proceed normally
	// Empty string = disabled (no guardrail checks run). Default.
	Mode string `yaml:"mode" validate:"omitempty,oneof=block log"`
	// OnError controls what happens when the guardrail check itself fails
	// (timeout, network error, model unavailable — after retries).
	//   "block" — fail-closed: block the content (default for mode=block)
	//   "allow" — fail-open: proceed without guardrail check (default for mode=log)
	// Decoupled from Mode so users can have mode=block + on_error=allow.
	OnError string `yaml:"on_error" validate:"omitempty,oneof=block allow"`
	// Timeout is the max duration for a single guardrail check.
	// If exceeded, the check is treated as if the guardrail model is unavailable.
	Timeout time.Duration `yaml:"timeout"`
	// Scope controls which message types are sent to the guardrail model.
	// Each scope has its own agent/prompt — a scope is active when agent or prompt is set.
	Scope GuardrailScope `yaml:"scope"`
	// Tools filters which tools trigger guardrail checks (for tool_calls scope).
	// Same enabled/disabled glob syntax as tools feature config.
	Tools GuardrailTools `yaml:"tools"`
}

Guardrail holds configuration for the guardrail feature — a secondary LLM that validates tool calls and user input against a policy prompt. Each scope (tool_calls, user_messages) has its own agent/prompt fields.

func (*Guardrail) ApplyDefaults

func (g *Guardrail) ApplyDefaults() error

ApplyDefaults sets sane defaults for zero-valued fields.

func (Guardrail) Enabled

func (g Guardrail) Enabled() bool

Enabled reports whether guardrail checks are active.

type GuardrailScope

type GuardrailScope struct {
	// ToolCalls checks assistant-generated tool calls before execution.
	ToolCalls GuardrailScopeEntry `yaml:"tool_calls"`
	// UserMessages checks user input before it enters conversation.
	UserMessages GuardrailScopeEntry `yaml:"user_messages"`
}

GuardrailScope controls which message types are sent to the guardrail model.

type GuardrailScopeEntry

type GuardrailScopeEntry struct {
	// Agent is the dedicated guardrail agent name for this scope.
	Agent string `yaml:"agent"`
	// Prompt is a named system prompt (from prompts/). When set, uses the
	// current agent's provider/model with this prompt instead of a dedicated
	// agent. Overrides Agent (same semantics as compaction.prompt).
	Prompt string `yaml:"prompt"`
}

GuardrailScopeEntry configures a single guardrail scope with its own agent/prompt.

func (GuardrailScopeEntry) Active

func (e GuardrailScopeEntry) Active() bool

Active reports whether this scope entry is configured (has agent or prompt).

type GuardrailTools

type GuardrailTools struct {
	// Enabled is a list of glob patterns. Only matching tools are checked.
	// Empty = all tools checked.
	Enabled []string `yaml:"enabled"`
	// Disabled is a list of glob patterns. Matching tools are skipped.
	// Applied after Enabled.
	Disabled []string `yaml:"disabled"`
}

GuardrailTools filters which tools trigger guardrail checks.

type Hook

type Hook struct {
	// Event is the hook timing: "pre" (before Execute) or "post" (after Execute).
	Event string `yaml:"event" validate:"required,oneof=pre post"`
	// Matcher is a regex matched against the tool name. Empty = match all tools.
	Matcher string `yaml:"matcher"`
	// Files is a glob pattern matched against file basenames (e.g. "*.go", "*.py").
	// When set, the hook only runs if at least one file path in the tool input matches.
	Files string `yaml:"files"`
	// Command is the shell command executed via sh -c. Receives JSON context on stdin.
	// $FILE env var is set to matched file paths (space-separated).
	Command string `yaml:"command" validate:"required"`
	// Timeout is the max seconds before the hook process is killed. nil = default (10s).
	Timeout *int `yaml:"timeout"`
	// Depends lists hook names that must run before this hook (within the same event).
	Depends []string `yaml:"depends"`
	// Silent suppresses all output and exit codes. The hook runs but never produces messages or blocks.
	Silent *bool `yaml:"silent"`
	// Disabled skips this hook entirely. It still appears in /hooks display but never executes.
	Disabled *bool `yaml:"disabled"`
	// Inherit lists parent hook names for config inheritance.
	Inherit []string `yaml:"inherit"`
}

Hook defines a user-configurable shell hook that runs before or after a tool call. Loaded from .aura/config/hooks/**/*.yaml. The map key is the hook name.

func (Hook) IsDisabled

func (h Hook) IsDisabled() bool

IsDisabled returns true if the hook is explicitly disabled.

func (Hook) IsEnabled

func (h Hook) IsEnabled() bool

IsEnabled returns true if the hook is active (not explicitly disabled).

func (Hook) IsSilent

func (h Hook) IsSilent() bool

IsSilent returns true if the hook suppresses all output.

func (Hook) TimeoutSeconds

func (h Hook) TimeoutSeconds() int

TimeoutSeconds returns the configured timeout in seconds, or 0 if not set.

type HookFilter

type HookFilter struct {
	// Enabled is the list of hook name patterns to include.
	Enabled []string `yaml:"enabled"`
	// Disabled is the list of hook name patterns to exclude.
	Disabled []string `yaml:"disabled"`
}

HookFilter controls which hooks are active for an agent or mode.

type Hooks

type Hooks map[string]Hook

Hooks maps hook names to their definitions.

func (Hooks) Display

func (h Hooks) Display(pre, post []string) string

Display formats hooks grouped by event in execution order. Pre/post name lists must already be topologically sorted (from hooks.Order) and contain only enabled hooks. Disabled hooks are shown separately at the end.

func (Hooks) Filtered

func (h Hooks) Filtered(include, exclude []string) Hooks

Filtered returns hooks matching the include/exclude patterns. Patterns support '*' wildcards (same as tool filtering). After name filtering, hooks with unsatisfied dependencies are cascade-pruned because dag.Build() hard-errors on undefined parents.

func (*Hooks) Load

func (h *Hooks) Load(ff files.Files) error

Load reads YAML files and merges all hook definitions into the map. Each file contains a map of hook names to their definitions. Multiple hooks can live in one file, or each hook in its own file — the loader is decoupled from filenames. Supports config inheritance via the `inherit` field within hook definitions.

type LSPServers

type LSPServers map[string]lsp.Server

LSPServers maps server names to their LSP server configurations. Loaded from .aura/config/lsp/**/*.yaml.

func (*LSPServers) Load

func (s *LSPServers) Load(ff files.Files) error

Load reads YAML files and merges all LSP server definitions into the map. Each file contains a map of server names to their definitions. Multiple servers can live in one file, or each server in its own file — the loader is decoupled from filenames.

type MCPFeature

type MCPFeature struct {
	// Enabled is the default for --include-mcps. Glob patterns for servers to connect.
	// Empty = connect all enabled servers. CLI --include-mcps overrides this.
	Enabled []string `yaml:"enabled"`
	// Disabled is the default for --exclude-mcps. Glob patterns for servers to skip.
	// Empty = skip none. CLI --exclude-mcps overrides this.
	Disabled []string `yaml:"disabled"`
}

MCPFeature holds feature-level settings for MCP server filtering.

func (*MCPFeature) ApplyDefaults

func (m *MCPFeature) ApplyDefaults() error

ApplyDefaults is a no-op — MCPFeature has no default values.

type MemoriesData

type MemoriesData struct {
	Local  string // concatenated .aura/memory/*.md contents
	Global string // concatenated ~/.aura/memory/*.md contents
}

MemoriesData holds concatenated memory file contents for template consumption. Templates use {{ .Memories.Local }} and {{ .Memories.Global }}.

func NewMemoriesData

func NewMemoriesData(home, globalHome string) (MemoriesData, error)

NewMemoriesData reads all *.md files from local and global memory directories and concatenates their contents with "---" separators. Missing directories produce empty strings. Unreadable files return an error.

type Mode

type Mode struct {
	// Metadata contains mode configuration details.
	Metadata ModeMetadata
	// Prompt is the mode's prompt template.
	Prompt prompts.Prompt
}

Mode represents an operational mode with associated tools and prompt.

func (Mode) Name

func (m Mode) Name() string

Name returns the mode's unique identifier.

func (Mode) Visible

func (m Mode) Visible() bool

Visible reports whether the mode is included in UI listing and cycling.

type ModeData

type ModeData struct {
	Name string
}

ModeData holds the active mode metadata for template consumption. Templates use {{ .Mode.Name }} instead of the former {{ .Mode }}.

type ModeMetadata

type ModeMetadata struct {
	// Name is the unique identifier for the mode.
	Name string `validate:"required"`
	// Description explains the mode's purpose.
	Description string
	// Hide excludes this mode from UI listing and cycling.
	Hide *bool
	// Tools defines tool availability for this mode.
	Tools Tools
	// Hooks controls which hooks are active for this mode.
	Hooks HookFilter
	// Features holds per-mode feature overrides. Non-zero values are merged
	// on top of agent features at mode resolution time.
	Features Features
	// Inherit lists parent mode names for config inheritance.
	Inherit []string `yaml:"inherit"`
}

ModeMetadata holds the YAML-decoded configuration for a mode.

func (ModeMetadata) IsHidden

func (m ModeMetadata) IsHidden() bool

IsHidden returns true if the mode is excluded from UI listing.

type Model

type Model struct {
	// Name is the model identifier.
	Name string `validate:"required"`
	// Provider is the name of the provider hosting the model.
	Provider string `validate:"required"`
	// Think configures extended thinking mode (zero value=off, bool, or "low"/"medium"/"high").
	Think thinking.Value
	// Context is the maximum context window size.
	Context int
	// Generation holds optional sampling, output, and thinking budget parameters.
	Generation *generation.Generation
}

Model represents the configuration for an AI model.

type ModelData

type ModelData struct {
	Name            string
	Family          string
	ParameterCount  int64  // raw value for comparisons: {{ if lt .Model.ParameterCount 10000000000 }}
	ParameterSize   string // display string: "8B", "70B", "1.5B"
	ContextLength   int
	Thinking        bool
	ThinkingLevels  bool
	Tools           bool
	Vision          bool
	Embedding       bool
	Reranking       bool
	ContextOverride bool
}

ModelData holds flattened model metadata for template consumption. Capabilities are exposed as booleans for easy conditional use in templates.

func NewModelData

func NewModelData(m model.Model) ModelData

NewModelData converts a resolved model.Model into template-friendly ModelData.

type ModelFilter

type ModelFilter struct {
	Include []string `yaml:"include"`
	Exclude []string `yaml:"exclude"`
}

ModelFilter controls which models appear in visual listings (aura models, /model).

func (ModelFilter) Apply

func (f ModelFilter) Apply(models model.Models) model.Models

Apply filters models using Include then Exclude with wildcard glob matching.

type Namer

type Namer interface {
	Name() string
}

Namer is satisfied by config entities that have a display name.

type Options

type Options struct {
	Homes          []string          // all config dirs in merge order (global first, then --config entries)
	WriteHome      string            // primary home for writes (sessions, debug, auth, plugins)
	GlobalHome     string            // ~/.aura — kept for approval provenance + global auth dir
	LaunchDir      string            // CWD at process start, before --workdir
	WorkDir        string            // CWD after --workdir processing
	WithPlugins    bool              // load plugin definitions
	UnsafePlugins  bool              // enable os/exec in plugins (--unsafe-plugins)
	SetVars        map[string]string // --set template variables for task metadata expansion
	ExtraTaskFiles []string          // additional task file glob patterns (from tasks --files)
	CLI            CLIOverrides
}

Options bundles the parameters for New().

type Part

type Part string

Part identifies a loadable section of the configuration. Callers pass parts to New() to declare exactly what they need.

const (
	PartModes         Part = "modes"
	PartAgents        Part = "agents"
	PartSystems       Part = "systems"
	PartAgentsMd      Part = "agents-md"
	PartProviders     Part = "providers"
	PartMCPs          Part = "mcps"
	PartFeatures      Part = "features"
	PartCommands      Part = "commands"
	PartSkills        Part = "skills"
	PartToolDefs      Part = "tool-defs"
	PartHooks         Part = "hooks"
	PartLSP           Part = "lsp"
	PartTasks         Part = "tasks"
	PartPlugins       Part = "plugins"
	PartApprovalRules Part = "approval-rules"
)

func AllParts

func AllParts() []Part

AllParts returns all config parts in load order.

type Paths

type Paths struct {
	// Home is the config directory path (e.g. ".aura" or "/home/user/.aura").
	Home string
	// Global is the global config directory (~/.aura).
	Global string
	// Launch is the CWD at process start, before os.Chdir(--workdir).
	Launch string
	// Work is the effective working directory after os.Chdir(--workdir).
	Work string
}

Paths holds filesystem context for config resolution and tool execution. Immutable after construction (the assistant uses a taskWorkDir override separately).

type Plugin

type Plugin struct {
	Description string         `yaml:"description"`
	Condition   string         `yaml:"condition"`
	Disabled    *bool          `yaml:"disabled"`
	Once        bool           `yaml:"once"`
	Override    bool           `yaml:"override"` // replace a built-in tool with the same name
	OptIn       bool           `yaml:"opt_in"`   // tool is hidden unless explicitly enabled by name
	Env         []string       `yaml:"env"`      // env var names this plugin may read (["*"] = all)
	Config      map[string]any `yaml:"config"`   // default config values shipped with the plugin

	Name      string         `yaml:"name"` // optional; defaults to directory name in Load()
	Source    string         `yaml:"-"`    // plugin.yaml file path
	Origin    gitutil.Origin `yaml:"-"`    // loaded from .origin.yaml sidecar
	OriginDir string         `yaml:"-"`    // directory where .origin.yaml lives (may differ from Dir() for packs)
}

Plugin is a user-defined plugin loaded from .aura/plugins/<name>/plugin.yaml.

func ByPack

func ByPack(pp StringCollection[Plugin], packName string) []Plugin

ByPack returns all plugins whose OriginDir base name matches the given pack name, sorted by plugin name.

func (Plugin) Dir

func (p Plugin) Dir() string

Dir returns the directory containing the plugin .go files.

func (Plugin) Display

func (p Plugin) Display(hooks []string, toolName, commandName string) string

Display returns a one-line summary for listing. Capabilities are provided externally because discovery requires a Yaegi interpreter.

func (Plugin) HasOrigin

func (p Plugin) HasOrigin() bool

HasOrigin returns true if the plugin was installed from a git source.

func (Plugin) IsEnabled

func (p Plugin) IsEnabled() bool

IsEnabled returns whether the plugin is active. Default is true (nil Disabled = enabled).

func (Plugin) IsPack

func (p Plugin) IsPack() bool

IsPack returns true if the plugin is part of a multi-plugin pack (OriginDir != Dir()).

func (Plugin) PackName

func (p Plugin) PackName() string

PackName returns the pack directory name, or empty string if not a pack member.

type PluginConfig

type PluginConfig struct {
	// Dir overrides the plugin discovery directory for a config home.
	// Relative paths resolve against the home that declares them.
	// Empty = default "plugins/" subdirectory.
	// NOTE: This field exists so the YAML parser accepts it, but plugin
	// discovery uses ResolvePluginDir (peek) because it runs before feature merge.
	Dir string `yaml:"dir"`
	// Unsafe allows plugins to use os/exec and other restricted imports.
	// When false (default), plugins that import os/exec fail at load time.
	Unsafe bool `yaml:"unsafe"`
	// Include filters plugins by name. Empty = load all enabled plugins.
	Include []string `yaml:"include"`
	// Exclude filters plugins by name. Applied after Include.
	Exclude []string `yaml:"exclude"`
	// Config holds plugin config values. Global values are sent to all plugins;
	// Local values are keyed by plugin name and override Global.
	Config struct {
		Global map[string]any            `yaml:"global"`
		Local  map[string]map[string]any `yaml:"local"`
	} `yaml:"config"`
}

PluginConfig holds feature-level settings for the plugin system.

func (*PluginConfig) ApplyDefaults

func (p *PluginConfig) ApplyDefaults() error

ApplyDefaults is a no-op — PluginConfig has no default values.

type PolicyAction

type PolicyAction int

PolicyAction is the result of evaluating a tool call against a policy.

const (
	// PolicyAuto means the tool call runs without user confirmation.
	PolicyAuto PolicyAction = iota
	// PolicyConfirm means the tool call requires user approval before execution.
	PolicyConfirm
	// PolicyDeny means the tool call is blocked.
	PolicyDeny
)

type Provider

type Provider struct {
	// URL is the API endpoint for the provider. Optional for providers with default endpoints (e.g., Anthropic).
	URL string
	// Type is the provider type (e.g., ollama, llamacpp, openrouter, openai, anthropic).
	Type string `validate:"required,oneof=ollama llamacpp openrouter openai anthropic google copilot codex"`
	// Token is the authentication token for API access.
	Token string
	// Models controls which models appear in visual listings.
	Models ModelFilter `yaml:"models"`
	// KeepAlive controls how long models stay loaded in VRAM after a request (Ollama only).
	// Uses Go duration syntax: "5m", "1h", "30s". Empty means provider default.
	KeepAlive string `yaml:"keep_alive"`
	// Timeout is the HTTP response header timeout for provider calls.
	// Uses Go duration syntax: "5m", "30s". Limits time waiting for response headers
	// without affecting long-running streaming responses.
	Timeout string `yaml:"timeout"`
	// Retry configures exponential-backoff retry for transient Chat() failures.
	// Disabled by default (MaxAttempts: 0). Only meaningful for cloud providers.
	Retry Retry `yaml:"retry"`
	// Capabilities declares what this provider supports (chat, embed, rerank, transcribe, synthesize).
	// Empty means all capabilities. Chat implies model listing.
	Capabilities []Capability `yaml:"capabilities"`
	// Source is the file path this provider was loaded from. Set by Load(), not from YAML.
	Source string `yaml:"-"`
	// AuthDirs is the ordered list of directories to search for stored auth tokens.
	// Populated by config.New(), not from YAML. Order: project auth dir, then global auth dir.
	AuthDirs []string `yaml:"-"`
}

Provider represents the configuration for an AI model provider.

func (*Provider) ApplyDefaults

func (p *Provider) ApplyDefaults() error

ApplyDefaults sets sane defaults for zero-valued fields.

func (Provider) Can

func (p Provider) Can(cap Capability) bool

Can returns true if the provider supports the given capability. When Capabilities is empty, all capabilities are assumed.

type Prune

type Prune struct {
	// Mode controls when pruning runs: "off", "iteration", "compaction".
	Mode PruneMode `yaml:"mode" validate:"omitempty,oneof=off iteration compaction"`
	// ProtectPercent is the percentage of the main model's context to protect
	// from pruning (most recent messages).
	ProtectPercent float64 `yaml:"protect_percent"`
	// ArgThreshold is the minimum estimated token count for a tool call's
	// arguments to be eligible for pruning.
	ArgThreshold int `yaml:"arg_threshold"`
}

Prune holds configuration for tool result pruning.

func (*Prune) ApplyDefaults

func (p *Prune) ApplyDefaults() error

ApplyDefaults sets sane defaults for zero-valued prune fields.

type PruneMode

type PruneMode string

PruneMode controls when tool result pruning runs.

const (
	PruneModeOff        PruneMode = "off"
	PruneModeIteration  PruneMode = "iteration"
	PruneModeCompaction PruneMode = "compaction"
)

func (PruneMode) AtCompaction

func (m PruneMode) AtCompaction() bool

AtCompaction reports whether pruning should run during compaction.

func (PruneMode) AtIteration

func (m PruneMode) AtIteration() bool

AtIteration reports whether pruning should run after each loop iteration.

type ReadBeforeConfig

type ReadBeforeConfig struct {
	Write  *bool `yaml:"write"`  // nil = default (true)
	Delete *bool `yaml:"delete"` // nil = default (false)
}

ReadBeforeConfig holds YAML-level read-before policy settings. Uses *bool so nil = inherit default via mergo merge chain.

func (ReadBeforeConfig) ToPolicy

func (r ReadBeforeConfig) ToPolicy() tool.ReadBeforePolicy

ToPolicy converts the config to a resolved ReadBeforePolicy, applying defaults for nil fields.

type ReadBeforeData

type ReadBeforeData struct {
	Write  bool // must read before writing/patching
	Delete bool // must read before deleting
}

ReadBeforeData holds read-before-write policy for template consumption. Templates can use {{ .ReadBefore.Write }}, {{ .ReadBefore.Delete }}.

type Restrictions

type Restrictions struct {
	ReadOnly  []string `mapstructure:"ro" yaml:"ro"`
	ReadWrite []string `mapstructure:"rw" yaml:"rw"`
}

Restrictions defines filesystem access restrictions for sandboxed execution.

type Retry

type Retry struct {
	// MaxAttempts is the number of retry attempts before giving up. 0 = disabled.
	MaxAttempts int `yaml:"max_attempts"`
	// BaseDelay is the initial delay between retries (Go duration). Default "1s".
	BaseDelay string `yaml:"base_delay"`
	// MaxDelay is the maximum delay between retries (Go duration). Default "30s".
	MaxDelay string `yaml:"max_delay"`
}

Retry configures exponential-backoff retry for transient Chat() failures. Zero value (MaxAttempts: 0) means retry is disabled.

type Runtime

type Runtime struct {

	// WithPlugins indicates whether user-defined Go plugins are enabled.
	WithPlugins bool
	// UnsafePlugins enables os/exec access for plugins (CLI --unsafe-plugins).
	UnsafePlugins bool
	// DisplayProviders holds CLI --providers filter for model listings.
	DisplayProviders []string
	// IncludeTools holds CLI --include-tools glob patterns.
	IncludeTools []string
	// ExcludeTools holds CLI --exclude-tools glob patterns.
	ExcludeTools []string
	// IncludeMCPs holds CLI --include-mcps glob patterns for MCP server filtering.
	IncludeMCPs []string
	// ExcludeMCPs holds CLI --exclude-mcps glob patterns for MCP server filtering.
	ExcludeMCPs []string

	// AllTools is the complete tool set including runtime-dependent tools (todo, vision, query).
	AllTools tool.Tools
	// ExtraFilter holds an additional runtime tool filter (e.g. task-level overrides).
	ExtraFilter *tool.Filter
	// OptInTools lists tool names that are hidden unless explicitly enabled by name or narrow glob.
	OptInTools []string
	// LoadedTools tracks tools loaded via LoadTools this session. Deferred tools
	// in this set stay eager on subsequent rebuilds.
	LoadedTools map[string]bool
	// ConditionState holds the current runtime state for evaluating tool/MCP conditions.
	// Nil means "skip all condition checks" (e.g. `aura tools` CLI, startup before model resolution).
	ConditionState *condition.State
}

Runtime holds CLI flags and computed state. Mutable throughout the session. CLI flag fields are set once at startup and preserved across config reloads. Computed fields are set/updated by the assistant layer (rebuildState).

type STT

type STT struct {
	// Agent is the name of the agent to use for transcription calls.
	Agent string `yaml:"agent"`
	// Language is the default ISO-639-1 language hint (e.g. "en"). Empty = auto-detect.
	Language string `yaml:"language"`
}

STT holds configuration for speech-to-text (transcription).

func (*STT) ApplyDefaults

func (s *STT) ApplyDefaults() error

ApplyDefaults is a no-op — STT has no default values.

type SandboxData

type SandboxData struct {
	Enabled   bool // Landlock actually enforcing (available AND requested)
	Requested bool // User wants sandbox (config or runtime toggle, independent of kernel)
	ReadOnly  []string
	ReadWrite []string
	Display   string // Pre-rendered restriction text for prompt injection
}

SandboxData holds sandbox metadata for template consumption. Templates can use {{ .Sandbox.Enabled }}, {{ .Sandbox.Requested }}, {{ .Sandbox.Display }}, etc.

func NewSandboxData

func NewSandboxData(enabled, requested bool, r Restrictions, display string) SandboxData

NewSandboxData creates template-friendly SandboxData from sandbox state and merged restrictions.

type SandboxFeature

type SandboxFeature struct {
	Enabled      *bool        `yaml:"enabled"`      // nil = inherit, &true = enable, &false = disable
	Restrictions Restrictions `yaml:"restrictions"` // base paths (override semantics via mergo)
	Extra        Restrictions `yaml:"extra"`        // additional paths (override semantics, concatenated at read time)
}

SandboxFeature holds sandbox configuration, loaded as part of Features.

func (*SandboxFeature) ApplyDefaults

func (s *SandboxFeature) ApplyDefaults() error

ApplyDefaults is a no-op — SandboxFeature has no default values.

func (SandboxFeature) EffectiveRestrictions

func (s SandboxFeature) EffectiveRestrictions() Restrictions

EffectiveRestrictions returns the merged restrictions by concatenating base Restrictions with Extra. Both fields individually follow override semantics via mergo; the concatenation happens here at resolution time.

func (SandboxFeature) IsEnabled

func (s SandboxFeature) IsEnabled() bool

IsEnabled returns true if the sandbox is explicitly enabled.

type SemanticChunking

type SemanticChunking struct {
	// Strategy is the chunking strategy to use.
	Strategy string `yaml:"strategy" validate:"omitempty,oneof=auto ast line"`
	// MaxTokens is the target max tokens per chunk.
	MaxTokens int `yaml:"max_tokens"`
	// OverlapTokens is the overlap tokens between adjacent chunks.
	OverlapTokens int `yaml:"overlap_tokens"`
}

SemanticChunking holds chunking parameters for embedding-based search.

func (SemanticChunking) ChunkerConfig

func (c SemanticChunking) ChunkerConfig(estimate func(string) int) chunker.Config

ChunkerConfig converts the YAML-sourced chunking settings into the typed chunker.Config.

type SemanticReranking

type SemanticReranking struct {
	// Agent is the name of the agent to use for reranking (empty = skip reranking).
	Agent string `yaml:"agent"`
	// Multiplier controls how many extra candidates to fetch for reranking.
	Multiplier int `yaml:"multiplier"`
	// Offload enables explicit model load/unload for the reranker model.
	// When true, the reranker model is loaded before reranking and unloaded after
	// to free VRAM.
	Offload bool `yaml:"offload"`
}

SemanticReranking holds reranking configuration for embedding-based search.

type Skill

type Skill struct {
	Metadata struct {
		Name        string `validate:"required"`
		Description string `validate:"required"`
	}
	Body string
}

Skill represents a user-defined LLM-invocable capability loaded from a Markdown file. Skills are invoked by the LLM via the Skill meta-tool. The description is visible in the tool schema for progressive disclosure; the full body is returned on invocation.

func (Skill) Display

func (s Skill) Display() string

Display returns a one-line summary for listing.

func (Skill) Name

func (s Skill) Name() string

Name returns the skill's identifier.

type StringCollection

type StringCollection[T any] map[string]T

StringCollection is a string-keyed collection of config entities. Used for Providers, MCPs, Plugins. Keys are lowercase-normalized at load time.

func FilterMCPs

func FilterMCPs(mcps StringCollection[mcp.Server], include, exclude []string) StringCollection[mcp.Server]

FilterMCPs returns a subset of servers matching the include/exclude glob patterns. Exclude takes precedence over include. Empty include = all pass.

func (StringCollection[T]) Apply

func (c StringCollection[T]) Apply(fn func(*T))

Apply calls fn on each entity, writing the result back (mutates in-place).

func (StringCollection[T]) Filter

func (c StringCollection[T]) Filter(fn func(string, T) bool) StringCollection[T]

Filter returns a new collection containing only entries matching the predicate. The predicate receives both the key and the value.

func (StringCollection[T]) Get

func (c StringCollection[T]) Get(name string) *T

Get retrieves an entity by name (case-insensitive O(1) lookup), returning nil if not found.

func (StringCollection[T]) Names

func (c StringCollection[T]) Names() []string

Names returns a sorted list of all entity keys.

func (StringCollection[T]) RemoveIf

func (c StringCollection[T]) RemoveIf(fn func(string, T) bool)

RemoveIf deletes all entries matching the predicate (mutates in-place).

func (StringCollection[T]) Values

func (c StringCollection[T]) Values() []T

Values returns all entities sorted by key.

type Subagent

type Subagent struct {
	// MaxSteps caps the total number of LLM round-trips per subagent run.
	MaxSteps int `yaml:"max_steps"`
	// DefaultAgent is the agent name used when no agent is specified in the Task tool call.
	DefaultAgent string `yaml:"default_agent"`
}

Subagent holds configuration for the subagent (Task tool) system.

func (*Subagent) ApplyDefaults

func (s *Subagent) ApplyDefaults() error

ApplyDefaults sets sane defaults for zero-valued fields.

type Summary

type Summary struct {
	Homes      []string
	Sections   []SummarySection
	Features   Features
	LSPServers LSPServers
}

Summary holds all the display data for a structured config overview.

func (Summary) Display

func (s Summary) Display() string

Display renders the summary as a human-readable string.

func (Summary) LSPDisplay

func (s Summary) LSPDisplay() string

LSPDisplay renders the LSP servers summary line.

type SummaryEntry

type SummaryEntry struct {
	Name   string
	Source string
	Detail string
}

SummaryEntry represents a single named config item with its source file and optional detail.

type SummarySection

type SummarySection struct {
	Label   string
	Entries []SummaryEntry
}

SummarySection groups config entries of the same type under a label.

type System

type System struct {
	// Metadata contains system prompt configuration details.
	Metadata SystemMetadata
	// Prompt is the system prompt template.
	Prompt prompts.Prompt
}

System represents a system prompt configuration.

func (System) Name

func (s System) Name() string

Name returns the system prompt's identifier.

type SystemMetadata

type SystemMetadata struct {
	// Name is the unique identifier for the system prompt.
	Name string `validate:"required"`
	// Description explains the system prompt's purpose.
	Description string
	// Inherit lists parent prompt names whose bodies are prepended to this prompt.
	Inherit []string `yaml:"inherit"`
}

SystemMetadata holds the YAML-decoded configuration for a system prompt.

type TTS

type TTS struct {
	// Agent is the name of the agent to use for synthesis calls.
	Agent string `yaml:"agent"`
	// Voice is the default voice identifier (e.g. "alloy", "af_heart").
	Voice string `yaml:"voice"`
	// Format is the default output audio format (e.g. "mp3", "wav").
	Format string `yaml:"format"`
	// Speed is the default playback speed (0.25-4.0). Default: 1.0.
	Speed float64 `yaml:"speed"`
}

TTS holds configuration for text-to-speech (synthesis).

func (*TTS) ApplyDefaults

func (t *TTS) ApplyDefaults() error

ApplyDefaults sets sane defaults for zero-valued fields.

type TemplateData

type TemplateData struct {
	Config     ConfigPaths
	LaunchDir  string // CWD at process start, before --workdir
	WorkDir    string // CWD after --workdir processing
	Model      ModelData
	Provider   string
	Agent      string
	Mode       ModeData
	Tools      ToolsData        // eager + deferred tool info, filled by BuildAgent
	Vars       map[string]any   // user-defined --set template variables
	Sandbox    SandboxData      // sandbox state, filled by BuildAgent before all template rendering
	ReadBefore ReadBeforeData   // read-before-write policy, filled by BuildAgent
	ToolPolicy ToolPolicyData   // tool policy, filled by BuildAgent
	Memories   MemoriesData     // concatenated memory file contents, filled by BuildAgent
	Files      []FileEntry      // autoloaded file entries for composition
	Workspace  []WorkspaceEntry // workspace (AGENTS.md) entries for composition
}

TemplateData is the context passed to all prompt templates during rendering. Templates access fields via Go template syntax, e.g., {{ .Model.Name }}, {{ .Tools.Eager }}. Model.Name is always set from agent config. Capability fields (Family, Thinking, Vision, etc.) are zero until runtime model resolution via the provider.

type Thinking

type Thinking struct {
	// Agent is the name of the agent to use for thinking rewrite (empty = current provider).
	Agent string `yaml:"agent"`
	// Prompt overrides the thinking agent: use the current agent's model with this
	// named system prompt (from prompts/) instead of delegating to a dedicated agent.
	// When set, Agent is ignored. This is the "self-rewrite" signal.
	Prompt string `yaml:"prompt"`
	// KeepLast is the number of recent messages whose thinking is preserved unchanged.
	KeepLast int `yaml:"keep_last"`
	// TokenThreshold is the minimum token count for a thinking block to be stripped or rewritten.
	TokenThreshold int `yaml:"token_threshold"`
}

Thinking holds configuration for thinking block management (strip and rewrite modes).

func (*Thinking) ApplyDefaults

func (t *Thinking) ApplyDefaults() error

ApplyDefaults sets sane defaults for zero-valued fields.

type Title

type Title struct {
	// Disabled skips LLM title generation and uses the first user message instead.
	Disabled *bool `yaml:"disabled"`
	// Agent is the name of the agent to use for title generation.
	// If empty and not disabled, falls back to the current conversation's provider/model.
	Agent string `yaml:"agent"`
	// Prompt overrides the title agent: use the current agent's model with this
	// named system prompt (from prompts/) instead of delegating to a dedicated agent.
	// When set, Agent is ignored.
	Prompt string `yaml:"prompt"`
	// MaxLength is the maximum character length for generated titles.
	MaxLength int `yaml:"max_length"`
}

Title holds configuration for session title generation.

func (*Title) ApplyDefaults

func (t *Title) ApplyDefaults() error

ApplyDefaults sets sane defaults for zero-valued fields.

func (Title) IsDisabled

func (t Title) IsDisabled() bool

IsDisabled returns true if LLM title generation is explicitly disabled.

func (Title) IsEnabled

func (t Title) IsEnabled() bool

IsEnabled returns true if LLM title generation is active (not explicitly disabled).

type ToolBash

type ToolBash struct {
	// Truncation controls middle-truncation of Bash tool output.
	Truncation BashTruncation `yaml:"truncation"`
	// Rewrite is a Go text/template applied to every Bash tool command before execution.
	// Template receives {{ .Command }} (the original command) and sprig functions.
	// Empty = no rewrite. Example: "rtk {{ .Command }}"
	Rewrite string `yaml:"rewrite"`
}

ToolBash groups Bash tool configuration (truncation + command rewrite).

type ToolDef

type ToolDef struct {
	Disabled    *bool  `yaml:"disabled"`
	Override    bool   `yaml:"override"`
	Description string `yaml:"description"`
	Usage       string `yaml:"usage"`
	Examples    string `yaml:"examples"`
	Condition   string `yaml:"condition"` // condition expression for conditional inclusion
	Parallel    *bool  `yaml:"parallel"`  // overrides tool.Parallel()
	Source      string `yaml:"-"`         // file path this definition was loaded from
}

ToolDef is a text-only override for a built-in or plugin tool. Loaded from .aura/config/tools/**/*.yaml.

func (ToolDef) IsDisabled

func (d ToolDef) IsDisabled() bool

IsDisabled returns true if the tool definition is explicitly disabled.

func (ToolDef) IsEnabled

func (d ToolDef) IsEnabled() bool

IsEnabled returns true if the tool definition is active (not explicitly disabled).

func (ToolDef) Text

func (d ToolDef) Text() tool.Text

Text returns the text fields for use as a text-only override.

type ToolDefs

type ToolDefs map[string]ToolDef

ToolDefs maps tool names to their definitions.

func (ToolDefs) Apply

func (td ToolDefs) Apply(ts *tool.Tools)

Apply applies text overrides and removes disabled tools. Matches tools by lowercased name against the ToolDefs keys. MergeText is idempotent — safe to call multiple times on the same tool set.

func (*ToolDefs) Load

func (td *ToolDefs) Load(ff files.Files) error

Load reads YAML files and merges all tool definitions into the map. Each file contains a map of tool names to their definitions. Multiple tools can live in one file, or each tool in its own file — the loader is decoupled from filenames.

func (ToolDefs) ParallelOverride

func (td ToolDefs) ParallelOverride(name string) *bool

ParallelOverride returns the config-level parallel override for a tool, or nil if not set.

type ToolExecution

type ToolExecution struct {
	// Mode selects the guard strategy: "tokens" (fixed limit) or "percentage" (context-fill based).
	Mode string `yaml:"mode" validate:"omitempty,oneof=percentage tokens"`
	// Result groups tool result size guard fields.
	Result ToolResult `yaml:"result"`
	// ReadSmallFileTokens is the token threshold below which the Read tool ignores line ranges and returns the full
	// file.
	ReadSmallFileTokens int `yaml:"read_small_file_tokens"`
	// MaxSteps caps the total number of iterations to prevent runaway loops.
	// At this limit, tools are disabled and the LLM must respond with text only.
	MaxSteps int `yaml:"max_steps"`
	// TokenBudget is the cumulative token limit (input + output) for a session.
	// Once reached, the assistant stops immediately. 0 = disabled.
	TokenBudget int `yaml:"token_budget"`
	// RejectionMessage is the fmt template sent back as the tool result when rejected.
	// Receives two %d arguments: estimated tokens, limit.
	RejectionMessage string `yaml:"rejection_message"`
	// Bash groups Bash tool configuration (truncation + command rewrite).
	Bash ToolBash `yaml:"bash"`
	// UserInputMaxPercentage is the context-fill percentage above which user input messages are rejected.
	// Prevents massive messages (typed, @Bash, @File) from entering the conversation and causing
	// unrecoverable context exhaustion. 0 = disabled.
	UserInputMaxPercentage float64 `yaml:"user_input_max_percentage"`
	// ReadBefore controls which file operations require a prior read.
	// write: true (default) = must read before overwriting existing files.
	// delete: false (default) = no read required before deleting.
	// Toggled at runtime with /readbefore (alias /rb).
	ReadBefore ReadBeforeConfig `yaml:"read_before"`
	// Enabled is the default for --include-tools. Glob patterns for tools to include.
	// Empty = no include filter (all tools pass). CLI --include-tools overrides this.
	Enabled []string `yaml:"enabled"`
	// Disabled is the default for --exclude-tools. Glob patterns for tools to exclude.
	// Empty = no exclude filter. CLI --exclude-tools overrides this.
	Disabled []string `yaml:"disabled"`
	// OptIn lists tool names that are registered but hidden unless explicitly enabled
	// by name or narrow glob at any layer (CLI, features, agent, mode, or task).
	// The bare "*" wildcard does NOT satisfy opt-in — only explicit names or narrow globs do.
	OptIn []string `yaml:"opt_in"`
	// Deferred lists tool name patterns excluded from request.Tools and listed in a
	// lightweight system prompt index instead. The model can load them on demand via
	// the LoadTools meta-tool. Empty = all tools are eager (no change in behavior).
	Deferred []string `yaml:"deferred"`
	// WebFetchMaxBodySize is the maximum response body size in bytes for the WebFetch tool.
	WebFetchMaxBodySize int64 `yaml:"webfetch_max_body_size"`
	// Parallel enables concurrent execution of independent tool calls within a single LLM turn.
	// nil = true (default). Explicit false = sequential (legacy behavior).
	Parallel *bool `yaml:"parallel"`
}

ToolExecution holds configuration for tool execution guards.

func (*ToolExecution) ApplyDefaults

func (t *ToolExecution) ApplyDefaults() error

ApplyDefaults sets sane defaults for zero-valued fields.

func (ToolExecution) ParallelEnabled

func (t ToolExecution) ParallelEnabled() bool

ParallelEnabled returns whether parallel tool execution is active. nil (default) = true.

type ToolPolicy

type ToolPolicy struct {
	Auto    []string `yaml:"auto"`
	Confirm []string `yaml:"confirm"`
	Deny    []string `yaml:"deny"`
	// contains filtered or unexported fields
}

ToolPolicy controls which tool calls are allowed, require confirmation, or are blocked. Three tiers: auto (run freely), confirm (ask user), deny (hard block). Precedence: deny > confirm > auto > default (auto).

Pattern format:

  • "Read" — matches the Read tool (name-only)
  • "mcp__*" — matches all MCP tools (glob on name)
  • "Bash:git commit*" — matches Bash with command matching "git commit*"
  • "Write:/tmp/*" — matches Write with path under /tmp/
  • "Read:/home/*" — matches Read with path under /home/

Argument matching (the part after ":") uses the tool's primary detail: Bash → command, file-operating tools → path/file_path argument.

func (*ToolPolicy) ApprovalsGlobal

func (p *ToolPolicy) ApprovalsGlobal() []string

ApprovalsGlobal returns the global-scoped approval patterns (from ~/.aura/config/rules/).

func (*ToolPolicy) ApprovalsProject

func (p *ToolPolicy) ApprovalsProject() []string

ApprovalsProject returns the project-scoped approval patterns (from config/rules/).

func (*ToolPolicy) DenyingPattern

func (p *ToolPolicy) DenyingPattern(toolName string, args map[string]any) string

DenyingPattern returns the first deny pattern matching the tool call, or "".

func (*ToolPolicy) Display

func (p *ToolPolicy) Display() string

Display returns a human-facing description for system prompt injection.

func (*ToolPolicy) Evaluate

func (p *ToolPolicy) Evaluate(toolName string, args map[string]any) PolicyAction

Evaluate returns the action for a given tool call. toolName is the tool's registered name (e.g. "Bash", "Write", "mcp__server__tool"). args are the tool call arguments (used for argument pattern matching).

func (*ToolPolicy) IsEmpty

func (p *ToolPolicy) IsEmpty() bool

IsEmpty reports whether the policy has no rules configured.

func (*ToolPolicy) Merge

func (p *ToolPolicy) Merge(other ToolPolicy) ToolPolicy

Merge combines two policies additively.

func (*ToolPolicy) PolicyDisplay

func (p *ToolPolicy) PolicyDisplay(agent, mode string) string

PolicyDisplay returns a rich human-facing policy summary for the /policy command.

type ToolPolicyData

type ToolPolicyData struct {
	Auto    []string // auto-approved patterns
	Confirm []string // confirmation-required patterns
	Deny    []string // denied patterns
	Display string   // pre-rendered display text
}

ToolPolicyData holds tool policy for template consumption. Templates can use {{ .ToolPolicy.Display }}, {{ range .ToolPolicy.Auto }}, etc.

type ToolResult

type ToolResult struct {
	// MaxTokens is the estimated token limit for a single tool result (used when mode = "tokens").
	MaxTokens int `yaml:"max_tokens"`
	// MaxPercentage is the context-fill percentage above which results are rejected (used when mode = "percentage").
	MaxPercentage float64 `yaml:"max_percentage"`
}

ToolResult groups tool result size guard configuration.

type ToolTrace

type ToolTrace struct {
	Name     string
	Included bool
	Reason   string
}

ToolTrace records the inclusion/exclusion status of a single tool along with the reason it was filtered.

type Tools

type Tools struct {
	// Enabled is the list of explicitly enabled tools.
	Enabled []string
	// Disabled is the list of explicitly disabled tools.
	Disabled []string
	// Policy controls which tool calls are auto-approved, require confirmation, or are blocked.
	Policy ToolPolicy `yaml:"policy"`
}

Tools defines which tools are enabled or disabled for an agent or mode.

type ToolsData

type ToolsData struct {
	Eager    []string // resolved eager tool names
	Deferred string   // pre-rendered deferred tool index XML (empty = none)
}

ToolsData holds eager and deferred tool information for template consumption. Templates use {{ .Tools.Eager }} and {{ .Tools.Deferred }}.

type Type

type Type string

Type identifies the scope of an AGENTS.md file.

const (
	// Global represents a user-wide AGENTS.md configuration.
	Global Type = "global"
	// Local represents a project-specific AGENTS.md configuration.
	Local Type = "local"
)

type Vision

type Vision struct {
	// Agent is the name of the agent to use for vision calls.
	Agent string `yaml:"agent"`
	// Dimension is the max pixel dimension for image compression (default: 1024).
	Dimension int `yaml:"dimension"`
	// Quality is the JPEG compression quality 1-100 (default: 75).
	Quality int `yaml:"quality"`
}

Vision holds configuration for the vision tool.

func (*Vision) ApplyDefaults

func (v *Vision) ApplyDefaults() error

ApplyDefaults sets sane defaults for zero-valued fields.

type WorkspaceEntry

type WorkspaceEntry struct {
	Type         string // display header (e.g., "Workspace Instructions: local")
	TemplateName string // registered template name (e.g., "ws:AGENTS.md")
}

WorkspaceEntry represents a workspace instruction file registered as a named template. Used in composition: {{ range .Workspace }}{{ include .TemplateName $ }}{{ end }}.

Directories

Path Synopsis
Package inherit provides struct-level config inheritance with DAG resolution.
Package inherit provides struct-level config inheritance with DAG resolution.
Package merge provides the canonical struct merge function for config inheritance and overlay.
Package merge provides the canonical struct merge function for config inheritance and overlay.

Jump to

Keyboard shortcuts

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