config

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 12, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package validator provides config validation utilities.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func APIKeyForProvider

func APIKeyForProvider(provider string) string

APIKeyForProvider reads the API key for a provider from the environment.

func AllEnvKeyStatus

func AllEnvKeyStatus() string

AllEnvKeyStatus returns a comma-separated summary of all known API key env vars.

func ApplyOutputStyle

func ApplyOutputStyle(content string, style OutputStyle) string

ApplyOutputStyle wraps content with the style template. The template may contain {{content}} as a placeholder for the actual content.

func BashCompletion

func BashCompletion() string

BashCompletion returns a bash completion script for hawk.

func BoolPtr

func BoolPtr(b bool) *bool

BoolPtr returns a pointer to the given bool value.

func BuildContext

func BuildContext() string

BuildContext assembles the full context string for the system prompt.

func BuildContextWithDirs

func BuildContextWithDirs(addDirs []string) string

BuildContextWithDirs assembles context including additional user-specified directories.

func DefaultAliases

func DefaultAliases() map[string]string

DefaultAliases returns the built-in command aliases.

func DefaultIgnorePatterns

func DefaultIgnorePatterns() []string

DefaultIgnorePatterns returns the built-in ignore patterns.

func EnvKeyStatus

func EnvKeyStatus(provider string) string

EnvKeyStatus returns "set" or "empty" for a provider's API key in the environment.

func FetchModelsForProvider

func FetchModelsForProvider(provider string) ([]catalog.ModelCatalogEntry, error)

FetchModelsForProvider fetches live models from the provider's API (if key available) or returns embedded catalog models. This is the runtime model discovery boundary.

func FishCompletion

func FishCompletion() string

FishCompletion returns a fish completion script for hawk.

func FormatActiveRules

func FormatActiveRules(rules []Rule) string

FormatActiveRules formats active rules for injection into the system prompt.

func FormatBudgetStatus

func FormatBudgetStatus(status BudgetStatus, spent, max float64) string

FormatBudgetStatus returns a human-readable string describing the budget status.

func GetAPIKey

func GetAPIKey(provider string) string

GetAPIKey returns the API key for a provider, checking multiple sources. Delegates to ProviderAPIKeyEnv (settings.go) as the single source of truth for provider→env-var mappings, with fallback aliases for compatibility.

func GitContext

func GitContext() string

GitContext returns git info for the system prompt.

func InstallCompletions

func InstallCompletions(shell string) string

InstallCompletions returns instructions for installing shell completions.

func LoadAPIKeysFromEnv

func LoadAPIKeysFromEnv() map[string]string

LoadAPIKeysFromEnv reads all known API keys from environment variables.

func LoadAgentDir

func LoadAgentDir() string

LoadAgentDir returns the path to .hawk/ or .agent/ directory, whichever exists. .hawk/ takes priority. Returns empty string if neither exists.

func LoadAgentsMD

func LoadAgentsMD() string

LoadAgentsMD reads AGENTS.md (or AGENTS.md for backward compatibility) from the current directory or parents.

func LoadAgentsMDFrom

func LoadAgentsMDFrom(start string) string

LoadAgentsMDFrom reads AGENTS.md (or AGENTS.md fallback) from start or its parents.

func LoadAliases

func LoadAliases() map[string]string

LoadAliases reads command aliases from ~/.hawk/aliases.json. Returns default aliases if the file does not exist.

func LoadDotEnv

func LoadDotEnv()

LoadDotEnv loads environment variables from .env files. Checks in order: .env, .env.local (project), then ~/.hawk/.env (global). Does NOT override existing environment variables.

func LoadEnvFile

func LoadEnvFile() error

LoadEnvFile reads ~/.hawk/env and applies export lines to the process.

func LoadIgnorePatterns

func LoadIgnorePatterns() []string

LoadIgnorePatterns reads ignore patterns from .hawkignore or .hawk/ignore. Falls back to default patterns if neither file exists.

func MaskAPIKey

func MaskAPIKey(key string) string

MaskAPIKey returns a masked version of an API key for display.

func NormalizeProviderForEngine

func NormalizeProviderForEngine(provider string) string

NormalizeProviderForEngine maps hawk provider aliases to eyrie canonical names. This is the boundary where hawk names become engine/eyrie names.

func OutputStyleModTime

func OutputStyleModTime() time.Time

OutputStyleModTime returns the latest modification time of any style file, useful for cache invalidation.

func ProviderAPIKeyEnv

func ProviderAPIKeyEnv(provider string) string

ProviderAPIKeyEnv returns the environment variable name for a provider's API key.

func RemoveEnvFile

