Files
archie/cmd/archied/telegram_setup.go
T
sam c66c0a2a38 refactor(config): move loading into infrastructure/configuration
internal/config both defined the types every package imports and performed
the file I/O to produce them. Importing a settings struct therefore pulled
in a TOML decoder and a YAML decoder, and the shared model owned discovery,
decoding, overlays, defaulting and validation all at once. See
docs/architecture/configuration.md, which requires loading to move out and
internal/config to be dissolved.

internal/config is now types only -- no os, no filepath, no toml. The new
package owns loading, one concern per file:

  features.go    the closed set of recognised feature files
  discovery.go   directory scan and classification
  decode.go      TOML/YAML decoding, format dispatch
  defaults.go    filling absent values, no errors
  validate.go    judging supplied values, no mutation
  provenance.go  which file contributed what
  loader.go      Loader wiring the above; File/Overlay/Dir

Beyond relocating, this fixes what the old code conflated:

  - Defaulting and validation were interleaved. applyAgentDefaults and
    applyDispatchDefaults returned validation errors; validateContainers and
    validateSingleIdentity quietly mutated the config. There was no point at
    which you could see what the operator actually supplied. They are now
    separate passes: applyDefaults never fails, validate never writes.
  - Errors were fmt.Errorf strings prefixed "config: ", so a caller could not
    distinguish operator-fixable input from an unreadable file without
    matching message text. Five sentinels now carry that distinction.
  - dataHome() read XDG_DATA_HOME directly and discarded the error from
    os.UserHomeDir, so defaulting could not be tested without the
    environment. It is injectable on Loader and no longer swallows the error.
  - Nothing recorded where a value came from. With overlays, feature files
    and conf.d/ all able to set the same field, "which file set this?" was
    answerable only by re-deriving precedence by hand. Provenance records it.
  - Feature files were applied in map iteration order, making load order and
    any resulting error arbitrary. Discovery now returns them sorted.
  - loadMainConfig reported "no config.yaml or config.toml found in %s" with
    an empty string: the directory was lost when it was extracted from
    loadDirInto, so the error named no directory.
  - Unreadable or malformed conf.d/ extras were skipped silently, which
    presents as a setting the operator wrote simply not taking effect.
  - Decode errors from the main config were returned bare, without naming
    the file that failed to parse.

The 40 loader tests moved with the code and their assertions are unchanged,
so the defaulting and validation rewrite is behaviour-preserving.

Document.Config is the temporary seam: still internal/config.Config, named
as a field so the compromise is visible at each use site, with its deletion
condition recorded in doc.go. Building typed per-domain sections now, while
every consumer still reads config.Config, would mean two shapes kept in sync
by hand with no consumer for the new one; that belongs with the dissolution
work, not ahead of it.

No consumer outside cmd/archied changed.

Verified: go build, go vet, gofmt clean; go test ./internal/config/... and
./internal/infrastructure/configuration/... pass. Pre-existing gateway and
telegram failures are unchanged.
2026-07-29 11:07:41 +10:00

230 lines
8.3 KiB
Go

