config

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 26, 2026 License: MIT Imports: 30 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 OS secret store.

func ActiveGateway

func ActiveGateway(ctx context.Context) string

ActiveGateway returns the user's setup gateway (never an aggregator owner slug like moonshotai).

func ActiveModel

func ActiveModel(ctx context.Context) string

ActiveModel returns the selected model from eyrie provider.json (not hawk settings).

func ActiveProvider

func ActiveProvider(ctx context.Context) string

ActiveProvider returns the selected provider from eyrie provider.json.

func AllCanonicalModelIDs

func AllCanonicalModelIDs() []string

AllCanonicalModelIDs returns sorted canonical model IDs from the eyrie catalog.

func AllCatalogProviders

func AllCatalogProviders() []string

AllCatalogProviders returns provider IDs from eyrie (providers + deployments, not hawk constants).

func AllEnvKeyStatus

func AllEnvKeyStatus() string

AllEnvKeyStatus returns a comma-separated summary of providers with credentials set.

func AllSetupGateways

func AllSetupGateways() []string

AllSetupGateways returns gateway IDs where users paste API keys (eyrie registry only). Aggregator owner slugs from OpenRouter/CanopyWave catalogs (ai21, alibaba, …) are excluded.

func ApplyEyrieCredentials

func ApplyEyrieCredentials(ctx context.Context) (*setup.ApplyCredentialsResult, error)

ApplyEyrieCredentials discovers the catalog and writes provider.json (routing only on disk).

func ApplyEyrieCredentialsForProvider

func ApplyEyrieCredentialsForProvider(ctx context.Context, providerID string) (*setup.ApplyCredentialsResult, error)

ApplyEyrieCredentialsForProvider refreshes live models for one provider after /config saves a key.

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 AutoRefreshCatalog

func AutoRefreshCatalog(ctx context.Context, out io.Writer, verbose bool) error

AutoRefreshCatalog runs eyrie discover (remote + live APIs when keys are set).

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 CachedModelCountForProvider

func CachedModelCountForProvider(provider string) int

CachedModelCountForProvider returns model count from the on-disk catalog only (no network).

func CatalogCachePathForDisplay

func CatalogCachePathForDisplay() string

CatalogCachePathForDisplay returns the path users should care about.

func CatalogEmptyHint

func CatalogEmptyHint(ctx context.Context) string

CatalogEmptyHint returns actionable guidance when the catalog has no models.

func CatalogReady

func CatalogReady(ctx context.Context) bool

CatalogReady reports whether the eyrie catalog cache exists and has models.

func CatalogStatusLine

func CatalogStatusLine(ctx context.Context) string

CatalogStatusLine returns a short one-line status for the TUI welcome banner.

func CheapestModelForProvider

func CheapestModelForProvider(provider, fallback string) string

CheapestModelForProvider picks the lowest input-priced model from eyrie's catalog.

func ClearActiveSelection

func ClearActiveSelection(ctx context.Context) error

ClearActiveSelection removes persisted provider/model from provider.json.

func CompiledCatalogV1

func CompiledCatalogV1() *catalog.CompiledCatalogV1

CompiledCatalogV1 loads the eyrie catalog from cache or bootstrap wiring (no network).

func ConfigProviderList

func ConfigProviderList(custom []CustomProviderConfig) []string

ConfigProviderList returns provider names for the /config UI from catalog + custom providers.

func ConfiguredCredentialProviders

func ConfiguredCredentialProviders() []string

ConfiguredCredentialProviders returns setup gateways with a stored API key.

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 DefaultModelConfigs

func DefaultModelConfigs() map[string]*ModelConfig

DefaultModelConfigs returns built-in configurations for common use cases.

func DefaultModelForProvider

func DefaultModelForProvider(provider string) string

func DefaultModelProviderFilter

func DefaultModelProviderFilter(ctx context.Context) string

DefaultModelProviderFilter picks which eyrie provider to list models for when the UI has no explicit filter. Host prefs (settings) win; otherwise eyrie routing/deployments decide.

func DeploymentRoutingEnabled

func DeploymentRoutingEnabled(s Settings) bool

