// Package setup runs archied's first-run configuration flow and returns the // TOML edits to persist it. package setup import ( "context" "crypto/rand" "encoding/hex" "fmt" "strings" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/infrastructure/configuration" "github.com/samcharles93/archie-core/internal/infrastructure/configuration/tomlwrite" "github.com/samcharles93/archie-core/internal/infrastructure/postgres" ) // SecretSink receives the secret values setup collects. Put buffers; the // caller commits once the generated config is proven loadable. type SecretSink interface { // Put records that key (as looked up through engine) must resolve to // value once Commit is called. Put(engine, key, value string) error // Commit persists everything Put has recorded so far. Commit() error } // ModelDiscovery finds locally available models for the self-hosted // provider path. A nil ModelDiscovery, or one that returns an error, // degrades to a free-text model name -- discovery is a convenience, not a // requirement. type ModelDiscovery interface { ListOllamaModels(ctx context.Context) ([]string, error) } // ExistingValues prefills prompts on a re-run. The zero value is correct // for a fresh install. type ExistingValues struct { BotUser string Operator string ForgeHost string DatabaseURL string } // tableEdits groups pending edits by table before Run flattens them into // []tomlwrite.Edit, so a step can build "everything for [forge]" as one // value and let Run decide the flattening order. type tableEdits = map[string]map[string]string // Params pre-answers setup questions; a step prompts only for unset fields. // Provider is a config class; Model is the bare model name. type Params struct { DatabaseURL string BotUser string Operator string ForgeType string // github | gitea | none ForgeHost string Provider string // a name from ProviderNames: the provider the model alias names Model string // bare model name; the step adds the "provider/" prefix // TelegramUserIDs non-empty configures Telegram. The reference fields name // already-stored secrets as engine:key; when set, the step writes the // reference without prompting. ForgeTokenRef config.SecretRef ProviderAPIKeyRef config.SecretRef TelegramTokenRef config.SecretRef TelegramUserIDs []int64 // Secret values are never parameters; they come from a prompt through // SecretSink. } // RunParams drives the setup flow with the question sites pre-answered from params. A zero // Params behaves exactly like Run. func RunParams(ctx context.Context, p Prompter, discovery ModelDiscovery, secrets SecretSink, existing ExistingValues, params Params) ([]tomlwrite.Edit, error) { var edits []tomlwrite.Edit add := func(all tableEdits) { for table, kv := range all { for k, v := range kv { edits = append(edits, tomlwrite.Edit{Table: table, Key: k, Value: v}) } } } dbURL, migrationURL, err := stepDatabase(ctx, p, secrets, existing.DatabaseURL, params.DatabaseURL) if err != nil { return nil, err } dbEdits := tableEdits{"": {"database_url": tomlwrite.String(dbURL)}} if migrationURL != "" { dbEdits[""]["migration_database_url"] = tomlwrite.String(migrationURL) } add(dbEdits) botUser := params.BotUser if strings.TrimSpace(botUser) == "" { var err error botUser, err = p.ReadLine(ctx, "Bot user (forge username for archied's commits and API calls): ", existing.BotUser) if err != nil { return nil, fmt.Errorf("setup: bot user: %w", err) } } if strings.TrimSpace(botUser) == "" { return nil, fmt.Errorf("setup: bot user is required") } add(tableEdits{"": {"bot_user": tomlwrite.String(botUser)}}) operator := params.Operator if strings.TrimSpace(operator) == "" { var err error operator, err = p.ReadLine(ctx, "Operator display name (shown to the chat agent; blank to skip): ", existing.Operator) if err != nil { return nil, fmt.Errorf("setup: operator: %w", err) } } if strings.TrimSpace(operator) != "" { add(tableEdits{"chat": {"operator": tomlwrite.String(operator)}}) } providerEdits, model, err := stepProvider(ctx, p, discovery, secrets, params) if err != nil { return nil, err } add(providerEdits) add(tableEdits{"models": {config.DefaultModelAlias: tomlwrite.String(model)}}) forgeEdits, err := stepForge(ctx, p, secrets, existing.ForgeHost, params) if err != nil { return nil, err } add(forgeEdits) chatEdits, err := stepChat(ctx, p, secrets, params) if err != nil { return nil, err } add(chatEdits) return edits, nil } // stepDatabase returns the PostgreSQL URLs the install serves from: the // runtime role's URL and, for the bundled database, the migration role's. A // blank answer on a fresh install means the bundled database. On a re-run with // an existing URL the bundled database is an explicit choice rather than // something reachable only by typing its socket URL; keeping the existing URL // is the first option, so the default answer is unchanged. func stepDatabase(ctx context.Context, p Prompter, secrets SecretSink, existing, param string) (runtimeURL, migrationURL string, err error) { if strings.TrimSpace(param) != "" { return param, "", nil } if strings.TrimSpace(existing) != "" { choice, err := p.Select(ctx, "Database:", []string{ "Keep the existing database URL", "Bundled database (Unix socket, generated password in the env file)", "Enter a different PostgreSQL 18 URL", }) if err != nil { return "", "", fmt.Errorf("setup: database choice: %w", err) } switch choice { case 0: return existing, "", nil case 1: return bundledDatabase(secrets) default: url, err := p.ReadLine(ctx, "PostgreSQL 18 URL: ", "") if err != nil { return "", "", fmt.Errorf("setup: database url: %w", err) } if strings.TrimSpace(url) == "" { // A blank answer keeps the existing URL, as it always has. return existing, "", nil } return url, "", nil } } prompt := "PostgreSQL 18 URL (blank for the bundled database with a generated password): " url, err := p.ReadLine(ctx, prompt, "") if err != nil { return "", "", fmt.Errorf("setup: database url: %w", err) } if strings.TrimSpace(url) != "" { return url, "", nil } return bundledDatabase(secrets) } // bundledDatabase switches to the bundled database: no network, reached // through its Unix socket. The services connect as the least-privilege runtime // role and migrations run as the schema-owning migration role; one generated // password goes only to the env file as PGPASSWORD, which pgx reads for both // passwordless URLs, so config.toml holds no secret. The superuser credential // the bundled server is created with lives in the installer's Compose-only // env file, never here. func bundledDatabase(secrets SecretSink) (runtimeURL, migrationURL string, err error) { pw := make([]byte, 24) if _, err := rand.Read(pw); err != nil { return "", "", fmt.Errorf("setup: generate database password: %w", err) } password := hex.EncodeToString(pw) if err := secrets.Put("env", "PGPASSWORD", password); err != nil { return "", "", fmt.Errorf("setup: store database password: %w", err) } socket := configuration.DefaultPostgresSocketDir() return "postgres://" + postgres.RuntimeRole + "@/archie?host=" + socket, "postgres://" + postgres.MigrationRole + "@/archie?host=" + socket, nil }