package main
import (
"context"
"fmt"
"log/slog"
"os"
"path/filepath"
"strings"
"time"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/ai-sdk/runtime"
"github.com/samcharles93/archie-core/internal/channels/telegram"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
"github.com/samcharles93/archie-core/internal/nell"
"github.com/samcharles93/archie-core/internal/releaseannounce"
"github.com/samcharles93/archie-core/internal/releaseupdate"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/tools"
)
// telegramSetup contains the inputs needed to initialise the Telegram
// chat gateway. Every field is intentionally explicit so the function
// signature acts as a contract of what the gateway depends on.
type telegramSetup struct {
Cfg config.Config
CfgPath string
OverlayPath string
St store.TaskStore
LLM *runtime.Runtime
ChatModels gateway.ModelManager
ToolReg *tools.Registry
Personas *gateway.PersonaRegistry
ChatTasks gateway.TaskCreator
ChatController gateway.TaskController
DefaultChatIdentity string
Log *slog.Logger
}
// setupTelegramGateway initialises the Telegram chat gateway when a
// token is configured. It returns a start function (nil when no token
// is configured) and ok=false to signal the caller must exit early.
func setupTelegramGateway(ctx context.Context, s telegramSetup) (start func(), ok bool) {
if s.Cfg.Chat.Telegram.TokenEnv == "" {
return nil, true
}
tgToken := os.Getenv(s.Cfg.Chat.Telegram.TokenEnv)
if tgToken == "" {
s.Log.Error("chat.telegram configured but token env var is empty", "env", s.Cfg.Chat.Telegram.TokenEnv)
return nil, false
}
if len(s.Cfg.Chat.Telegram.AllowedUserIDs) == 0 {
s.Log.Warn("chat.telegram has no allowed_user_ids: every sender will be rejected. " +
"Add your Telegram user id to chat.telegram.allowed_user_ids to enable the bot.")
}
tg := telegram.New(tgToken, "", "", s.Cfg.Chat.Telegram.AllowedUserIDs, s.Log)
tg.Version = func() string {
return fmt.Sprintf("Archie\nGateway: %s\nRuntime: %s", gatewayVersion, runtimeVersion)
}
configureTelegramUpdates(tg, s)
tg.ReleaseAnnouncements = &releaseannounce.Announcer{
StatePath: releaseAnnouncementStatePath(s.Cfg.WorkDir, s.Cfg.BotUser),
Components: []releaseannounce.Component{
{ID: "gateway", Label: "THE GATEWAY", Version: gatewayVersion, ChangelogPath: packagedGatewayChangelogPath},
{ID: "runtime", Label: "THE RUNTIME", Version: runtimeVersion, ChangelogPath: packagedRuntimeChangelogPath},
},
}
tg.Reload = makeTelegramReload(s)
sessionStore := makeTelegramSessionStore(s)
router := buildTelegramRouter(ctx, tg, s, sessionStore)
return func() {
go func() {
if err := tg.Start(ctx, router); err != nil && ctx.Err() == nil {
s.Log.Error("telegram gateway stopped", "err", err)
}
}()
s.Log.Info("telegram gateway started")
}, true
}
func configureTelegramUpdates(tg *telegram.Gateway, s telegramSetup) {
if len(s.Cfg.Chat.Telegram.UpdateCheckCommand) == 0 {
return
}
updates := &releaseupdate.Service{
Catalog: releaseupdate.CommandCatalog{Command: s.Cfg.Chat.Telegram.UpdateCheckCommand},
StatePath: filepath.Join(s.Cfg.WorkDir, "telegram-update-deferrals.json"),
}
if len(s.Cfg.Chat.Telegram.UpdateInstallCommand) != 0 {
updates.Installer = releaseupdate.CommandInstaller{Command: s.Cfg.Chat.Telegram.UpdateInstallCommand}
}
tg.Updates = updates
}
func makeTelegramReload(s telegramSetup) func(*telegram.Gateway) error {
return func(g *telegram.Gateway) error {
doc, err := configuration.New(s.Log).Overlay(s.CfgPath, s.OverlayPath)
if err != nil {
return fmt.Errorf("reload config: %w", err)
}
newCfg := doc.Config
tokenEnv := newCfg.Chat.Telegram.TokenEnv
if tokenEnv == "" {
return fmt.Errorf("reload config: chat.telegram.token_env is unset")
}
token := os.Getenv(tokenEnv)
if token == "" {
return fmt.Errorf("reload config: %s is empty", tokenEnv)
}
g.Token = token
g.AllowedUserIDs = newCfg.Chat.Telegram.AllowedUserIDs
s.Log.Info("chat gateway config reloaded", "allowed_user_ids", len(g.AllowedUserIDs))
return nil
}
}
func makeTelegramSessionStore(s telegramSetup) gateway.SessionStore {
if nellAdapter, ok := s.St.(*nell.Adapter); ok {
return gateway.NewSessionStore(nellAdapter.Store(), s.Cfg.BotUser)
}
return gateway.NewSessionStoreMemory(s.Cfg.BotUser)
}
func buildTelegramRouter(ctx context.Context, tg *telegram.Gateway, s telegramSetup, sessionStore gateway.SessionStore) *gateway.Router {
llmResponder, llmStream := makeTelegramLLMResponder(ctx, tg, s, sessionStore)
router := gateway.NewRouter(s.St, llmResponder, "telegram")
router.LLMStream = llmStream
router.Models = s.ChatModels
router.InitSessions(sessionStore)
configureTaskCommands(router, s.ChatTasks, s.ChatController, s.DefaultChatIdentity)
return router
}
func makeTelegramLLMResponder(ctx context.Context, tg *telegram.Gateway, s telegramSetup, sessionStore gateway.SessionStore) (gateway.LLMResponder, gateway.LLMStreamResponder) {
if s.LLM == nil {
return nil, nil
}
resolveSession := func(ctx context.Context, msg gateway.Message) string {
return sessionKey(msg)
}
respond := func(ctx context.Context, msg gateway.Message, onDelta func(string)) (string, error) {
sk := resolveSession(ctx, msg)
if err := sessionStore.SaveMessage(ctx, sk, msg); err != nil {
return "", fmt.Errorf("save inbound chat message: %w", err)
}
history, err := sessionStore.RecentMessages(ctx, sk, 100)
if err != nil {
return "", fmt.Errorf("load chat history: %w", err)
}
compressed := make([]gateway.CompressedMessage, 0, len(history))
for _, h := range history {
role := "user"
if h.From == s.Cfg.BotUser {
role = "assistant"
}
compressed = append(compressed, gateway.CompressedMessage{Role: role, Content: h.Text})
}
view := gateway.CompressHistory(compressed, gateway.DefaultCompressionConfig())
options, err := chatGenerateOptions(nil, s.ToolReg)
if err != nil {
return "", fmt.Errorf("build chat tools: %w", err)
}
chatModel := s.ChatModels.ActiveModel()
systemPrompt := gateway.BuildSystemPrompt(gateway.SystemPromptConfig{
Persona: s.Personas.GetActive(sk), Tools: toolSummaries(options.Tools),
Channel: tg.Name(), Model: chatModel, SessionID: sk, Now: time.Now(),
})
view.Messages = append(
[]gateway.CompressedMessage{{Role: "system", Content: systemPrompt}}, view.Messages...,
)
messages := make([]chat.Message, len(view.Messages))
for i, cm := range view.Messages {
role := chat.RoleUser
switch cm.Role {
case "assistant":
role = chat.RoleAssistant
case "system":
role = chat.RoleSystem
}
messages[i] = chat.Message{Role: role, Content: cm.Content}
}
options.Messages = messages
text, err := sendChatTurn(ctx, s.LLM, chatModel, options, onDelta)
if err != nil {
return "", err
}
if err := sessionStore.SaveMessage(ctx, sk, gateway.Message{From: s.Cfg.BotUser, Text: text}); err != nil {
return "", fmt.Errorf("save outbound chat message: %w", err)
}
return text, nil
}
return func(ctx context.Context, msg gateway.Message) (string, error) {
return respond(ctx, msg, nil)
}, func(ctx context.Context, msg gateway.Message, onDelta func(string)) (string, error) {
return respond(ctx, msg, onDelta)
}
}
func sendChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, options core.GenerateOptions, onDelta func(string)) (string, error) {
if onDelta == nil {
result, err := llm.Chat(ctx, chatModel, options)
if err != nil {
return "", fmt.Errorf("llm chat: %w", err)
}
return result.Text, nil
}
stream, err := llm.ChatStream(ctx, chatModel, options)
if err != nil {
return "", fmt.Errorf("llm chat stream: %w", err)
}
var sb strings.Builder
for part := range stream.FullStream {
if part.Type != core.StreamPartTextDelta || part.TextDelta == "" {
continue
}
sb.WriteString(part.TextDelta)
onDelta(part.TextDelta)
}
if _, err := stream.FinishReason(); err != nil {
return "", fmt.Errorf("llm chat stream: %w", err)
}
return sb.String(), nil
}