DeploymentRoutingEnabled decides whether hawk uses catalog-backed deployment routing (same rules as eyrie CLI). HAWK_DEPLOYMENT_ROUTING overrides; otherwise settings flag, otherwise provider.json shape via eyrie/setup.

func DeploymentRoutingLabel

func DeploymentRoutingLabel(settings Settings) string

DeploymentRoutingLabel returns a short on/off label for the config hub.

func DeploymentStatusReport

func DeploymentStatusReport(ctx context.Context, activeModel string) (string, error)

DeploymentStatusReport returns hawk deployment routing diagnostics.

func DetectVersion

func DetectVersion(data map[string]interface{}) int

DetectVersion uses heuristics to determine the config version when no config_version field is present.

func DiffConfigs

func DiffConfigs(old, new map[string]interface{}) string

DiffConfigs returns a human-readable diff showing what changed during migration.

func DiscoverCatalogAfterSetup

func DiscoverCatalogAfterSetup(ctx context.Context, out io.Writer)

DiscoverCatalogAfterSetup runs during optional hawk setup after API keys are saved.

func EnsureCatalogAvailable

func EnsureCatalogAvailable(ctx context.Context) error

EnsureCatalogAvailable returns an error when the production catalog cache is missing or empty.

func EnvKeyStatus

func EnvKeyStatus(provider string) string

EnvKeyStatus returns set, empty, or local from the OS credential store.

func EstimateCost

func EstimateCost(pack *ModelPack, tokensPerSession int) float64

EstimateCost estimates the cost of a session with the given pack based on approximate tokens per session distributed evenly across roles.

func ExampleModelHints

func ExampleModelHints() (anthropic, openai string)

ExampleModelHints returns short example model aliases for user-facing error messages.

func FetchModelsForProvider

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

FetchModelsForProvider returns models from the eyrie catalog (dynamic; no hawk hardcoded lists). RefreshModelCatalogV1 is the explicit network refresh boundary.

func FirstRunSetupHint

func FirstRunSetupHint(ctx context.Context) string

FirstRunSetupHint returns a short banner line for the welcome screen.

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 FormatApplyCredentialsSummary

func FormatApplyCredentialsSummary(result *setup.ApplyCredentialsResult) string

func FormatBudgetStatus

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

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

func FormatCatalogHealth

func FormatCatalogHealth(h CatalogHealth) string

FormatCatalogHealth returns human-readable catalog status for hawk doctor.

func FormatConfig

func FormatConfig(config *ModelConfig) string

FormatConfig produces a human-readable summary of a ModelConfig.

func FormatConfigProviderError

func FormatConfigProviderError(providerID string, err error) string

FormatConfigProviderError maps eyrie setup errors to user-facing /config hints.

func FormatCredentialCLIStatus

func FormatCredentialCLIStatus(ctx context.Context) string

FormatCredentialCLIStatus returns hawk credentials status output (providers, not raw env names).

func FormatDeveloperPathReport

func FormatDeveloperPathReport(ctx context.Context) string

FormatDeveloperPathReport renders the developer path readiness report for CLI/TUI.

func FormatEcosystemPanel

func FormatEcosystemPanel(ctx context.Context, provider, model string) string

FormatEcosystemPanel summarizes eyrie, yaad, and tok integration for doctor and status output.

func FormatPack

func FormatPack(pack *ModelPack) string

FormatPack returns a human-readable formatted string for a model pack.

func FormatTemplate

func FormatTemplate(template *ConfigTemplate) string

FormatTemplate returns a human-readable summary of a template.

func GatewayDisplayName

func GatewayDisplayName(gatewayID string) string

func GatewayForModel

func GatewayForModel(modelID string) string

GatewayForModel resolves the setup gateway for a model id.

func GenerateAgentsmd

func GenerateAgentsmd(template *ConfigTemplate, vars map[string]string) string

GenerateAgentsmd generates AGENTS.md content from a template.

func GenerateHawkConfig

func GenerateHawkConfig(template *ConfigTemplate, vars map[string]string) string

GenerateHawkConfig generates .hawk/settings.json content from a template.

func GenerateRules

func GenerateRules(template *ConfigTemplate) string

GenerateRules generates .hawk/rules permission file content from a template.

func GitContext

func GitContext() string

GitContext returns git info for the system prompt.

func HasConfiguredDeployment