func RemoveEnvFile(key string) error

RemoveEnvFile removes an export line from ~/.hawk/env.

func ResolveAlias

func ResolveAlias(input string, aliases map[string]string) string

ResolveAlias checks if the first word of input matches an alias key. If found, it replaces the alias with its expansion and appends the rest of the input. If not found, returns the input unchanged.

func SaveAliases

func SaveAliases(aliases map[string]string) error

SaveAliases writes command aliases to ~/.hawk/aliases.json.

func SaveEnvFile

func SaveEnvFile(key, value string) error

SaveEnvFile writes an export line to ~/.hawk/env, deduplicating existing entries.

func SaveGlobal

func SaveGlobal(s Settings) error

SaveGlobal saves settings to the global config file.

func SaveProject

func SaveProject(s Settings) error

SaveProject saves settings to the project config file.

func SetGlobalSetting

func SetGlobalSetting(key, value string) error

SetGlobalSetting updates a supported scalar/list setting in ~/.hawk/settings.json. Herm-style: API keys are NOT stored in settings.json. Use environment variables.

func SettingValue

func SettingValue(s Settings, key string) (string, bool)

SettingValue returns a display-safe value for a supported setting key.

func ShouldIgnore

func ShouldIgnore(path string, patterns []string) bool

ShouldIgnore checks if a path matches any of the given ignore patterns. Supports gitignore-style matching:

  • Simple names match any path component (e.g., "node_modules" matches "a/node_modules/b")
  • Glob patterns with * are matched against the base name (e.g., "*.pyc" matches "foo.pyc")
  • Paths with / are matched against the full path

func ValidateAPIKey

func ValidateAPIKey(provider string) (string, bool)

ValidateAPIKey checks if an API key is set for the provider.

func ZshCompletion

func ZshCompletion() string

ZshCompletion returns a zsh completion script for hawk.

Types

type Attribution

type Attribution struct {
	TrailerStyle  string `json:"trailer_style,omitempty"`  // "none", "co-authored-by", "assisted-by" (default)
	GeneratedWith bool   `json:"generated_with,omitempty"` // append "Generated with Hawk" line
}

Attribution controls how hawk identifies itself in git commits.

type BudgetConfig

type BudgetConfig struct {
	MaxCostUSD          float64 `json:"max_cost_usd"`
	MaxTokensPerSession int     `json:"max_tokens_per_session"`
	WarnAtPercent       float64 `json:"warn_at_percent"` // 0-100, default 80
}

BudgetConfig holds cost and token budget settings.

func DefaultBudgetConfig

func DefaultBudgetConfig() BudgetConfig

DefaultBudgetConfig returns a BudgetConfig with sensible defaults.

func LoadBudget

func LoadBudget() BudgetConfig

LoadBudget loads budget configuration from settings. It reads MaxBudgetUSD from the global settings and applies defaults.

type BudgetStatus

type BudgetStatus int

BudgetStatus represents the current budget state.

const (
	BudgetOK       BudgetStatus = iota // within budget
	BudgetWarning                      // approaching limit
	BudgetExceeded                     // over limit
)

func CheckBudget

func CheckBudget(spent float64, config BudgetConfig) BudgetStatus

CheckBudget evaluates current spending against the budget config. Returns BudgetOK, BudgetWarning, or BudgetExceeded.

func (BudgetStatus) String

func (s BudgetStatus) String() string

String returns a human-readable budget status.

type CustomProviderConfig

type CustomProviderConfig struct {
	Name      string `json:"name"`
	BaseURL   string `json:"base_url"`
	APIKeyEnv string `json:"api_key_env,omitempty"`
	Model     string `json:"model,omitempty"`
}

CustomProviderConfig defines a user-specified OpenAI-compatible provider.

type MCPServerConfig

type MCPServerConfig struct {
	Name    string            `json:"name"`
	Command string            `json:"command,omitempty"`
	Args    []string          `json:"args,omitempty"`
	Type    string            `json:"type,omitempty"`    // "stdio" (default), "sse", "http"
	URL     string            `json:"url,omitempty"`     // for sse/http transports
	Headers map[string]string `json:"headers,omitempty"` // custom headers for sse/http
}

MCPServerConfig defines an MCP server to connect at startup.

type OutputStyle

type OutputStyle struct {
	Name             string
	Description      string
	Template         string
	KeepInstructions bool
}

OutputStyle defines a custom output format loaded from a markdown file.

func LoadOutputStyles

func LoadOutputStyles() []OutputStyle

