Files
odidere/internal/config/config.go
T

367 lines
11 KiB
Go
Raw Normal View History

2026-02-13 15:03:02 +00:00
// Package config loads and validates YAML configuration for odidere.
package config
import (
"fmt"
2026-06-19 14:31:41 +00:00
"net/url"
2026-02-13 15:03:02 +00:00
"os"
"regexp"
"time"
"gopkg.in/yaml.v3"
)
2026-06-13 18:55:16 +00:00
// 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.
2026-09-25 18:26:54 +00:00
// Defaults to 60s if zero.
Timeout time.Duration `yaml:"timeout"`
2026-06-13 18:55:16 +00:00
}
func (cfg TTS) Validate() error {
if cfg.URL == "" {
return fmt.Errorf("missing URL")
}
2026-06-19 14:31:41 +00:00
if _, err := url.Parse(cfg.URL); err != nil {
return fmt.Errorf("invalid URL %q: %w", cfg.URL, err)
}
2026-06-13 18:55:16 +00:00
if cfg.Voice == "" {
return fmt.Errorf("missing voice")
}
2026-09-25 18:26:54 +00:00
if cfg.Timeout < 0 {
return fmt.Errorf("invalid timeout %v: must not be negative", cfg.Timeout)
2026-06-13 18:55:16 +00:00
}
return nil
}
2026-09-20 12:27:03 +00:00
// 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
}
2026-06-15 10:51:17 +00:00
// 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")
}
2026-06-19 14:31:41 +00:00
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").
2026-09-25 18:26:54 +00:00
// Defaults to 5 minutes if zero.
Timeout time.Duration `yaml:"timeout"`
2026-06-19 14:31:41 +00:00
// 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)
}
2026-09-25 18:26:54 +00:00
if cfg.Timeout < 0 {
return fmt.Errorf("invalid timeout %v: must not be negative", cfg.Timeout)
2026-06-19 14:31:41 +00:00
}
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").
2026-09-25 18:26:54 +00:00
Timeout time.Duration `yaml:"timeout,omitempty"`
2026-09-20 12:27:03 +00:00
// UserId identifies the user that owns conversations created by this job.
UserId string `yaml:"user_id,omitempty"`
2026-06-19 14:31:41 +00:00
}
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")
}
2026-09-25 18:26:54 +00:00
if cfg.Timeout < 0 {
return fmt.Errorf("invalid timeout %v: must not be negative", cfg.Timeout)
}
2026-09-26 17:20:32 +00:00
if cfg.UserId == "" {
return fmt.Errorf("missing user_id")
}
2026-09-20 12:27:03 +00:00
2026-06-19 14:31:41 +00:00
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"`
2026-09-25 18:26:54 +00:00
// 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", "<no value>"}
//
// The missing message is therefore passed to echo as the text
// "<no value>"; 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.
2026-06-19 14:31:41 +00:00
Arguments []string `yaml:"arguments"`
2026-09-25 18:26:54 +00:00
// 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.
2026-06-19 14:31:41 +00:00
Parameters map[string]any `yaml:"parameters"`
2026-09-25 18:26:54 +00:00
// Timeout limits execution time (e.g., "30s", "5m"). Zero means no limit.
Timeout time.Duration `yaml:"timeout"`
2026-10-06 12:08:12 +00:00
// RequiresApproval specifies whether a tool must be approved by a user
// to execute.
RequiresApproval bool `yaml:"require_approval,omitempty"`
2026-06-19 14:31:41 +00:00
}
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")
}
2026-09-25 18:26:54 +00:00
if cfg.Timeout < 0 {
return fmt.Errorf("invalid timeout %v: must not be negative", cfg.Timeout)
2026-06-19 14:31:41 +00:00
}
2026-06-15 10:51:17 +00:00
return nil
}
2026-02-13 15:03:02 +00:00
// Config holds all application configuration sections.
type Config struct {
// Address is the host:port to listen on.
Address string `yaml:"address"`
2026-09-20 12:27:03 +00:00
// Database configures the SQLite database path.
Database Database `yaml:"database"`
2026-02-13 15:03:02 +00:00
// ShutdownTimeout is the maximum time to wait for graceful shutdown.
2026-09-25 18:26:54 +00:00
ShutdownTimeout time.Duration `yaml:"shutdown_timeout"`
2026-06-19 14:31:41 +00:00
// 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"`
2026-06-15 10:51:17 +00:00
// STT configures the speech-to-text server URL passed to the frontend.
STT STT `yaml:"stt"`
2026-06-02 12:03:15 +00:00
// Jobs defines scheduled autonomous tasks.
2026-06-19 14:31:41 +00:00
Jobs []JobConfig `yaml:"jobs"`
2026-02-13 15:03:02 +00:00
// Tools defines external commands available to the LLM.
2026-06-19 14:31:41 +00:00
Tools []ToolConfig `yaml:"tools"`
2026-02-13 15:03:02 +00:00
// TTS configures the text-to-speech client.
2026-06-13 18:55:16 +00:00
TTS TTS `yaml:"tts"`
2026-02-13 15:03:02 +00:00
}
// ApplyDefaults sets default values for optional configuration fields.
func (cfg *Config) ApplyDefaults() {
2026-09-25 18:26:54 +00:00
if cfg.ShutdownTimeout == 0 {
cfg.ShutdownTimeout = 30 * time.Second
2026-02-13 15:03:02 +00:00
}
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")
}
2026-09-20 12:27:03 +00:00
if err := cfg.Database.Validate(); err != nil {
return fmt.Errorf("invalid database config: %w", err)
}
2026-06-19 14:31:41 +00:00
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)
}
2026-02-13 15:03:02 +00:00
}
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)
}
2026-09-25 18:26:54 +00:00
if cfg.ShutdownTimeout < 0 {
return fmt.Errorf("invalid shutdown_timeout %v: must not be negative", cfg.ShutdownTimeout)
2026-02-13 15:03:02 +00:00
}
2026-06-02 12:03:15 +00:00
for i, jc := range cfg.Jobs {
if err := jc.Validate(); err != nil {
return fmt.Errorf("jobs[%d] invalid: %w", i, err)
}
}
2026-06-19 14:31:41 +00:00
for i, tc := range cfg.Tools {
if err := tc.Validate(); err != nil {
2026-02-13 15:03:02 +00:00
return fmt.Errorf("tools[%d] invalid: %w", i, err)
}
}
return nil
}
// Load reads a YAML configuration file, expands environment variables,
2026-06-19 14:31:41 +00:00
// applies defaults, and validates the result.
2026-02-13 15:03:02 +00:00
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(`\$\{([^}]+)\}`)
2026-06-19 14:31:41 +00:00
expanded := re.ReplaceAllStringFunc(string(data), func(match string) string {
v := match[2 : len(match)-1]
return os.Getenv(v)
})
2026-02-13 15:03:02 +00:00
var cfg Config
if err := yaml.Unmarshal([]byte(expanded), &cfg); err != nil {
return nil, fmt.Errorf("parse config: %w", err)
}
2026-06-19 14:31:41 +00:00
cfg.ApplyDefaults()
2026-02-13 15:03:02 +00:00
if err := cfg.Validate(); err != nil {
return nil, fmt.Errorf("invalid config: %v", err)
}
return &cfg, nil
}