func HasConfiguredDeployment(ctx context.Context) bool

HasConfiguredDeployment reports whether at least one eyrie deployment has credentials.

func HasConfiguredDeploymentCached

func HasConfiguredDeploymentCached(ctx context.Context) bool

HasConfiguredDeploymentCached is a fast cached check for the /config TUI only.

func HasSelectedModel

func HasSelectedModel() bool

HasSelectedModel reports whether eyrie provider.json has a selected model.

func InstallCompletions

func InstallCompletions(shell string) string

InstallCompletions returns instructions for installing shell completions.

func InvalidateConfigUICache

func InvalidateConfigUICache()

InvalidateConfigUICache drops in-memory catalog and credential snapshots (call after refresh/key changes).

func IsSetupGateway

func IsSetupGateway(providerID string) bool

IsSetupGateway reports whether id is a registered setup gateway.

func LoadAPIKeysFromStore

func LoadAPIKeysFromStore() map[string]string

LoadAPIKeysFromStore reads API keys for all eyrie catalog providers from the OS secret store.

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 LoadIgnorePatterns

func LoadIgnorePatterns() []string

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

func LoadRoutingPolicyJSON

func LoadRoutingPolicyJSON() (string, error)

LoadRoutingPolicyJSON returns the routing section of provider.json as indented JSON.

func MaskCredentialForProvider

func MaskCredentialForProvider(ctx context.Context, provider string) string

MaskCredentialForProvider returns a partially masked API key for UI display.

func MigrateProviderConfig

func MigrateProviderConfig() error

MigrateProviderConfig upgrades ~/.hawk/provider.json to deployment v2 in place.

func MigrateProviderSecrets

func MigrateProviderSecrets() error

MigrateProviderSecrets strips api keys from on-disk provider.json (one-time hygiene).

func ModelIDsForProvider

func ModelIDsForProvider(provider string) ([]string, error)

func NeedsFirstRunSetup

func NeedsFirstRunSetup(ctx context.Context) bool

NeedsFirstRunSetup is true when the user should complete /config (API key and/or model).

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 ParseEnvFile

func ParseEnvFile(path string) (map[string]string, error)

