Files
audita/internal/appconfig/config.go

187 lines
6.3 KiB
Go
Raw Permalink Normal View History

// Package appconfig composes Audita and PromptKit configuration sources.
package appconfig
import (
"context"
"errors"
"fmt"
"path/filepath"
"sort"
"strings"
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig/sharedglossary"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema"
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
ck "go.maximumdirect.net/configkit"
pk "go.maximumdirect.net/promptkit"
)
// AssetError reports a failure to access an embedded application resource.
type AssetError struct{ Err error }
func (e *AssetError) Error() string { return e.Err.Error() }
func (e *AssetError) Unwrap() error { return e.Err }
func IsAssetError(err error) bool {
var target *AssetError
return errors.As(err, &target)
}
// Config combines Audita's root settings with native PromptKit settings.
type Config struct {
Application config.Config `yaml:",inline"`
PromptKit pk.Settings `yaml:"promptkit"`
}
type Options struct {
Overlay string
Overrides []ck.Override
GlossaryFiles []string
}
type Acquisition struct {
*ck.Result[Config]
GlossarySources []string
}
// GlossaryInputError identifies failures in the separate runtime input load.
type GlossaryInputError struct{ Err error }
func (e *GlossaryInputError) Error() string { return e.Err.Error() }
func (e *GlossaryInputError) Unwrap() error { return e.Err }
const operatorImports = `config:
imports:
- path: prompts.yml
required: false
- dir: prompts
required: false
recursive: true
pattern: ["*.yml", "*.yaml"]
`
// Definition combines application rules with PromptKit's native rules.
func Definition() ck.Definition[Config] {
domain := config.Definition()
definition := ck.Definition[Config]{
Defaults: func() Config { return Config{Application: domain.Defaults()} },
Version: domain.Version,
SequenceIdentities: domain.SequenceIdentities,
Sensitive: domain.Sensitive,
Resolve: func(value *Config, resolution *ck.Resolution) error {
return domain.Resolve(&value.Application, resolution)
},
Validate: func(value *Config, validation *ck.Validation) {
domain.Validate(&value.Application, validation)
},
}
return pk.Configure(definition, func(value *Config) *pk.Settings { return &value.PromptKit })
}
// Load composes built-in resources and optional companions with the selected input.
func Load(ctx context.Context, input ck.Input, options Options) (*Acquisition, *ck.SecretsReport, error) {
if err := ctx.Err(); err != nil {
return nil, nil, err
}
report, prepared, err := ck.LoadSecretsIntoEnvironmentFromConfig(input.Source, ck.SecretsFromConfigOptions{Filesystem: input.Filesystem})
if canceled := ctx.Err(); canceled != nil {
return nil, report, errors.Join(err, canceled)
}
if err != nil {
return nil, report, err
}
input.Source = prepared
var glossarySources []string
overrides := append([]ck.Override(nil), options.Overrides...)
if len(options.GlossaryFiles) > 0 {
inputs := make([]ck.Input, len(options.GlossaryFiles))
for i, path := range options.GlossaryFiles {
absolute, err := filepath.Abs(path)
if err != nil {
return nil, report, &GlossaryInputError{Err: err}
}
inputs[i] = ck.Input{Source: ck.File(absolute), Imports: true}
}
glossaries, err := sharedglossary.Load(ctx, inputs)
if canceled := ctx.Err(); canceled != nil {
return nil, report, errors.Join(err, canceled)
}
if err != nil {
return nil, report, &GlossaryInputError{Err: err}
}
for _, source := range glossaries.Sources() {
if source.Kind == ck.SourceKindFile {
glossarySources = append(glossarySources, source.Path)
}
}
collections := glossaries.Config["collections"].(map[string]any)
projected := make(map[string]any, len(collections))
for name, value := range collections {
collection := value.(map[string]any)
projected[name] = map[string]any{"entries": collection["entries"]}
}
overrides = append(overrides, glossaryOverrides(projected, options.Overrides)...)
}
embedded, err := pk.FilesystemInputs("Audita embedded prompts", prompts.Filesystem(), prompts.AssetRoot)
if err != nil {
return nil, report, &AssetError{Err: fmt.Errorf("discover embedded prompts: %w", err)}
}
for i := range embedded {
embedded[i].Destination = ck.Keys("promptkit")
}
schemas := ck.NewFilesystem("Audita embedded schemas", responseschema.Filesystem())
embedded = append(embedded, ck.Input{
Source: pk.SchemaRootSource("Audita embedded schemas", responseschema.AssetRoot),
Destination: ck.Keys("promptkit"),
Filesystem: &ck.FilesystemContext{FS: &schemas, Root: ".", BaseDir: "."},
})
input.Imports = true
result, err := ck.LoadLayered(input, ck.LayeredOptions[Config]{
Definition: Definition(),
Overlay: options.Overlay,
Overrides: overrides,
Underlays: []ck.Underlay{
pk.BundledOpenRouterUnderlay(),
{Inputs: embedded},
{Inputs: []ck.Input{
{Source: ck.Bytes("Audita automatic prompt imports", []byte(operatorImports)), Destination: ck.Keys("promptkit"), Imports: true, MainRelative: ck.MainRelative()},
}},
},
})
if canceled := ctx.Err(); canceled != nil {
return nil, report, errors.Join(err, canceled)
}
if err != nil {
return nil, report, err
}
return &Acquisition{Result: result, GlossarySources: glossarySources}, report, nil
}
func glossaryOverrides(projected map[string]any, supplied []ck.Override) []ck.Override {
if len(projected) == 0 {
return nil
}
root := ck.Keys("glossary_collections")
for _, override := range supplied {
path := override.Path.String()
if path != root.String() && !strings.HasPrefix(path, root.String()+"/") {
continue
}
// Only split when caller overrides need to share this namespace. The
// usual batch keeps one native record regardless of collection count.
names := make([]string, 0, len(projected))
for name := range projected {
names = append(names, name)
}
sort.Strings(names)
result := make([]ck.Override, 0, len(names))
for _, name := range names {
entries := projected[name].(map[string]any)["entries"]
result = append(result, ck.Override{Path: root.Key(name).Key("entries"), Value: entries, Flag: "--glossary-file"})
}
return result
}
return []ck.Override{{Path: root, Value: projected, Flag: "--glossary-file"}}
}