// Package config loads and validates YAML configuration for odidere. package config import ( "fmt" "net/url" "os" "regexp" "time" "gopkg.in/yaml.v3" ) // TTS holds the configuration for TTS. type TTS struct { // URL is the base URL of kokoro-fastapi. // For example, "http://localhost:8880". URL string `yaml:"url"` // Voice is the default voice ID to use (e.g., "af_heart"). Voice string `yaml:"voice"` // Timeout is the maximum duration for a synthesis request. // Defaults to 60s if zero. Timeout time.Duration `yaml:"timeout"` } func (cfg TTS) Validate() error { if cfg.URL == "" { return fmt.Errorf("missing URL") } if _, err := url.Parse(cfg.URL); err != nil { return fmt.Errorf("invalid URL %q: %w", cfg.URL, err) } if cfg.Voice == "" { return fmt.Errorf("missing voice") } if cfg.Timeout < 0 { return fmt.Errorf("invalid timeout %v: must not be negative", cfg.Timeout) } return nil } // Database holds the SQLite database configuration. type Database struct { // Path is the filesystem path to the SQLite database file. Path string `yaml:"path"` } func (cfg Database) Validate() error { if cfg.Path == "" { return fmt.Errorf("missing path") } return nil } // STT holds the configuration for the frontend-facing speech-to-text server. type STT struct { // URL is the base URL of the whisper-server. // For example, "http://localhost:8178". URL string `yaml:"url"` } func (cfg STT) Validate() error { if cfg.URL == "" { return fmt.Errorf("missing URL") } if _, err := url.Parse(cfg.URL); err != nil { return fmt.Errorf("invalid URL %q: %w", cfg.URL, err) } return nil } // ProviderConfig holds the configuration for a single LLM provider. type ProviderConfig struct { // Name uniquely identifies this provider (e.g., "llama.cpp", "openrouter"). Name string `yaml:"name"` // URL is the base URL of the OpenAI-compatible API endpoint. URL string `yaml:"url"` // Key is the API key for authentication. Key string `yaml:"key"` // Timeout is the maximum duration for a query (e.g., "5m"). // Defaults to 5 minutes if zero. Timeout time.Duration `yaml:"timeout"` // Models is an optional whitelist of model IDs for this provider. Models []string `yaml:"models,omitempty"` } func (cfg ProviderConfig) Validate() error { if cfg.Name == "" { return fmt.Errorf("missing name") } if cfg.URL == "" { return fmt.Errorf("missing URL") } if _, err := url.Parse(cfg.URL); err != nil { return fmt.Errorf("invalid URL %q: %w", cfg.URL, err) } if cfg.Timeout < 0 { return fmt.Errorf("invalid timeout %v: must not be negative", cfg.Timeout) } return nil } // ModelConfig specifies the provider and model to use. type ModelConfig struct { // Provider is the provider name (e.g., "llama.cpp"). Provider string `yaml:"provider,omitempty"` // Model is the model ID within that provider (e.g., "qwen3.6-27b"). Model string `yaml:"model,omitempty"` } // JobConfig holds the user-facing configuration for a job. type JobConfig struct { // MaxIterations caps the number of agent loop iterations. MaxIterations int `yaml:"max_iterations,omitempty"` // Name uniquely identifies the job within the config. Name string `yaml:"name"` // Model is the optional model for this job. Model ModelConfig `yaml:"model,omitempty"` // Schedule is a cron expression (e.g., "0 9 * * *"). Schedule string `yaml:"schedule"` // SystemMessage overrides the global system message for this job. SystemMessage string `yaml:"system_message,omitempty"` // Task is the user-level instruction to give the LLM. Task string `yaml:"task"` // Timeout limits the job execution time (e.g., "10m"). Timeout time.Duration `yaml:"timeout,omitempty"` // UserId identifies the user that owns conversations created by this job. UserId string `yaml:"user_id,omitempty"` } func (cfg JobConfig) Validate() error { if cfg.Name == "" { return fmt.Errorf("missing name") } if cfg.Task == "" { return fmt.Errorf("missing task") } if cfg.Schedule == "" { return fmt.Errorf("missing schedule") } if cfg.MaxIterations < 0 { return fmt.Errorf("max_iterations must be non-negative") } if cfg.Timeout < 0 { return fmt.Errorf("invalid timeout %v: must not be negative", cfg.Timeout) } if cfg.UserId == "" { return fmt.Errorf("missing user_id") } return nil } // ToolConfig represents an external tool definition. type ToolConfig struct { // Name uniquely identifies the tool within a registry. Name string `yaml:"name"` // Description explains the tool's purpose for the LLM. Description string `yaml:"description"` // Command is the executable path or name. Command string `yaml:"command"` // Arguments defines the arguments passed to Command when the LLM calls // this tool. Each entry is a Go text/template template evaluated with the // JSON object supplied by the LLM. // // For example, this configuration: // // arguments: // - "--message" // - "{{.message}}" // - "{{if .verbose}}--verbose{{end}}" // // combines with these tool-call arguments: // // {"message":"hello world","verbose":true} // // to run Command with: // // []string{"--message", "hello world", "--verbose"} // // Each configured entry becomes one element of that []string. Spaces in // "hello world" do not divide it into separate arguments. If verbose were // false, its template would produce an empty string, and ParseArguments // would leave that entry out, resulting in: // // []string{"--message", "hello world"} // // Template output is passed directly to the program. It is not interpreted // by a shell. Each entry in Arguments adds either zero or one element to // the argument vector, regardless of the type of the value it renders. // // For example, suppose Command is "cat", Arguments contains: // // - "{{.files}}" // // and the tool-call JSON is: // // {"files":["one.txt","two.txt"]} // // The program is invoked with: // // []string{"cat", "[one.txt two.txt]"} // // This asks cat to read one file named "[one.txt two.txt]". It does not // produce the following argument vector, which would ask cat to read two // files: // // []string{"cat", "one.txt", "two.txt"} // // Note that templates may accept missing values without reporting an // error. For example, suppose Command is "echo", Arguments contains: // // - "--message" // - "{{.message}}" // // and the tool-call JSON is {}. The program is invoked with: // // []string{"echo", "--message", ""} // // The missing message is therefore passed to echo as the text // ""; it does not cause the tool call to fail. // // Each template is compiled when the tool is constructed, so a template // syntax error is reported at configuration load, not on the tool's // first call. // // See https://pkg.go.dev/text/template. Arguments []string `yaml:"arguments"` // Parameters is the JSON Schema included in the tool definition sent to // the LLM. It describes the values the LLM should provide when calling the // tool, including their names, types, and which values are required. // // The schema is not used to validate a tool call before Arguments is // evaluated. For example, if Parameters requires "message" but the LLM // supplies {}, evaluation continues without first reporting that // "message" is missing. Values that do not have the types described by the // schema may likewise reach the argument templates. Parameters map[string]any `yaml:"parameters"` // Timeout limits execution time (e.g., "30s", "5m"). Zero means no limit. Timeout time.Duration `yaml:"timeout"` } func (cfg ToolConfig) Validate() error { if cfg.Name == "" { return fmt.Errorf("missing name") } if cfg.Description == "" { return fmt.Errorf("missing description") } if cfg.Command == "" { return fmt.Errorf("missing command") } if cfg.Timeout < 0 { return fmt.Errorf("invalid timeout %v: must not be negative", cfg.Timeout) } return nil } // Config holds all application configuration sections. type Config struct { // Address is the host:port to listen on. Address string `yaml:"address"` // Database configures the SQLite database path. Database Database `yaml:"database"` // ShutdownTimeout is the maximum time to wait for graceful shutdown. ShutdownTimeout time.Duration `yaml:"shutdown_timeout"` // SystemMessage is the default system prompt prepended to all conversations. SystemMessage string `yaml:"system_message"` // DefaultModel specifies the default provider and model. DefaultModel ModelConfig `yaml:"default_model"` // Providers defines the available LLM providers. Providers []ProviderConfig `yaml:"providers"` // STT configures the speech-to-text server URL passed to the frontend. STT STT `yaml:"stt"` // Jobs defines scheduled autonomous tasks. Jobs []JobConfig `yaml:"jobs"` // Tools defines external commands available to the LLM. Tools []ToolConfig `yaml:"tools"` // TTS configures the text-to-speech client. TTS TTS `yaml:"tts"` } // ApplyDefaults sets default values for optional configuration fields. func (cfg *Config) ApplyDefaults() { if cfg.ShutdownTimeout == 0 { cfg.ShutdownTimeout = 30 * time.Second } if cfg.Address == "" { cfg.Address = ":8080" } } // Validate checks that all required fields are present and valid. func (cfg *Config) Validate() error { if cfg.Address == "" { return fmt.Errorf("address required") } if err := cfg.Database.Validate(); err != nil { return fmt.Errorf("invalid database config: %w", err) } if cfg.DefaultModel.Provider == "" { return fmt.Errorf("default_model.provider required") } if cfg.DefaultModel.Model == "" { return fmt.Errorf("default_model.model required") } if len(cfg.Providers) == 0 { return fmt.Errorf("at least one provider required") } for i, p := range cfg.Providers { if err := p.Validate(); err != nil { return fmt.Errorf("providers[%d] invalid: %w", i, err) } } if err := cfg.STT.Validate(); err != nil { return fmt.Errorf("invalid stt config: %w", err) } if err := cfg.TTS.Validate(); err != nil { return fmt.Errorf("invalid tts config: %w", err) } if cfg.ShutdownTimeout < 0 { return fmt.Errorf("invalid shutdown_timeout %v: must not be negative", cfg.ShutdownTimeout) } for i, jc := range cfg.Jobs { if err := jc.Validate(); err != nil { return fmt.Errorf("jobs[%d] invalid: %w", i, err) } } for i, tc := range cfg.Tools { if err := tc.Validate(); err != nil { return fmt.Errorf("tools[%d] invalid: %w", i, err) } } return nil } // Load reads a YAML configuration file, expands environment variables, // applies defaults, and validates the result. func Load(path string) (*Config, error) { data, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("read file: %w", err) } // Expand environment variables. re := regexp.MustCompile(`\$\{([^}]+)\}`) expanded := re.ReplaceAllStringFunc(string(data), func(match string) string { v := match[2 : len(match)-1] return os.Getenv(v) }) var cfg Config if err := yaml.Unmarshal([]byte(expanded), &cfg); err != nil { return nil, fmt.Errorf("parse config: %w", err) } cfg.ApplyDefaults() if err := cfg.Validate(); err != nil { return nil, fmt.Errorf("invalid config: %v", err) } return &cfg, nil }