ParseEnvFile parses a .env file and returns a map of key-value pairs. Supports: KEY=value, KEY="quoted value", KEY='single quoted', comments (#), empty lines, export prefix, and multiline values with \.

func PersistAPIKey

func PersistAPIKey(ctx context.Context, envKey, secret string) error

PersistAPIKey saves a provider API key via eyrie (OS secret store).

func PrepareCatalogForSession

func PrepareCatalogForSession(ctx context.Context, out io.Writer, opts CatalogStartupOptions) error

PrepareCatalogForSession ensures a usable, fresh catalog before chat/print. By default hawk auto-discovers when the cache is missing, empty, or stale.

func PrepareCredentialDiscovery

func PrepareCredentialDiscovery(ctx context.Context)

PrepareCredentialDiscovery migrates any legacy ~/.hawk/env keys into the OS secret store.

func PrimaryAPIKeyEnvForDeployment

func PrimaryAPIKeyEnvForDeployment(deploymentID string) string

PrimaryAPIKeyEnvForDeployment returns the env var name for a deployment's API key.

func ProviderAPIKeyEnv

func ProviderAPIKeyEnv(provider string) string

ProviderAPIKeyEnv returns the API key env var from eyrie deployment env_fallbacks.

func ProviderConfigJSON

func ProviderConfigJSON() (string, error)

ProviderConfigJSON returns the current provider.json as indented JSON (routing included).

func ProviderIDForDeployment

func ProviderIDForDeployment(deploymentID string) string

ProviderIDForDeployment returns the catalog provider id for a deployment (e.g. anthropic-direct → anthropic).

func ProviderOfModel

func ProviderOfModel(modelName string) string

ProviderOfModel resolves catalog provider for a canonical model ID or alias.

func RefreshCatalogAfterCredentials

func RefreshCatalogAfterCredentials(ctx context.Context, out io.Writer) error

RefreshCatalogAfterCredentials runs eyrie discover after /config saves API keys.

func RefreshConfigCredSnapshot

func RefreshConfigCredSnapshot(ctx context.Context)

RefreshConfigCredSnapshot re-reads keychain status for setup gateways (call when opening /config).

func RefreshGatewayCatalog

func RefreshGatewayCatalog(ctx context.Context, providerID string) (string, error)

RefreshGatewayCatalog fetches live models for one gateway and updates the cache.

func RefreshModelCatalogV1

func RefreshModelCatalogV1(ctx context.Context) (string, error)

RefreshModelCatalogV1 asks eyrie to refresh the remote catalog and provider APIs using env API keys.

func RemoveStoredCredential

func RemoveStoredCredential(ctx context.Context, target string) ([]string, error)

RemoveStoredCredential deletes stored API key(s) for a provider name or env var.

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 ResolveCanonicalModel

func ResolveCanonicalModel(model string) string

ResolveCanonicalModel maps aliases and native IDs to catalog canonical model IDs.

func RollbackMigration

func RollbackMigration(configPath, backupPath string) error

RollbackMigration restores a config file from its backup.

func RoutingPreviewJSON

func RoutingPreviewJSON(ctx context.Context, model string) (string, error)

RoutingPreviewJSON returns effective routing for a model (eyrie routing JSON preview).

func SaveAliases

func SaveAliases(aliases map[string]string) error

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

func SaveCredential

func SaveCredential(ctx context.Context, inference CredentialInference, secret string) error

SaveCredential validates, probes, and stores via eyrie keychain.

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 SaveProjectOrGlobalDeploymentRouting

func SaveProjectOrGlobalDeploymentRouting(enabled bool) error

SaveProjectOrGlobalDeploymentRouting persists the flag to project settings when present.

func SaveRoutingPolicyJSON

func SaveRoutingPolicyJSON(raw string) error

SaveRoutingPolicyJSON validates and persists routing into provider.json.

func ScheduleBackgroundCatalogRefresh

func ScheduleBackgroundCatalogRefresh(ctx context.Context)

ScheduleBackgroundCatalogRefresh silently refreshes the catalog when it is already stale, or after StaleAfter passes during a long interactive session.

func SetActiveModel

func SetActiveModel(ctx context.Context, modelID string) error

SetActiveModel persists model selection to eyrie provider.json.

func SetActiveProvider

func SetActiveProvider(ctx context.Context, provider string) error

SetActiveProvider persists provider selection to eyrie provider.json.

func SetGlobalSetting

func SetGlobalSetting(key, value string) error

SetGlobalSetting updates a supported scalar/list setting in ~/.hawk/settings.json. Hawk: API keys are NOT stored in settings.json. Use /config and the OS secret store.

func SettingValue

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

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

func ShouldClearSelectionAfterCredentialRemove

func ShouldClearSelectionAfterCredentialRemove(ctx context.Context, removedProvider string) bool

ShouldClearSelectionAfterCredentialRemove reports whether provider/model should reset.

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 StartupCatalogPrefetch

func StartupCatalogPrefetch(ctx context.Context)

StartupCatalogPrefetch refreshes the catalog in the background when the cache needs it.

func SyncProviderConfigFromEnv

func SyncProviderConfigFromEnv() (string, error)

SyncProviderConfigFromEnv re-applies eyrie catalog + env into provider.json (deployments + routing).

func SyncSelectionWithCredentials

func SyncSelectionWithCredentials(ctx context.Context)

SyncSelectionWithCredentials clears stale provider/model when keys are missing.

func TryAutoRefreshCatalog

func TryAutoRefreshCatalog(ctx context.Context) error

TryAutoRefreshCatalog refreshes once when the cache cannot be read (e.g. mid-session).

func ValidateConfig

func ValidateConfig(data map[string]interface{}) []string

ValidateConfig checks that a migrated config has required fields and correct types. Returns a list of warnings (empty list means valid).

func ZshCompletion

func ZshCompletion() string

ZshCompletion returns a zsh completion script for hawk.

Types

type Attribution

type Attribution = types.Attribution

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 CatalogHealth

type CatalogHealth struct {
	CachePath   string
	Exists      bool
	Modified    time.Time
	SizeBytes   int64
	Models      int
	Deployments int
	Offerings   int
	Stale       bool
	StaleAfter  time.Time
	Source      string
	Error       string
}

CatalogHealth summarizes the on-disk eyrie model catalog for doctor / status output.

func CatalogHealthReport

func CatalogHealthReport(ctx context.Context) CatalogHealth

CatalogHealthReport inspects ~/.eyrie/model_catalog.json (or EYRIE_MODEL_CATALOG_PATH).

type CatalogStartupOptions

type CatalogStartupOptions struct {
	ForceRefresh    bool
	SkipAutoRefresh bool
	VerboseOutput   bool // full DiscoverReport; default is one line
}

CatalogStartupOptions controls automatic catalog refresh at hawk startup.

type ConfigTemplate

type ConfigTemplate struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Language    string                 `json:"language"`
	Framework   string                 `json:"framework"`
	Content     map[string]interface{} `json:"content"`
	Files       map[string]string      `json:"files"` // additional files to generate
	Tags        []string               `json:"tags"`
}

