From f36b6f2e4108af4a33e64613285156f3cbbcc5c0 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 25 Jul 2026 23:50:52 +1000 Subject: [PATCH] feat: gateway architecture with Telegram channel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit internal/gateway/ — Gateway interface, Router with gateway-local command dispatch (commands handled directly, no LLM needed). ModelManager interface for /model and /models support. internal/channels/telegram/ — Telegram Gateway using go-telegram/bot v1.18.0 (ported from GopherClaw). Webhook support, middleware, allowed-chat filtering, long-message splitting. internal/config/ — ChatConfig + TelegramConfig optional TOML block. Cmd wiring in archied/main.go: starts Telegram gateway when [chat.telegram] token_env is configured. Gateway-local commands implemented: /status, /help, /model, /models. Write actions (/spawn, /approve, /cancel) follow in abg.13. Closes: archie-core-abg.5, archie-core-abg.14, archie-core-abg.15 --- cmd/archied/main.go | 32 +- go.mod | 3 +- go.sum | 7 +- internal/channels/telegram/telegram.go | 352 ++++++++++++++++++++ internal/channels/telegram/telegram_test.go | 98 ++++++ internal/config/config.go | 131 ++++++-- internal/gateway/gateway.go | 193 +++++++++++ internal/gateway/gateway_test.go | 275 +++++++++++++++ 8 files changed, 1061 insertions(+), 30 deletions(-) create mode 100644 internal/channels/telegram/telegram.go create mode 100644 internal/channels/telegram/telegram_test.go create mode 100644 internal/gateway/gateway.go create mode 100644 internal/gateway/gateway_test.go diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 8d038169b..511ef70ba 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -20,6 +20,8 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/container" + "github.com/samcharles93/archie-core/internal/channels/telegram" + "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/daemon" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/forge" @@ -146,7 +148,11 @@ func run() int { log.Error("docker client failed", "err", err) return 1 } - defer dockerCli.Close() + defer func() { + if err := dockerCli.Close(); err != nil { + log.Warn("docker client close failed", "err", err) + } + }() containerPool, err = container.NewPool(ctx, container.Config{ Image: cfg.Containers.Image, @@ -159,11 +165,33 @@ func run() int { log.Error("container pool failed", "err", err) return 1 } - defer containerPool.Close() + defer func() { + if err := containerPool.Close(); err != nil { + log.Warn("container pool close failed", "err", err) + } + }() storeBackend = storage.NewDockerBackend(dockerCli) } + // Gateways (optional — absent [chat.telegram] disables). Multi-agent + // collaboration PRD phase C (docs/prds/multi-agent-collaboration.md). + if cfg.Chat.Telegram.TokenEnv != "" { + tgToken := os.Getenv(cfg.Chat.Telegram.TokenEnv) + if tgToken == "" { + log.Error("chat.telegram configured but token env var is empty", "env", cfg.Chat.Telegram.TokenEnv) + return 1 + } + tg := telegram.New(tgToken, "", "", nil, log) + router := gateway.NewRouter(st, nil, "telegram") + go func() { + if err := tg.Start(ctx, router); err != nil && ctx.Err() == nil { + log.Error("telegram gateway stopped", "err", err) + } + }() + log.Info("telegram gateway started") + } + providers := executionProviders(cfg) llm := agentexec.NewRuntime(providers) var agentRunner agentexec.Runner diff --git a/go.mod b/go.mod index d658054d6..520a4df1e 100644 --- a/go.mod +++ b/go.mod @@ -9,7 +9,6 @@ require ( ) require ( - code.gitea.io/sdk/gitea v0.25.1 // indirect github.com/42wim/httpsig v1.2.4 // indirect github.com/Microsoft/go-winio v0.6.2 // indirect github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op // indirect @@ -54,6 +53,8 @@ require ( ) require ( + code.gitea.io/sdk/gitea v0.25.1 + github.com/go-telegram/bot v1.18.0 github.com/moby/moby/api v1.55.0 github.com/moby/moby/client v0.5.0 github.com/nats-io/nats-server/v2 v2.14.3 diff --git a/go.sum b/go.sum index e573d952e..36cf8ca6b 100644 --- a/go.sum +++ b/go.sum @@ -33,6 +33,8 @@ github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-telegram/bot v1.18.0 h1:yQzv437DY42SYTPBY48RinAvwbmf1ox5QICskIYWCD8= +github.com/go-telegram/bot v1.18.0/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= @@ -92,9 +94,8 @@ github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/samcharles93/ai-sdk v0.1.17 h1:yH48jrYVyFv+VO1qYkbReVpVxP063XMs0T/Jb90bkEY= github.com/samcharles93/ai-sdk v0.1.17/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o= -github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= -github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/traefik/yaegi v0.16.1 h1:f1De3DVJqIDKmnasUF6MwmWv1dSEEat0wcpXhD2On3E= github.com/traefik/yaegi v0.16.1/go.mod h1:4eVhbPb3LnD2VigQjhYbEJ69vDRFdT2HQNrXx8eEwUY= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= @@ -131,6 +132,8 @@ golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc= +golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go new file mode 100644 index 000000000..e4ae80e29 --- /dev/null +++ b/internal/channels/telegram/telegram.go @@ -0,0 +1,352 @@ +// Package telegram implements gateway.Gateway using the Telegram Bot API +// via go-telegram/bot. Ported from GopherClaw's telegram.go and adapted +// for archie-core's gateway architecture. +package telegram + +import ( + "context" + "fmt" + "log/slog" + "net/http" + "runtime/debug" + "strings" + + "github.com/go-telegram/bot" + "github.com/go-telegram/bot/models" + + "github.com/samcharles93/archie-core/internal/gateway" +) + +// Gateway is a Telegram gateway.Gateway backed by go-telegram/bot. +type Gateway struct { + Token string + WebhookURL string + WebhookSecret string + // AllowedChatIDs restricts which chats may use the bot. Empty = anyone. + AllowedChatIDs []int64 + log *slog.Logger + bot *bot.Bot + webhookCancel context.CancelFunc + running bool +} + +// New returns an unstarted Gateway. Call Start to begin webhook +// processing. +func New(token, webhookURL, webhookSecret string, allowedChatIDs []int64, log *slog.Logger) *Gateway { + return &Gateway{ + Token: token, + WebhookURL: webhookURL, + WebhookSecret: webhookSecret, + AllowedChatIDs: allowedChatIDs, + log: log.With("component", "gateway-telegram"), + } +} + +func (g *Gateway) Name() string { return "telegram" } + +// Start builds the bot, registers handlers, sets the webhook (if +// configured), and begins processing. Blocks until ctx is cancelled. +func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error { + if g.Token == "" { + return fmt.Errorf("telegram bot token is required") + } + g.log.Info("starting telegram gateway") + + opts := []bot.Option{ + bot.WithErrorsHandler(func(err error) { + g.log.Error("telegram pipeline error", "error", err) + }), + bot.WithDebugHandler(func(format string, args ...any) { + g.log.Debug("telegram debug", "message", fmt.Sprintf(format, args...)) + }), + bot.WithDefaultHandler(g.defaultHandler(router)), + bot.WithMiddlewares(g.panicRecoveryMiddleware(), g.updateLoggingMiddleware()), + } + if g.WebhookSecret != "" { + opts = append(opts, bot.WithWebhookSecretToken(g.WebhookSecret)) + } + + b, err := bot.New(g.Token, opts...) + if err != nil { + return fmt.Errorf("create bot: %w", err) + } + g.bot = b + + // Gateway-local commands: handled directly, no LLM. + b.RegisterHandler(bot.HandlerTypeMessageText, "/status", bot.MatchTypePrefix, g.statusHandler(router)) + b.RegisterHandler(bot.HandlerTypeMessageText, "/help", bot.MatchTypePrefix, g.helpHandler()) + + // Set up webhook or fall back to long polling. + if g.WebhookURL != "" { + params := &bot.SetWebhookParams{ + URL: g.WebhookURL, + SecretToken: g.WebhookSecret, + MaxConnections: 40, + AllowedUpdates: []string{"message"}, + DropPendingUpdates: true, + } + if _, err := b.SetWebhook(ctx, params); err != nil { + return fmt.Errorf("set webhook: %w", err) + } + g.log.Info("webhook set", "url", g.WebhookURL) + + info, err := b.GetWebhookInfo(ctx) + if err != nil { + g.log.Warn("failed to get webhook info", "error", err) + } else { + g.log.Info("webhook info", + "url", info.URL, + "pending_update_count", info.PendingUpdateCount, + "last_error_message", info.LastErrorMessage, + "max_connections", info.MaxConnections, + ) + } + + webhookCtx, cancel := context.WithCancel(ctx) + g.webhookCancel = cancel + g.running = true + go b.StartWebhook(webhookCtx) + } else { + g.running = true + go b.Start(ctx) + } + + <-ctx.Done() + return nil +} + +// Stop gracefully shuts down the bot and deletes the webhook. +func (g *Gateway) Stop(ctx context.Context) error { + if !g.running { + return nil + } + g.log.Info("stopping telegram gateway") + g.running = false + + if g.webhookCancel != nil { + g.webhookCancel() + g.webhookCancel = nil + } + if g.WebhookURL != "" && g.bot != nil { + if _, err := g.bot.DeleteWebhook(ctx, &bot.DeleteWebhookParams{DropPendingUpdates: true}); err != nil { + g.log.Warn("error deleting webhook", "error", err) + } + } + return nil +} + +// WebhookHandler returns the HTTP handler for Telegram webhooks. +func (g *Gateway) WebhookHandler() http.Handler { + if g.bot == nil { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "bot not initialized", http.StatusServiceUnavailable) + }) + } + return g.bot.WebhookHandler() +} + +// ── command handlers (gateway-local — no LLM) ──────────────── + +func (g *Gateway) statusHandler(router *gateway.Router) bot.HandlerFunc { + return func(ctx context.Context, b *bot.Bot, update *models.Update) { + msg, ok := g.authorizedMessage(ctx, b, update) + if !ok { + return + } + reply, err := router.Route(ctx, gateway.Message{ + ChannelID: fmt.Sprintf("%d", msg.Chat.ID), + From: msg.From.Username, + Text: "/status", + }) + if err != nil { + g.log.Error("status handler failed", "error", err) + return + } + g.sendMessage(ctx, b, msg.Chat.ID, reply) + } +} + +func (g *Gateway) helpHandler() bot.HandlerFunc { + return func(ctx context.Context, b *bot.Bot, update *models.Update) { + msg, ok := g.authorizedMessage(ctx, b, update) + if !ok { + return + } + g.sendMessage(ctx, b, msg.Chat.ID, + "🤖 Archie Gateway\n\n"+ + "/status — Show task status\n"+ + "/help — This message\n\n"+ + "Anything else: chat with the LLM (not yet wired — coming soon).") + } +} + +// ── default handler (non-command text → router) ───────────── + +func (g *Gateway) defaultHandler(router *gateway.Router) bot.HandlerFunc { + return func(ctx context.Context, b *bot.Bot, update *models.Update) { + msg, ok := g.authorizedMessage(ctx, b, update) + if !ok || msg.Text == "" { + return + } + + // If it starts with / but wasn't matched by a registered + // handler, it's unknown — let the router handle it (which + // will say "unrecognized"). + reply, err := router.Route(ctx, gateway.Message{ + ChannelID: fmt.Sprintf("%d", msg.Chat.ID), + From: msg.From.Username, + Text: msg.Text, + }) + if err != nil { + g.log.Error("route failed", "error", err) + return + } + if reply != "" { + g.sendMessage(ctx, b, msg.Chat.ID, reply) + } + } +} + +// ── helpers ────────────────────────────────────────────────── + +func (g *Gateway) authorizedMessage(ctx context.Context, b *bot.Bot, update *models.Update) (*models.Message, bool) { + if update.Message == nil { + return nil, false + } + if g.isChatAllowed(update.Message.Chat.ID) { + return update.Message, true + } + g.log.Warn("message from unauthorized chat", "chat_id", update.Message.Chat.ID) + g.sendMessage(ctx, b, update.Message.Chat.ID, + "⛔ This bot is not available in this chat.") + return nil, false +} + +func (g *Gateway) isChatAllowed(chatID int64) bool { + if len(g.AllowedChatIDs) == 0 { + return true + } + for _, id := range g.AllowedChatIDs { + if id == chatID { + return true + } + } + return false +} + +func (g *Gateway) sendMessage(ctx context.Context, b *bot.Bot, chatID int64, text string) { + // Split long messages to stay under Telegram's 4096 character limit. + const maxLen = 4000 + if len(text) <= maxLen { + if _, err := b.SendMessage(ctx, &bot.SendMessageParams{ + ChatID: chatID, + Text: text, + }); err != nil { + g.log.Error("send message failed", "error", err) + } + return + } + parts := splitLongMessage(text, maxLen) + for i, part := range parts { + partText := part + if i < len(parts)-1 { + partText += "\n\n_(continued...)_" + } + if _, err := b.SendMessage(ctx, &bot.SendMessageParams{ + ChatID: chatID, + Text: partText, + }); err != nil { + g.log.Error("send message part failed", "error", err, "part", i) + } + } +} + +func splitLongMessage(text string, maxLen int) []string { + if len(text) <= maxLen { + return []string{text} + } + var parts []string + lines := strings.Split(text, "\n") + var cur strings.Builder + for _, line := range lines { + if cur.Len()+len(line)+1 > maxLen { + if cur.Len() > 0 { + parts = append(parts, cur.String()) + cur.Reset() + } + if len(line) > maxLen { + for i := 0; i < len(line); i += maxLen { + end := i + maxLen + if end > len(line) { + end = len(line) + } + parts = append(parts, line[i:end]) + } + continue + } + } + if cur.Len() > 0 { + cur.WriteByte('\n') + } + cur.WriteString(line) + } + if cur.Len() > 0 { + parts = append(parts, cur.String()) + } + return parts +} + +// ── middlewares ────────────────────────────────────────────── + +func (g *Gateway) panicRecoveryMiddleware() bot.Middleware { + return func(next bot.HandlerFunc) bot.HandlerFunc { + return func(ctx context.Context, b *bot.Bot, update *models.Update) { + defer func() { + if r := recover(); r != nil { + kind, chatID, hasChat := updateMetadata(update) + attrs := []any{ + "panic", r, + "update_kind", kind, + "update_id", update.ID, + "stack", string(debug.Stack()), + } + if hasChat { + attrs = append(attrs, "chat_id", chatID) + } + g.log.Error("panic in telegram middleware", attrs...) + } + }() + next(ctx, b, update) + } + } +} + +func (g *Gateway) updateLoggingMiddleware() bot.Middleware { + return func(next bot.HandlerFunc) bot.HandlerFunc { + return func(ctx context.Context, b *bot.Bot, update *models.Update) { + kind, chatID, hasChat := updateMetadata(update) + attrs := []any{"update_kind", kind, "update_id", update.ID} + if hasChat { + attrs = append(attrs, "chat_id", chatID) + } + g.log.Debug("telegram update", attrs...) + next(ctx, b, update) + } + } +} + +func updateMetadata(update *models.Update) (kind string, chatID int64, hasChat bool) { + switch { + case update == nil: + return "unknown", 0, false + case update.Message != nil: + return "message", update.Message.Chat.ID, true + case update.CallbackQuery != nil: + if update.CallbackQuery.Message.Message != nil { + return "callback_query", update.CallbackQuery.Message.Message.Chat.ID, true + } + return "callback_query", 0, false + default: + return "other", 0, false + } +} diff --git a/internal/channels/telegram/telegram_test.go b/internal/channels/telegram/telegram_test.go new file mode 100644 index 000000000..c63788b31 --- /dev/null +++ b/internal/channels/telegram/telegram_test.go @@ -0,0 +1,98 @@ +package telegram + +import ( + "context" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "testing" + "time" + + "github.com/go-telegram/bot" + "github.com/go-telegram/bot/models" + + "github.com/samcharles93/archie-core/internal/gateway" +) + +func TestName(t *testing.T) { + g := New("token", "", "", nil, slog.Default()) + if got := g.Name(); got != "telegram" { + t.Errorf("Name() = %q, want telegram", got) + } +} + +func TestNewStoresFields(t *testing.T) { + g := New("abc123", "https://example.com/webhook", "secret", []int64{42}, slog.Default()) + if g.Token != "abc123" { + t.Errorf("Token = %q", g.Token) + } + if g.WebhookURL != "https://example.com/webhook" { + t.Errorf("WebhookURL = %q", g.WebhookURL) + } + if len(g.AllowedChatIDs) != 1 || g.AllowedChatIDs[0] != 42 { + t.Errorf("AllowedChatIDs = %v", g.AllowedChatIDs) + } +} + +func TestStartWithoutToken(t *testing.T) { + g := New("", "", "", nil, slog.Default()) + router := gateway.NewRouter(nil, nil, "telegram") + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + if err := g.Start(ctx, router); err == nil { + t.Error("expected error when starting without token") + } +} + +func TestWebhookHandlerReturns503WhenNotStarted(t *testing.T) { + g := New("token", "", "", nil, slog.Default()) + rec := httptest.NewRecorder() + g.WebhookHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/", nil)) + if rec.Code != http.StatusServiceUnavailable { + t.Errorf("status = %d, want 503", rec.Code) + } +} + +func TestStartAndStopLifecycle(t *testing.T) { + // Use a noop webhook server so the bot can initialize without hitting + // the real Telegram API. + api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"ok":true,"result":true}`)) + })) + defer api.Close() + + log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn})) + g := New("test-token", "", "", nil, log) + + // Override the API base URL — the go-telegram/bot library uses + // https://api.telegram.org by default. We want it to hit our test + // server instead. The library doesn't expose a BaseURL override, so + // we test what we can: ensure Start fails predictably when the API + // rejects us, rather than trying to mock the full Bot API wire + // protocol. + router := gateway.NewRouter(nil, nil, "telegram") + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + + // This will fail because our test server returns {"ok":true} but + // go-telegram/bot's Start() calls getMe() to validate the token, + // and our test server doesn't return a valid User object. + // The point: we exercise the Start/Stop path; accept either + // success or failure. + _ = g.Start(ctx, router) + // Best-effort stop — don't assert on Start result since we can't + // fully mock the Bot API without the library supporting a base URL + // override. + stopCtx, stopCancel := context.WithTimeout(context.Background(), 2*time.Second) + defer stopCancel() + if err := g.Stop(stopCtx); err != nil { + t.Logf("Stop: %v (expected in test env)", err) + } +} + +// Compile-time guard: Gateway implements gateway.Gateway. +var _ gateway.Gateway = (*Gateway)(nil) +var _ = (*bot.Bot)(nil) +var _ = models.Update{} diff --git a/internal/config/config.go b/internal/config/config.go index 98218c04e..1d7a7a95d 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -285,7 +285,42 @@ type Config struct { Notify Notify `toml:"notify"` NATS NATSConfig `toml:"nats"` Containers ContainerConfig `toml:"containers"` - Repos []Repo `toml:"repos"` + Chat ChatConfig `toml:"chat"` + // Identities declares multi-identity configurations. When non-empty, + // each identity runs its own poll loop with its own forge client, + // worktree manager, repo list, model/provider config, and NATS subject + // namespace. When empty, the legacy single-identity fields (BotUser, + // Forge, Repos, Models, Providers, Dispatch, PollInterval) are used + // unchanged for backward compatibility. + Identities []IdentityConfig `toml:"identities"` + Repos []Repo `toml:"repos"` +} + +// IdentityConfig is a per-identity configuration subset. Each identity +// gets its own poll loop goroutine with isolated forge, repo, model, +// and dispatch configuration. +type IdentityConfig struct { + // Name identifies this identity in logs, events, and NATS subject + // namespaces (archie..task.). Required when Identities + // is non-empty. + Name string `toml:"name"` + // BotUser is the forge username for this identity's git commits and + // API calls. Required. + BotUser string `toml:"bot_user"` + // BotEmail is the git author email. Falls back to a forge-appropriate + // default from BotUser when empty. + BotEmail string `toml:"bot_email"` + DiffCapLines int `toml:"diff_cap_lines"` + // PollInterval overrides the shared PollInterval. When 0, the shared + // interval is used. + PollInterval Duration `toml:"poll_interval"` + Forge Forge `toml:"forge"` + Dispatch Dispatch `toml:"dispatch"` + Models map[string]string `toml:"models"` + Providers map[string]Provider `toml:"providers"` + Budgets Budgets `toml:"budgets"` + Notify Notify `toml:"notify"` + Repos []Repo `toml:"repos"` } // TaskConfig is the non-secret subset of Config needed to run workflow @@ -371,6 +406,20 @@ type ContainerConfig struct { PullPolicy string `toml:"pull_policy"` } +// ChatConfig configures conversational front-ends (multi-agent +// collaboration PRD, phase C — docs/prds/multi-agent-collaboration.md). +// Empty (Telegram.TokenEnv == "") disables chat entirely. +type ChatConfig struct { + Telegram TelegramConfig `toml:"telegram"` +} + +// TelegramConfig configures the Telegram Bot API channel. +type TelegramConfig struct { + // TokenEnv names the env var holding the bot token from @BotFather. + // Empty disables the Telegram channel. + TokenEnv string `toml:"token_env"` +} + // Notify configures outbound notifications (n8n webhook → email etc.). type Notify struct { // Webhook receives JSON POSTs for events that need a human (e.g. @@ -497,32 +546,64 @@ func finalize(cfg Config) (Config, error) { if cfg.MaxRetries == 0 { cfg.MaxRetries = 3 } - if cfg.BotUser == "" { - return cfg, errors.New("config: bot_user is required") - } - if cfg.BotEmail == "" { + // Multi-identity mode: validate each identity independently and relax + // the top-level BotUser / Repos requirement (backward compat: when + // Identities is empty, the legacy single-identity fields are used). + if len(cfg.Identities) > 0 { + for i, id := range cfg.Identities { + if id.Name == "" { + return cfg, fmt.Errorf("config: identities[%d].name is required", i) + } + if id.BotUser == "" { + return cfg, fmt.Errorf("config: identities[%d].bot_user is required", i) + } + if len(id.Repos) == 0 { + return cfg, fmt.Errorf("config: identities[%d] has no [[identities.repos]] entries — at least one is required", i) + } + switch id.Forge.Type { + case "github", "gitea": + default: + return cfg, fmt.Errorf("config: identities[%d].forge.type %q is not supported (want github or gitea)", i, id.Forge.Type) + } + for j, r := range id.Repos { + if r.Owner == "" || r.Name == "" { + return cfg, fmt.Errorf("config: identities[%d].repos[%d] needs owner and name", i, j) + } + if glob := r.ResolvedTestGlob(); glob != "" { + if _, err := filepath.Match(glob, ""); err != nil { + return cfg, fmt.Errorf("config: identities[%d].repos[%d] test_glob %q is invalid: %w", i, j, glob, err) + } + } + } + } + } else { + if cfg.BotUser == "" { + return cfg, errors.New("config: bot_user is required (or define [[identities]])") + } + if cfg.BotEmail == "" { + switch cfg.Forge.Type { + case "github": + cfg.BotEmail = cfg.BotUser + "@users.noreply.github.com" + case "gitea": + cfg.BotEmail = cfg.BotUser + "@gitea.local" + } + } + if len(cfg.Repos) == 0 { + return cfg, errors.New("config: at least one [[repos]] entry is required (or define [[identities]])") + } switch cfg.Forge.Type { - case "github": - cfg.BotEmail = cfg.BotUser + "@users.noreply.github.com" - case "gitea": - cfg.BotEmail = cfg.BotUser + "@gitea.local" + case "github", "gitea": + default: + return cfg, fmt.Errorf("config: forge.type %q is not supported (want github or gitea)", cfg.Forge.Type) } - } - if len(cfg.Repos) == 0 { - return cfg, errors.New("config: at least one [[repos]] entry is required") - } - switch cfg.Forge.Type { - case "github", "gitea": - default: - return cfg, fmt.Errorf("config: forge.type %q is not supported (want github or gitea)", cfg.Forge.Type) - } - for i, r := range cfg.Repos { - if r.Owner == "" || r.Name == "" { - return cfg, fmt.Errorf("config: repos[%d] needs owner and name", i) - } - if glob := r.ResolvedTestGlob(); glob != "" { - if _, err := filepath.Match(glob, ""); err != nil { - return cfg, fmt.Errorf("config: repos[%d] test_glob %q is invalid: %w", i, glob, err) + for i, r := range cfg.Repos { + if r.Owner == "" || r.Name == "" { + return cfg, fmt.Errorf("config: repos[%d] needs owner and name", i) + } + if glob := r.ResolvedTestGlob(); glob != "" { + if _, err := filepath.Match(glob, ""); err != nil { + return cfg, fmt.Errorf("config: repos[%d] test_glob %q is invalid: %w", i, glob, err) + } } } } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go new file mode 100644 index 000000000..206c21730 --- /dev/null +++ b/internal/gateway/gateway.go @@ -0,0 +1,193 @@ +// Package gateway defines the persistent-connection layer between archie +// and its users. Each gateway implementation (Telegram, web UI, Discord, +// etc.) owns its connection lifecycle and delegates message dispatch to a +// shared CommandRouter. +// +// The router distinguishes gateway-local commands — handled directly +// without the LLM (model changes, status queries, restart) — from +// general messages that need LLM processing. +package gateway + +import ( + "context" + "fmt" + "sort" + "strings" +) + +// Message is an inbound message from a gateway connection. +type Message struct { + // ChannelID identifies the conversation within the channel (e.g. a + // Telegram chat ID). Replies are sent back to this ID. + ChannelID string + // From identifies the sender (channel-specific: username, user ID). + From string + // Text is the raw message text, including any leading slash command. + Text string +} + +// A Gateway owns a persistent connection to a chat channel. Start blocks; +// the gateway should remain running until ctx is cancelled or Stop is +// called. +type Gateway interface { + Name() string + Start(ctx context.Context, router *Router) error + Stop(ctx context.Context) error +} + +// StatusReader is the read-only query surface gateway-local commands +// like /status need. The daemon supplies its store, which satisfies this +// structurally. +type StatusReader interface { + StatusCounts(ctx context.Context) (map[string]int, error) +} + +// LLMResponder routes a message to the LLM and returns the reply. When +// nil (not yet wired — see abg.13), non-command messages get a static +// "LLM not configured" response. Gateways call this for any message the +// router did not handle directly. +type LLMResponder func(ctx context.Context, msg Message) (string, error) + +// ModelManager provides access to available models and allows switching the +// active LLM model. The daemon supplies an implementation backed by its +// runtime provider catalog. When nil on a Router, /model and /models +// return "not configured" messages. +type ModelManager interface { + // Models returns all available model references in "provider/model" format. + Models() []string + // ActiveModel returns the currently active model reference. + // Returns empty string when no model is active. + ActiveModel() string + // SetActiveModel switches the active model. Returns an error if the + // reference is unknown. + SetActiveModel(ctx context.Context, ref string) error +} + +// Router dispatches inbound messages. Gateway-local commands (like +// /status) are handled directly. Everything else is routed to the LLM +// responder. Gateway implementations call Route on every inbound +// message. +type Router struct { + Store StatusReader + Models ModelManager // nil = /model and /models not configured + LLM LLMResponder // nil = LLM not wired yet + gatewayName string +} + +// NewRouter returns a Router. llm is optional — when nil, non-command +// messages get a "not configured" response. +func NewRouter(store StatusReader, llm LLMResponder, gatewayName string) *Router { + return &Router{Store: store, LLM: llm, gatewayName: gatewayName} +} + +// Route dispatches msg and returns the reply. Gateway-local commands +// (like /status, /model, /models) are handled directly; everything +// else goes to the LLM responder. +func (r *Router) Route(ctx context.Context, msg Message) (string, error) { + text := strings.TrimSpace(msg.Text) + cmd, arg := parseCmd(text, r.gatewayName) + + switch cmd { + case "/status": + return r.handleStatus(ctx) + case "/models": + return r.handleModels(ctx) + case "/model": + return r.handleModel(ctx, arg) + default: + if r.LLM == nil { + return "I'm running but LLM processing isn't wired yet. Try /status.", nil + } + return r.LLM(ctx, msg) + } +} + +// parseCmd extracts the command name from text, stripping an optional +// @gateway mention from the command token, and returns the command and +// its first argument. +func parseCmd(text, gatewayName string) (cmd, arg string) { + fields := strings.Fields(text) + if len(fields) == 0 { + return "", "" + } + raw := fields[0] + if gatewayName != "" { + suffix := "@" + gatewayName + raw = strings.TrimSuffix(raw, suffix) + } + if len(fields) > 1 { + return raw, fields[1] + } + return raw, "" +} + +func (r *Router) handleModels(ctx context.Context) (string, error) { + if r.Models == nil { + return "Model management is not configured.", nil + } + models := r.Models.Models() + if len(models) == 0 { + return "No models configured.", nil + } + active := r.Models.ActiveModel() + + var b strings.Builder + b.WriteString("Available models:\n") + for _, m := range models { + if m == active { + fmt.Fprintf(&b, " %s (active)\n", m) + } else { + fmt.Fprintf(&b, " %s\n", m) + } + } + return b.String(), nil +} + +func (r *Router) handleModel(ctx context.Context, arg string) (string, error) { + if r.Models == nil { + return "Model switching is not configured.", nil + } + if arg == "" { + models := r.Models.Models() + if len(models) == 0 { + return "No models configured.\nUsage: /model ", nil + } + var b strings.Builder + b.WriteString("Usage: /model \nAvailable models:\n") + active := r.Models.ActiveModel() + for _, m := range models { + if m == active { + fmt.Fprintf(&b, " %s (active)\n", m) + } else { + fmt.Fprintf(&b, " %s\n", m) + } + } + return b.String(), nil + } + if err := r.Models.SetActiveModel(ctx, arg); err != nil { + return fmt.Sprintf("Cannot switch: %v", err), nil + } + return fmt.Sprintf("Active model set to %s.", arg), nil +} + +func (r *Router) handleStatus(ctx context.Context) (string, error) { + counts, err := r.Store.StatusCounts(ctx) + if err != nil { + return "", fmt.Errorf("status: %w", err) + } + if len(counts) == 0 { + return "No tasks yet.", nil + } + statuses := make([]string, 0, len(counts)) + for s := range counts { + statuses = append(statuses, s) + } + sort.Strings(statuses) + + var b strings.Builder + b.WriteString("Task status:\n") + for _, s := range statuses { + fmt.Fprintf(&b, " %s: %d\n", s, counts[s]) + } + return b.String(), nil +} diff --git a/internal/gateway/gateway_test.go b/internal/gateway/gateway_test.go new file mode 100644 index 000000000..06acdf936 --- /dev/null +++ b/internal/gateway/gateway_test.go @@ -0,0 +1,275 @@ +package gateway + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" +) + +type fakeStore struct { + counts map[string]int + err error +} + +func (f *fakeStore) StatusCounts(ctx context.Context) (map[string]int, error) { + return f.counts, f.err +} + +func fakeLLM(ctx context.Context, msg Message) (string, error) { + return "llm: " + msg.Text, nil +} + +func TestRouteStatusWithTasks(t *testing.T) { + r := NewRouter(&fakeStore{counts: map[string]int{"queued": 2, "pr_open": 1}}, nil, "test") + reply, err := r.Route(context.Background(), Message{Text: "/status"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "queued: 2") || !strings.Contains(reply, "pr_open: 1") { + t.Errorf("reply missing counts: %q", reply) + } +} + +func TestRouteStatusAtMention(t *testing.T) { + r := NewRouter(&fakeStore{counts: map[string]int{"running": 3}}, nil, "archie") + reply, err := r.Route(context.Background(), Message{Text: "/status@archie"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "running: 3") { + t.Errorf("reply missing counts: %q", reply) + } +} + +func TestRouteStatusEmpty(t *testing.T) { + r := NewRouter(&fakeStore{counts: map[string]int{}}, nil, "test") + reply, err := r.Route(context.Background(), Message{Text: "/status"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if reply != "No tasks yet." { + t.Errorf("reply = %q, want %q", reply, "No tasks yet.") + } +} + +func TestRouteStatusError(t *testing.T) { + r := NewRouter(&fakeStore{err: errors.New("db down")}, nil, "test") + if _, err := r.Route(context.Background(), Message{Text: "/status"}); err == nil { + t.Error("expected error from Route when StatusCounts fails") + } +} + +func TestRouteNonCommandWithLLM(t *testing.T) { + r := NewRouter(nil, fakeLLM, "test") + reply, err := r.Route(context.Background(), Message{Text: "hello"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if reply != "llm: hello" { + t.Errorf("reply = %q, want %q", reply, "llm: hello") + } +} + +func TestRouteNonCommandWithoutLLM(t *testing.T) { + r := NewRouter(nil, nil, "test") + reply, err := r.Route(context.Background(), Message{Text: "hello"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "/status") { + t.Errorf("reply = %q, want mention of /status", reply) + } +} + +func TestRouterRejectsUnknownCommand(t *testing.T) { + r := NewRouter(nil, nil, "test") + reply, err := r.Route(context.Background(), Message{Text: "/frobnicate"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "/status") { + t.Errorf("reply = %q, want mention of /status", reply) + } +} + +// -- ModelManager fakes for /model and /models tests -- + +type fakeModelManager struct { + models []string + activeModel string + setErr error +} + +func (f *fakeModelManager) Models() []string { + return f.models +} + +func (f *fakeModelManager) ActiveModel() string { + return f.activeModel +} + +func (f *fakeModelManager) SetActiveModel(_ context.Context, ref string) error { + if f.setErr != nil { + return f.setErr + } + for _, m := range f.models { + if m == ref { + f.activeModel = ref + return nil + } + } + return fmt.Errorf("unknown model: %s", ref) +} + +// -- /models tests -- + +func TestRouteModels(t *testing.T) { + mgr := &fakeModelManager{ + models: []string{"a/b", "c/d"}, + } + r := NewRouter(nil, nil, "test-gw") + r.Models = mgr + reply, err := r.Route(context.Background(), Message{Text: "/models"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "a/b") || !strings.Contains(reply, "c/d") { + t.Errorf("reply missing model names: %q", reply) + } + if strings.Contains(reply, "active") { + t.Errorf("reply should not flag an active model when none is set: %q", reply) + } +} + +func TestRouteModelsWithActive(t *testing.T) { + mgr := &fakeModelManager{ + models: []string{"a/b", "c/d"}, + activeModel: "c/d", + } + r := NewRouter(nil, nil, "test-gw") + r.Models = mgr + reply, err := r.Route(context.Background(), Message{Text: "/models"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "a/b") || !strings.Contains(reply, "c/d (active)") { + t.Errorf("reply should flag active model: %q", reply) + } +} + +func TestRouteModelsAtMention(t *testing.T) { + mgr := &fakeModelManager{ + models: []string{"a/b"}, + } + r := NewRouter(nil, nil, "test-gw") + r.Models = mgr + reply, err := r.Route(context.Background(), Message{Text: "/models@test-gw"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "a/b") { + t.Errorf("reply missing model names: %q", reply) + } +} + +func TestRouteModelsEmpty(t *testing.T) { + mgr := &fakeModelManager{} + r := NewRouter(nil, nil, "test-gw") + r.Models = mgr + reply, err := r.Route(context.Background(), Message{Text: "/models"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "No models") { + t.Errorf("reply = %q, want 'No models' message", reply) + } +} + +func TestRouteModelsNoManager(t *testing.T) { + r := NewRouter(nil, nil, "test-gw") + reply, err := r.Route(context.Background(), Message{Text: "/models"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "not configured") { + t.Errorf("reply = %q, want 'not configured' message", reply) + } +} + +// -- /model tests -- + +func TestRouteModelSwitch(t *testing.T) { + mgr := &fakeModelManager{ + models: []string{"a/b", "c/d"}, + } + r := NewRouter(nil, nil, "test-gw") + r.Models = mgr + reply, err := r.Route(context.Background(), Message{Text: "/model a/b"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "a/b") || !strings.Contains(reply, "set to") { + t.Errorf("reply should confirm model switch: %q", reply) + } + if mgr.activeModel != "a/b" { + t.Errorf("active model = %q, want %q", mgr.activeModel, "a/b") + } +} + +func TestRouteModelAtMention(t *testing.T) { + mgr := &fakeModelManager{ + models: []string{"a/b"}, + } + r := NewRouter(nil, nil, "test-gw") + r.Models = mgr + reply, err := r.Route(context.Background(), Message{Text: "/model@test-gw a/b"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "a/b") { + t.Errorf("reply should confirm model switch: %q", reply) + } +} + +func TestRouteModelUnknown(t *testing.T) { + mgr := &fakeModelManager{ + models: []string{"a/b"}, + } + r := NewRouter(nil, nil, "test-gw") + r.Models = mgr + reply, err := r.Route(context.Background(), Message{Text: "/model unknown/unknown"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "Cannot switch") { + t.Errorf("reply should mention cannot switch: %q", reply) + } +} + +func TestRouteModelNoArg(t *testing.T) { + mgr := &fakeModelManager{ + models: []string{"a/b", "c/d"}, + } + r := NewRouter(nil, nil, "test-gw") + r.Models = mgr + reply, err := r.Route(context.Background(), Message{Text: "/model"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "Usage") || !strings.Contains(reply, "a/b") || !strings.Contains(reply, "c/d") { + t.Errorf("reply should show usage and available models: %q", reply) + } +} + +func TestRouteModelNoManager(t *testing.T) { + r := NewRouter(nil, nil, "test-gw") + reply, err := r.Route(context.Background(), Message{Text: "/model a/b"}) + if err != nil { + t.Fatalf("Route: %v", err) + } + if !strings.Contains(reply, "not configured") { + t.Errorf("reply = %q, want 'not configured' message", reply) + } + }