Documentation
¶
Index ¶
- Variables
- func LoadDotEnv()
- func LoadProjectContext(workDir string) (content string, path string)
- func LocalConfigPath() (string, error)
- func WatchConfig(ctx context.Context, path string, ch chan<- ConfigReloadMsg)
- type AgentsConfig
- type Config
- type ConfigReloadMsg
- type FeaturesConfig
- type GitConfig
- type LedgerConfig
- type ModelConfig
- type PermissionRule
- type PermissionsAgentConfig
- type PermissionsConfig
- type ProviderConfig
- type ProviderCredentialConfig
- type ToolsConfig
- type UIConfig
- type ValidationError
- type VerifyConfig
Constants ¶
This section is empty.
Variables ¶
var ErrValidation = errors.New("config validation")
ErrValidation is returned when config validation fails.
Functions ¶
func LoadDotEnv ¶
func LoadDotEnv()
func LoadProjectContext ¶
LoadProjectContext reads the first available project context file from workDir. It checks AGENTS.md, .m31a/agents.md, and MEMORY.md in priority order. Returns the file content and the path it was loaded from. Returns empty string and empty path if no context file is found.
func LocalConfigPath ¶
LocalConfigPath returns the path where a new project-level m31a.toml should be created (cwd/m31a.toml).
func WatchConfig ¶
func WatchConfig(ctx context.Context, path string, ch chan<- ConfigReloadMsg)
WatchConfig watches the config file for changes using fsnotify and sends ConfigReloadMsg to the provided channel when a change is detected. Falls back to polling with ConfigWatchInterval if fsnotify is unavailable. Runs until ctx is cancelled.
Types ¶
type AgentsConfig ¶
type Config ¶
type Config struct {
Provider ProviderConfig `toml:"provider"`
Model ModelConfig `toml:"model"`
UI UIConfig `toml:"ui"`
Permissions PermissionsConfig `toml:"permissions"`
Features FeaturesConfig `toml:"features"`
Ledger LedgerConfig `toml:"ledger"`
Tools ToolsConfig `toml:"tools"`
Agents AgentsConfig `toml:"agents"`
Git GitConfig `toml:"git"`
Verify VerifyConfig `toml:"verify"`
}
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns a Config with sane defaults. Missing config file causes Load to return DefaultConfig without error.
func Load ¶
Load reads a TOML config file from the given path, applies multi-layer merging (global TOML → env vars → project m31a.toml), validation, and variable substitution, then returns the resulting Config.
Config loading order (later overrides earlier):
- DefaultConfig() — zero-valued defaults
- Global TOML (~/.m31a/config.toml via path arg)
- Environment variable overrides (M31A_*)
- Project-level m31a.toml (walked up from cwd, max 3 levels)
- Variable substitution — ${VAR} → env value
- Validation — type/range checks on known fields
Missing global config file is not an error — first-run flow handles creation.
func (*Config) ResolveAPIKeys ¶
ResolveAPIKeys resolves API keys for OpenRouter and Zen using the priority order: environment variable → OS keychain → config file field.
Resolution per provider:
- Check M31A_OPENROUTER_API_KEY / M31A_ZEN_API_KEY env var
- If not set, try keychain.Get("openrouter") / keychain.Get("zen")
- If keychain returns ErrKeyNotFound or ErrKeychainUnavailable, fall back to c.Provider.OpenRouter.APIKey / c.Provider.Zen.APIKey
Never returns an error for missing keys — keys may be left empty for first-run or settings screen to handle.
func (*Config) Save ¶
Save writes the config to a TOML file atomically (temp file + rename). If M31A_CONFIG env var is set, it is used as the path instead. API keys are never persisted to the config file — they must be set via environment variables or the OS keychain.
func (*Config) SaveProject ¶
SaveProject writes the config to a project-level m31a.toml in the working directory. API keys are always cleared from project config for security — they belong in the global config or keychain.
func (*Config) SaveWithKeychain ¶
SaveWithKeychain writes the config to a TOML file atomically. If a keychain is provided and available, API keys are saved to the keychain and cleared from the config file. If the keychain is unavailable or nil, API keys are persisted to the config file as a fallback (with a warning).
type ConfigReloadMsg ¶
ConfigReloadMsg is emitted when the config file changes on disk.
type FeaturesConfig ¶
type FeaturesConfig struct {
AutoBackup bool `toml:"auto_backup"`
ResumeOnStartup bool `toml:"resume_on_startup"`
// WorkflowMode controls phase-skipping behaviour:
// "auto" — classify and adapt automatically (default)
// "full" — always run all 6 phases
// "fast" — skip Plan phase (Discuss→Execute)
// "direct" — skip Discuss, Plan, Verify (only Initialize→Execute→Ship)
// Empty string means auto.
WorkflowMode string `toml:"workflow_mode"`
// Model cache TTL in minutes. Default 5.
ModelCacheTTLMinutes int `toml:"model_cache_ttl_minutes"`
// Stale cache TTL in hours. Default 24.
ModelCacheStaleHours int `toml:"model_cache_stale_hours"`
// Health check latency thresholds in milliseconds.
HealthCheckLiveMs int `toml:"healthcheck_live_ms"`
HealthCheckSlowMs int `toml:"healthcheck_slow_ms"`
// Session ID length in hex chars. Default 8.
SessionIDLength int `toml:"session_id_length"`
// Max recent models to remember. Default 10.
MaxRecentModels int `toml:"max_recent_models"`
// Session retention in days. Default 30.
SessionRetentionDays int `toml:"session_retention_days"`
// Health check timeout in seconds. Default 10.
HealthCheckTimeoutSecs int `toml:"health_check_timeout_secs"`
// Rate limit backoff in seconds. Default 120.
RateLimitBackoffSecs int `toml:"rate_limit_backoff_secs"`
// Optional per-session budget limit in USD. 0 means no limit.
// When set, workflow phases check cumulative cost before proceeding.
BudgetLimitUSD float64 `toml:"budget_limit_usd"`
}
type GitConfig ¶
type GitConfig struct {
CommitPrefix string `toml:"commit_prefix"`
FixPrefix string `toml:"fix_prefix"`
ShipPrefix string `toml:"ship_prefix"`
UserName string `toml:"user_name"`
UserEmail string `toml:"user_email"`
}
GitConfig holds configurable git commit message prefixes and user identity.
func DefaultGitConfig ¶
func DefaultGitConfig() GitConfig
DefaultGitConfig returns the default git configuration.
type LedgerConfig ¶
type ModelConfig ¶
type ModelConfig struct {
Default string `toml:"default"`
ContextWarningThreshold float64 `toml:"context_warning_threshold"`
ShowThinkingByDefault bool `toml:"show_thinking_by_default"`
AutoCollapseTools bool `toml:"auto_collapse_tools"`
AutoArbitrage bool `toml:"auto_arbitrage"`
ArbitrageThreshold float64 `toml:"arbitrage_threshold"`
// Default context length used when provider doesn't return one.
DefaultContextLength int `toml:"default_context_length"`
// Token estimator EMA calibration rate (0.0–1.0). Lower = slower calibration.
TokenEMAAlpha float64 `toml:"token_ema_alpha"`
}
type PermissionRule ¶
type PermissionsAgentConfig ¶
type PermissionsAgentConfig struct {
DefaultAction string `toml:"default_action"`
Rules []PermissionRule `toml:"rules"`
}
PermissionsAgentConfig defines per-agent permission profiles. Each agent (e.g., "build", "plan", "default") can have its own default action and ruleset.
type PermissionsConfig ¶
type PermissionsConfig struct {
DefaultMode string `toml:"default_mode"`
TimeoutSeconds int `toml:"timeout_seconds"`
Rules []PermissionRule `toml:"rules"`
Agents map[string]PermissionsAgentConfig `toml:"agents,omitempty"`
}
type ProviderConfig ¶
type ProviderConfig struct {
Default string `toml:"default"`
AutoFallback bool `toml:"auto_fallback"`
OpenRouter ProviderCredentialConfig `toml:"openrouter"`
Zen ProviderCredentialConfig `toml:"zen"`
// Custom base URLs for self-hosted or proxied gateways.
// Empty means use the default provider URLs.
OpenRouterBaseURL string `toml:"openrouter_base_url"`
ZenBaseURL string `toml:"zen_base_url"`
// HTTP-Referer and X-Title headers sent to OpenRouter.
// Empty means use defaults ("https://github.com/eshanized/M31A", "M31A").
OpenRouterReferer string `toml:"openrouter_referer"`
OpenRouterTitle string `toml:"openrouter_title"`
}
type ProviderCredentialConfig ¶
type ProviderCredentialConfig struct {
APIKey string `toml:"api_key"`
}
type ToolsConfig ¶
type ToolsConfig struct {
MaxGlobResults int `toml:"max_glob_results"`
MaxGrepResults int `toml:"max_grep_results"`
BashKillGraceSecs int `toml:"bash_kill_grace_secs"`
MaxBackupsPerFile int `toml:"max_backups_per_file"`
WebfetchMaxRedirects int `toml:"webfetch_max_redirects"`
WebfetchUserAgent string `toml:"webfetch_user_agent"`
SkipDirs []string `toml:"skip_dirs"`
WebSearchBaseURL string `toml:"websearch_base_url"`
WebSearchEnabled bool `toml:"websearch_enabled"`
}
AgentsConfig defines per-workflow-phase model assignments. Each field names a workflow phase and holds a model ID string. Allows users to assign different models to different workflow phases (e.g., cheap model for Plan, powerful model for Execute). ToolsConfig defines configurable limits for tool execution.
type UIConfig ¶
type UIConfig struct {
Theme string `toml:"theme"`
CompactMode bool `toml:"compact_mode"`
ShowTokenUsage bool `toml:"show_token_usage"`
ShowCostEstimate bool `toml:"show_cost_estimate"`
MaxIterations int `toml:"max_iterations"`
// Leader key for chord shortcuts. Default "ctrl+x".
LeaderKey string `toml:"leader_key"`
// Leader key timeout duration in milliseconds. Default 1000.
LeaderTimeoutMs int `toml:"leader_timeout_ms"`
// Minimum terminal width before sidebar auto-shows. Default 120.
SidebarWidthThreshold int `toml:"sidebar_width_threshold"`
// Discuss Q&A timeout in seconds. Default 300 (5 minutes).
DiscussTimeout int `toml:"discuss_timeout"`
// Max lines for thinking block content. Default 20.
ThinkingMaxLines int `toml:"thinking_max_lines"`
// Permission modal width in columns. Default 60.
PermissionModalWidth int `toml:"permission_modal_width"`
// Sidebar width in columns. Default 42.
SidebarWidth int `toml:"sidebar_width"`
// Max message history entries. Default 1000.
MaxMessageHistory int `toml:"max_message_history"`
// Fallback banner display duration in seconds. Default 15.
FallbackBannerSecs int `toml:"fallback_banner_timeout_secs"`
// Default number of log lines to show. Default 20.
DefaultLogLines int `toml:"default_log_lines"`
// Max sessions to list in resume screen. Default 10.
SessionListLimit int `toml:"session_list_limit"`
// Thinking block opacity. Default 0.6.
ThinkingOpacity float64 `toml:"thinking_opacity"`
// Frecent history max entries. Default 100.
FrecentHistorySize int `toml:"frecent_history_size"`
// New - Theme & Colors
AccentColor string `toml:"accent_color"`
CustomBackground string `toml:"custom_background"`
BorderStyle string `toml:"border_style"`
// New - Typography
BoldHeaders bool `toml:"bold_headers"`
ItalicThinking bool `toml:"italic_thinking"`
TabWidth int `toml:"tab_width"`
// New - Layout
SidebarPosition string `toml:"sidebar_position"`
SidebarAutoShow bool `toml:"sidebar_auto_show"`
CardPadding int `toml:"card_padding"`
WelcomeScreen bool `toml:"welcome_screen"`
ZenModeKey string `toml:"zen_mode_key"`
// New - Animation
AnimationSpeed string `toml:"animation_speed"`
SpinnerStyle string `toml:"spinner_style"`
TransitionStyle string `toml:"transition_style"`
BreathingEffects bool `toml:"breathing_effects"`
LogoAnimation bool `toml:"logo_animation"`
// New - Status Bar
StatusBarStyle string `toml:"status_bar_style"`
StatusBarPosition string `toml:"status_bar_position"`
ShowSpinnerInStatus bool `toml:"show_spinner_in_status"`
// New - Tool Cards
ToolCardStyle string `toml:"tool_card_style"`
ToolOutputMaxLines int `toml:"tool_output_max_lines"`
SyntaxHighlight bool `toml:"syntax_highlight"`
// New - Toasts
ToastPosition string `toml:"toast_position"`
ToastDurationSecs int `toml:"toast_duration_secs"`
ToastMaxVisible int `toml:"toast_max_visible"`
}
type ValidationError ¶
ValidationError describes a single field-level config validation failure.
func (ValidationError) Error ¶
func (e ValidationError) Error() string
type VerifyConfig ¶
type VerifyConfig struct {
BuildCommand string `toml:"build_command"`
TestCommand string `toml:"test_command"`
}
VerifyConfig holds configurable verification commands. Empty values trigger auto-detection (existing behavior).