ConfigTemplate defines a project configuration template that generates hawk-specific files based on detected project characteristics.

type CredentialInference

type CredentialInference struct {
	ProviderID   string
	DeploymentID string
	EnvVar       string
	DisplayName  string
}

CredentialInference is one eyrie provider match for a pasted API key.

func CredentialInferenceForProvider

func CredentialInferenceForProvider(providerID string) (CredentialInference, error)

CredentialInferenceForProvider returns save metadata for a configured gateway.

func InferCredentialsFromAPIKey

func InferCredentialsFromAPIKey(ctx context.Context, secret string) []CredentialInference

InferCredentialsFromAPIKey delegates provider detection to eyrie from key shape + catalog.

func InferenceFromOption

func InferenceFromOption(opt CredentialProviderOption) CredentialInference

InferenceFromOption converts a provider picker row to persistence metadata.

func LocalCredentialInference

func LocalCredentialInference(providerID string) (CredentialInference, error)

LocalCredentialInference returns setup metadata for no-key providers (e.g. Ollama).

type CredentialProviderOption

type CredentialProviderOption struct {
	ProviderID   string
	DeploymentID string
	EnvVar       string
	DisplayName  string
	Inferred     bool
	RequiresKey  bool
	Rank         int
}

CredentialProviderOption is one eyrie provider row for /config pickers.

type CredentialResolveResult

type CredentialResolveResult struct {
	FormatOK    bool
	FormatError string
	Providers   []CredentialProviderOption
}

CredentialResolveResult is eyrie paste-key resolution (all providers + inferred hints).

func ResolveCredential

func ResolveCredential(ctx context.Context, secret string) CredentialResolveResult

ResolveCredential validates format and lists all providers from eyrie registry.

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 DeploymentRow

type DeploymentRow struct {
	ID         string
	Name       string
	ProviderID string
	Configured bool
	Status     string
	EnvVars    []EnvVarStatus
}

DeploymentRow is one catalog deployment with local credential status.

func ListDeploymentRows

func ListDeploymentRows(ctx context.Context) ([]DeploymentRow, error)

ListDeploymentRows lists catalog deployments and whether hawk can use them now.

type DeveloperPathReport

type DeveloperPathReport struct {
	Checks      []PathCheck
	ChatReady   bool
	SecureReady bool
	Ready       bool
	NextStep    string
}

DeveloperPathReport summarizes developer readiness (setup, security, sandbox, ecosystem).

func EvaluateDeveloperPath

func EvaluateDeveloperPath(ctx context.Context) DeveloperPathReport

EvaluateDeveloperPath builds the developer path readiness report.

type Distribution

type Distribution struct {
	Name        string            `yaml:"name"`
	DisplayName string            `yaml:"display_name"`
	Version     string            `yaml:"version"`
	Provider    DistroProvider    `yaml:"provider"`
	Extensions  []DistroExtension `yaml:"extensions"`
	Branding    DistroBranding    `yaml:"branding"`
	Defaults    DistroDefaults    `yaml:"defaults"`
	Recipes     []string          `yaml:"recipes"`
}

Distribution defines a custom hawk distribution (white-label configuration).

func FindDistribution

func FindDistribution() *Distribution

FindDistribution looks for a distribution config in standard locations.

func LoadDistribution

func LoadDistribution(path string) (*Distribution, error)

LoadDistribution reads a distribution config from a YAML file.

type DistroBranding