LoadOutputStyles loads .md files from .hawk/output-styles/ (project-local) and ~/.hawk/output-styles/ (global), merging both. Project-local styles take priority over global styles with the same name.

type PromptTemplate

type PromptTemplate struct {
	Name     string   `json:"name"`
	Template string   `json:"template"`
	Args     []string `json:"args,omitempty"`
}

PromptTemplate is a reusable prompt template.

func LoadTemplates

func LoadTemplates() []PromptTemplate

LoadTemplates loads prompt templates from ~/.hawk/templates/.

func (*PromptTemplate) Apply

func (t *PromptTemplate) Apply(args map[string]string) string

Apply fills template args using {{key}} placeholders.

type Rule

type Rule struct {
	Name    string
	Content string
	Paths   []string // glob patterns; empty = always active
}

Rule represents a project rule loaded from .hawk/rules/*.md.

func ActiveRules

func ActiveRules(rules []Rule, touchedPaths []string) []Rule

ActiveRules filters rules to those whose Paths match any of the touchedPaths. Rules with empty Paths are always active.

func LoadRules

func LoadRules() []Rule

LoadRules reads all .md files from .hawk/rules/ in the current directory. Each file can have optional YAML frontmatter with a paths field.

func LoadRulesFrom

func LoadRulesFrom(base string) []Rule

LoadRulesFrom reads rules from .hawk/rules/ under the given directory.

type Settings

type Settings struct {
	Model                   string                 `json:"model,omitempty"`
	Provider                string                 `json:"provider,omitempty"`
	Theme                   string                 `json:"theme,omitempty"`
	AutoAllow               []string               `json:"auto_allow,omitempty"`      // tools to always allow
	AllowedTools            []string               `json:"allowedTools,omitempty"`    // archive-compatible allow rules
	DisallowedTools         []string               `json:"disallowedTools,omitempty"` // archive-compatible deny rules
	MaxBudgetUSD            float64                `json:"max_budget_usd,omitempty"`  // cost cap per session
	CustomHeaders           map[string]string      `json:"custom_headers,omitempty"`
	MCPServers              []MCPServerConfig      `json:"mcp_servers,omitempty"`
	CustomProviders         []CustomProviderConfig `json:"custom_providers,omitempty"`
	RepoMap                 *bool                  `json:"repo_map,omitempty"`
	RepoMapMaxTokens        int                    `json:"repo_map_max_tokens,omitempty"`
	Sandbox                 string                 `json:"sandbox,omitempty"`                    // sandbox mode: strict, workspace, off
	AutoCommit              *bool                  `json:"auto_commit,omitempty"`                // auto-commit file changes
	Autonomy                int                    `json:"autonomy,omitempty"`                   // autonomy level 0-4
	ModelRoles              *routing.ModelRoles    `json:"model_roles,omitempty"`                // per-role model overrides
	AutoCompactThresholdPct int                    `json:"auto_compact_threshold_pct,omitempty"` // token % to trigger auto-compact (default 85)
	Frugal                  bool                   `json:"frugal,omitempty"`                     // aggressive cost optimization: cascade to cheap models, lower max_tokens, earlier compaction
	Attribution             *Attribution           `json:"attribution,omitempty"`
}

Settings holds hawk configuration. Herm-style: no API keys stored here. Secrets come from environment variables only.

func LoadGlobalSettings

func LoadGlobalSettings() Settings

LoadGlobalSettings loads only ~/.hawk/settings.json.

func LoadSettings

func LoadSettings() Settings

LoadSettings loads settings from global + project, with project overriding global.

func LoadSettingsWithOverride

func LoadSettingsWithOverride(override string) (Settings, error)

LoadSettingsWithOverride loads normal settings plus a JSON object or JSON file override.

func MergeSettings

func MergeSettings(base, override Settings) Settings

MergeSettings applies override fields on top of base using project-style precedence.

func (*Settings) UnmarshalJSON

func (s *Settings) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts both Go-era snake_case keys and archive-style camelCase keys.

type ValidationError

type ValidationError struct {
	Field   string `json:"field"`
	Message string `json:"message"`
	Value   string `json:"value,omitempty"`
}

ValidationError represents a config validation error.

func (ValidationError) Error

func (e ValidationError) Error() string

type ValidationResult

type ValidationResult struct {
	Errors []ValidationError `json:"errors"`
	Valid  bool              `json:"valid"`
}

ValidationResult contains all validation errors.

func ValidateSettings

func ValidateSettings(s Settings) ValidationResult

ValidateSettings validates a Settings object.

func (ValidationResult) Error

func (r ValidationResult) Error() string

Error returns a formatted error string.

Jump to

Keyboard shortcuts

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