type DistroBranding struct {
	Prompt     string `yaml:"prompt"`
	WelcomeMsg string `yaml:"welcome_message"`
	AgentName  string `yaml:"agent_name"`
	Color      string `yaml:"color"`
}

DistroBranding customizes the UI appearance.

type DistroDefaults

type DistroDefaults struct {
	PermissionMode string   `yaml:"permission_mode"`
	AllowedTools   []string `yaml:"allowed_tools"`
	MaxTurns       int      `yaml:"max_turns"`
	SystemPrompt   string   `yaml:"system_prompt"`
}

DistroDefaults sets default behavior.

type DistroExtension

type DistroExtension struct {
	Name    string   `yaml:"name"`
	Command string   `yaml:"command"`
	Args    []string `yaml:"args"`
}

DistroExtension defines a bundled extension.

type DistroProvider

type DistroProvider struct {
	Name   string `yaml:"name"`
	Model  string `yaml:"model"`
	EnvKey string `yaml:"env_key"`
}

DistroProvider configures the default LLM provider.

type EnvManager

type EnvManager struct {
	Vars          map[string]*EnvVar  `json:"vars"`
	Profiles      map[string][]string `json:"profiles"`
	ActiveProfile string              `json:"active_profile"`
	// contains filtered or unexported fields
}

EnvManager manages environment variables, profiles, and secrets.

func NewEnvManager

func NewEnvManager() *EnvManager

NewEnvManager creates a new EnvManager with initialized maps.

func (*EnvManager) Diff

func (em *EnvManager) Diff(other *EnvManager) []string

Diff returns a list of differences between this EnvManager and another.

func (*EnvManager) Export

func (em *EnvManager) Export(format string) string

Export returns the environment variables in the specified format. Supported formats: "env" (KEY=value), "json" (JSON object), "shell" (export KEY=value).

func (*EnvManager) Get

func (em *EnvManager) Get(key string) string

Get returns the value of an environment variable, or empty string if not found.

func (*EnvManager) GetRequired

func (em *EnvManager) GetRequired(key string) (string, error)

GetRequired returns the value of a required environment variable. Returns an error if the variable is not set or is empty.

func (*EnvManager) ListForDisplay

func (em *EnvManager) ListForDisplay() string

ListForDisplay returns a formatted string showing all environment variables. Secret values are partially masked; the source is displayed for each variable.

func (*EnvManager) Load

func (em *EnvManager) Load(sources ...string) error

Load reads environment variables from explicit file sources when provided. By default only the OS environment is used — API keys are not loaded from .env files.

func (*EnvManager) LoadProfile

func (em *EnvManager) LoadProfile(name string) error

LoadProfile activates a named profile, setting its variables as active.

func (*EnvManager) MaskSecrets

func (em *EnvManager) MaskSecrets(text string) string

MaskSecrets replaces known secret values in the given text with "***".

func (*EnvManager) SaveProfile

func (em *EnvManager) SaveProfile(name string, vars []string) error

SaveProfile saves a named profile with the given list of variable keys.

func (*EnvManager) Set

func (em *EnvManager) Set(key, value string, secret bool)

Set sets an environment variable with the given key and value. If secret is true, the value will be masked in display output.

func (*EnvManager) Validate

func (em *EnvManager) Validate() []string

Validate checks that all required variables are set and returns warnings for missing optional but recommended variables.

type EnvVar

type EnvVar struct {
	Key         string `json:"key"`
	Value       string `json:"value"`
	Source      string `json:"source"` // "env", "file", "profile", "default"
	Secret      bool   `json:"secret"`
	Required    bool   `json:"required"`
	Description string `json:"description,omitempty"`
}

EnvVar represents a single environment variable with metadata.

type EnvVarStatus

type EnvVarStatus struct {
	Name string
	Set  bool
}

EnvVarStatus tracks whether an env var is set for a deployment.

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 Migration

type Migration struct {
	FromVersion int
	ToVersion   int
	Description string
	Migrate     func(data map[string]interface{}) (map[string]interface{}, error)
}

Migration represents a single config version upgrade step.

type MigrationRegistry

type MigrationRegistry struct {
	Migrations     []Migration
	CurrentVersion int
}

MigrationRegistry holds all registered migrations and the current target version.

func NewMigrationRegistry

func NewMigrationRegistry() *MigrationRegistry

NewMigrationRegistry returns a registry with all default migrations registered.

func (*MigrationRegistry) Backup

func (r *MigrationRegistry) Backup(configPath string) (string, error)

Backup creates a timestamped backup of the config file before migration. Returns the path to the backup file.

func (*MigrationRegistry) MigrateFile

func (r *MigrationRegistry) MigrateFile(path string) error

MigrateFile reads a config JSON file, checks if migration is needed, creates a backup, applies migrations, and writes the updated config.

func (*MigrationRegistry) NeedsMigration

func (r *MigrationRegistry) NeedsMigration(data map[string]interface{}) bool

NeedsMigration returns true if the config data is at a version below CurrentVersion.

func (*MigrationRegistry) Run

func (r *MigrationRegistry) Run(data map[string]interface{}) (map[string]interface{}, error)

Run applies all relevant migrations sequentially from the config's current version to the registry's CurrentVersion. Each migration is atomic: if one fails, we return the error without applying further migrations.

type ModelConfig

type ModelConfig struct {
	From       string
	Parameters map[string]interface{}
	System     string
	Template   string
	Messages   []ModelMessage
	License    string
	Adapters   []string
}

ModelConfig holds the parsed configuration from a Modelfile.

type ModelMessage

type ModelMessage struct {
	Role    string
	Content string
}

ModelMessage represents a conversation example in a Modelfile.

type ModelOption

type ModelOption struct {
	ID          string
	DisplayName string
}

ModelOption is one hawk /config model row.

func OptionsFromSetupUI

func OptionsFromSetupUI(ui *setup.SetupUI, providerFilter string) []ModelOption

OptionsFromSetupUI builds picker rows; providerFilter limits to one provider.

type ModelPack

type ModelPack struct {
	Name            string                 `json:"name"`
	Description     string                 `json:"description"`
	Models          map[string]ModelRole   `json:"models"`
	DefaultProvider string                 `json:"default_provider"`
	Settings        map[string]interface{} `json:"settings"`
	Tags            []string               `json:"tags"`
	Author          string                 `json:"author"`
}

ModelPack is a named configuration that bundles model + provider + settings for different use cases.

type ModelPackRegistry

type ModelPackRegistry struct {
	Packs      map[string]*ModelPack `json:"packs"`
	ActivePack string                `json:"active_pack"`
	// contains filtered or unexported fields
}

ModelPackRegistry holds all registered packs and tracks the active one.

func NewModelPackRegistry

func NewModelPackRegistry() *ModelPackRegistry

NewModelPackRegistry creates a registry pre-loaded with built-in packs.

func (*ModelPackRegistry) Compare

func (r *ModelPackRegistry) Compare(packA, packB string) string

Compare produces a side-by-side comparison of two packs.

func (*ModelPackRegistry) GetModel

func (r *ModelPackRegistry) GetModel(role string) ModelRole

GetModel returns the ModelRole for the given role from the active pack. If the role is not found, it returns a zero-value ModelRole.

func (*ModelPackRegistry) List

func (r *ModelPackRegistry) List() []*ModelPack

List returns all registered packs sorted by name.

func (*ModelPackRegistry) Load

func (r *ModelPackRegistry) Load() error

Load reads the registry from disk, merging with built-in packs.

func (*ModelPackRegistry) Register

func (r *ModelPackRegistry) Register(pack *ModelPack)

Register adds a new pack to the registry. If a pack with the same name already exists it will be overwritten.

func (*ModelPackRegistry) Save

func (r *ModelPackRegistry) Save() error

Save persists the registry to disk as JSON.

func (*ModelPackRegistry) SetActive

func (r *ModelPackRegistry) SetActive(packName string) error

SetActive switches the active pack. Returns an error if the pack does not exist.

type ModelRole

type ModelRole struct {
	Provider    string  `json:"provider"`
	Model       string  `json:"model"`
	Temperature float64 `json:"temperature"`
	MaxTokens   int     `json:"max_tokens"`
	Purpose     string  `json:"purpose"`
}

ModelRole defines a model configuration for a specific role within a pack.

type ModelfileParser

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

ModelfileParser parses Modelfile DSL content into ModelConfig.

func NewModelfileParser

func NewModelfileParser() *ModelfileParser

NewModelfileParser creates a new ModelfileParser instance.

func (*ModelfileParser) MergeConfigs

func (p *ModelfileParser) MergeConfigs(base, override *ModelConfig) *ModelConfig

MergeConfigs merges override into base. Override takes precedence for same parameters.

func (*ModelfileParser) Parse

func (p *ModelfileParser) Parse(content string) (*ModelConfig, error)

Parse parses Modelfile DSL content and returns a ModelConfig.

func (*ModelfileParser) ParseFile

func (p *ModelfileParser) ParseFile(path string) (*ModelConfig, error)

ParseFile reads a Modelfile from disk and parses it.

func (*ModelfileParser) Render

func (p *ModelfileParser) Render(config *ModelConfig) string

Render converts a ModelConfig back into Modelfile format.

func (*ModelfileParser) ToProviderConfig

func (p *ModelfileParser) ToProviderConfig(config *ModelConfig) map[string]interface{}

ToProviderConfig converts a ModelConfig into an eyrie-compatible provider configuration map.

func (*ModelfileParser) Validate

func (p *ModelfileParser) Validate(config *ModelConfig) []string

Validate checks the ModelConfig for errors and returns a list of issues.

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 PathCheck

type PathCheck struct {
	Section  string
	Name     string
	Status   PathCheckStatus
	Detail   string
	FixHint  string
	Blocking bool
}

PathCheck is one row in the developer path readiness report.

type PathCheckStatus

type PathCheckStatus string

PathCheckStatus is pass, warn, or fail for one readiness row.

const (
	PathPass PathCheckStatus = "pass"
	PathWarn PathCheckStatus = "warn"
	PathFail PathCheckStatus = "fail"
)

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 and Provider are legacy fields read only for one-time migration into eyrie provider.json.
	// Hawk does not persist model/provider here; use SetActiveModel / SetActiveProvider.
	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"`
	DeploymentRouting       *bool                  `json:"deployment_routing,omitempty"` // use catalog deployment router when true / unset + provider.json qualifies
}

Settings holds hawk configuration. Hawk: no API keys stored here. Secrets come from the OS secret store via eyrie.

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 ToggleDeploymentRouting

func ToggleDeploymentRouting(settings Settings) (Settings, bool, error)

ToggleDeploymentRouting flips deployment_routing in global settings.

func (*Settings) UnmarshalJSON

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

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

type SetupState

type SetupState struct {
	HasCredentials bool
	HasModel       bool
	NeedsSetup     bool
	Hint           string
}

SetupState is a single evaluation of first-run /config requirements.

func EvaluateSetup

func EvaluateSetup(ctx context.Context) SetupState

EvaluateSetup loads the OS credential store and reports whether /config is still required.

func EvaluateSetupCached

func EvaluateSetupCached(ctx context.Context) SetupState

EvaluateSetupCached uses the in-memory credential snapshot (fast; for TUI hot paths).

type TemplateRegistry

type TemplateRegistry struct {
	Templates map[string]*ConfigTemplate
	// contains filtered or unexported fields
}

TemplateRegistry manages configuration templates.

func NewTemplateRegistry

func NewTemplateRegistry() *TemplateRegistry

NewTemplateRegistry creates a registry pre-loaded with built-in templates.

func (*TemplateRegistry) DetectAndGenerate

func (r *TemplateRegistry) DetectAndGenerate(projectDir string) (map[string]string, error)

DetectAndGenerate auto-detects the project type from projectDir, selects the best matching template, and generates configs.

func (*TemplateRegistry) Generate

func (r *TemplateRegistry) Generate(templateName string, vars map[string]string) (map[string]string, error)

Generate creates all config files from the named template with variable substitution.

func (*TemplateRegistry) List

func (r *TemplateRegistry) List() []*ConfigTemplate

List returns all registered templates sorted by name.

func (*TemplateRegistry) Preview

func (r *TemplateRegistry) Preview(templateName string, vars map[string]string) string

Preview shows what files would be generated without writing them.

func (*TemplateRegistry) Register

func (r *TemplateRegistry) Register(template *ConfigTemplate)

Register adds a new template to the registry.

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