From 1ea15462c0d2f6f0798a493c1ebd98c4fbcadf98 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 31 Oct 2026 14:49:50 +1100 Subject: [PATCH] feat(messaging): run Telegram as an archipelago channel extension (#1399) The bundled internal/channels/telegram package (17 files) is deleted; the channel now ships as archipelago/channels/telegram, launched by archiemessaging through the existing channel-extension machinery. An existing [chat.telegram] config enables it with the same keys: the token stays a secret reference (token_ref) the host resolves, allowed_user_ids and show_tool_calls map onto extension settings. Per-org bots compose the same extension per org from the org's credential binding. Reload support is now derived from a channels.Reloader interface instead of a *telegram.Gateway assertion. The five host-only seams (/update, release announcements, running versions, in-place show_tool_calls, reload) are dropped from the channel and need a contract home or deletion. --- .../app/archiemessaging/channel_status.go | 11 +- internal/app/archiemessaging/compose.go | 78 +- internal/app/archiemessaging/config.go | 36 +- .../app/archiemessaging/enablement_test.go | 176 ++-- .../app/archiemessaging/extension_channels.go | 118 ++- internal/app/archiemessaging/org_channels.go | 61 +- internal/app/archiemessaging/reconcile.go | 117 +-- internal/app/archiemessaging/run.go | 26 +- .../app/archiemessaging/telegram_features.go | 95 -- internal/channels/channel.go | 13 + internal/channels/ephemeral.go | 88 -- internal/channels/telegram/approval.go | 369 ------- internal/channels/telegram/commands.go | 99 -- internal/channels/telegram/ephemeral.go | 53 - internal/channels/telegram/ephemeral_send.go | 53 - internal/channels/telegram/inboundmedia.go | 198 ---- internal/channels/telegram/interactive.go | 209 ---- internal/channels/telegram/live.go | 656 ------------ internal/channels/telegram/media.go | 213 ---- internal/channels/telegram/model.go | 557 ---------- .../channels/telegram/polling_readiness.go | 68 -- internal/channels/telegram/provider.go | 165 --- internal/channels/telegram/ratelimit.go | 20 - internal/channels/telegram/restart.go | 48 - internal/channels/telegram/richblocks.go | 603 ----------- internal/channels/telegram/stop.go | 116 -- internal/channels/telegram/telegram.go | 988 ------------------ internal/channels/telegram/update.go | 380 ------- internal/domain/messaging/tool_parameters.go | 73 ++ internal/domain/messaging/tool_render.go | 311 ------ internal/webui/api_chat.go | 5 - 31 files changed, 363 insertions(+), 5640 deletions(-) delete mode 100644 internal/app/archiemessaging/telegram_features.go delete mode 100644 internal/channels/ephemeral.go delete mode 100644 internal/channels/telegram/approval.go delete mode 100644 internal/channels/telegram/commands.go delete mode 100644 internal/channels/telegram/ephemeral.go delete mode 100644 internal/channels/telegram/ephemeral_send.go delete mode 100644 internal/channels/telegram/inboundmedia.go delete mode 100644 internal/channels/telegram/interactive.go delete mode 100644 internal/channels/telegram/live.go delete mode 100644 internal/channels/telegram/media.go delete mode 100644 internal/channels/telegram/model.go delete mode 100644 internal/channels/telegram/polling_readiness.go delete mode 100644 internal/channels/telegram/provider.go delete mode 100644 internal/channels/telegram/ratelimit.go delete mode 100644 internal/channels/telegram/restart.go delete mode 100644 internal/channels/telegram/richblocks.go delete mode 100644 internal/channels/telegram/stop.go delete mode 100644 internal/channels/telegram/telegram.go delete mode 100644 internal/channels/telegram/update.go create mode 100644 internal/domain/messaging/tool_parameters.go delete mode 100644 internal/domain/messaging/tool_render.go diff --git a/internal/app/archiemessaging/channel_status.go b/internal/app/archiemessaging/channel_status.go index fbb885721..4427880ee 100644 --- a/internal/app/archiemessaging/channel_status.go +++ b/internal/app/archiemessaging/channel_status.go @@ -7,7 +7,6 @@ import ( "github.com/samcharles93/archie-core/internal/channels" "github.com/samcharles93/archie-core/internal/channels/status" - "github.com/samcharles93/archie-core/internal/channels/telegram" "github.com/samcharles93/archie-core/internal/domain/storecontract" ) @@ -42,8 +41,8 @@ func reloadable(instance *channelInstance) bool { // configuration in place. A disabled channel (nil) cannot, which is what a // channel that enablement turned off should declare. func channelReloadable(ch channels.Channel) bool { - gateway, ok := ch.(*telegram.Gateway) - return ok && gateway.Reload != nil + _, ok := ch.(channels.Reloader) + return ok } // ReloadChannel asks one channel to reload its configuration, refusing @@ -53,11 +52,11 @@ func (s *Service) ReloadChannel(_ context.Context, id string) error { if instance.name != id { continue } - gateway, ok := instance.current().(*telegram.Gateway) - if !ok || gateway.Reload == nil { + reloader, ok := instance.current().(channels.Reloader) + if !ok { return fmt.Errorf("messaging: channel %q does not support reload", id) } - if err := gateway.Reload(gateway); err != nil { + if err := reloader.Reload(); err != nil { return fmt.Errorf("messaging: reload %q: %w", id, err) } return nil diff --git a/internal/app/archiemessaging/compose.go b/internal/app/archiemessaging/compose.go index 8ec0c1090..3b5c00f19 100644 --- a/internal/app/archiemessaging/compose.go +++ b/internal/app/archiemessaging/compose.go @@ -12,13 +12,10 @@ import ( "github.com/samcharles93/archie-core/internal/channels" "github.com/samcharles93/archie-core/internal/channels/status" - "github.com/samcharles93/archie-core/internal/channels/telegram" - "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/applystatus" "github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/infrastructure/messagingrpc" - "github.com/samcharles93/archie-core/internal/releaseupdate" "github.com/samcharles93/archie-core/internal/secret" ) @@ -26,24 +23,20 @@ type deps struct { // ChannelStatus is where the service publishes channel lifecycle for the // dashboard. Optional: nil leaves the report in-process only. ChannelStatus storecontract.ChannelStatusStore - // Presence reads which version each service reports for itself, to verify - // update reports. Nil leaves them unverified. - Presence storecontract.PresenceStore - Config ResolvedConfig + Config ResolvedConfig // ExtensionChannels are channels served by installed channel extensions. ExtensionChannels []*channelInstance - Log *slog.Logger - Chat messaging.ChatContract - Settings *messaging.SettingsCommand + // ExtensionFactory builds further extension channels on demand, for orgs + // that run their own bot. Nil when no extension source is available. + ExtensionFactory *channelFactory + Log *slog.Logger + Chat messaging.ChatContract // Secrets resolves channel credential references, including those naming an // extension engine. Secrets *secret.Registry // SettingsSource enables live channel-settings reconciliation. Nil disables // it. SettingsSource chatSettingsSource - // Updates serves /update from the stored update settings. Nil without a - // State Store. - Updates *releaseupdate.Service // ApplyReporter records what this process applied. Nil reports nothing. ApplyReporter *applystatus.Reporter // AppliedVersion is the channel-settings version already running when the @@ -107,6 +100,9 @@ type Service struct { secrets *secret.Registry log *slog.Logger chat messaging.ChatContract + // extensions builds extension channels on demand, for orgs that run their + // own bot. Nil when no extension source is available. + extensions *channelFactory // chMu guards channels, which grows as orgs gain channels. chMu sync.RWMutex channels []*channelInstance @@ -147,6 +143,7 @@ func compose(ctx context.Context, d deps) (*Service, error) { secrets: d.Secrets, log: d.Log, chat: d.Chat, + extensions: d.ExtensionFactory, settingsSource: d.SettingsSource, reporter: d.ApplyReporter, orgs: d.OrgChannels, @@ -170,24 +167,15 @@ func compose(ctx context.Context, d deps) (*Service, error) { return srv, nil } -// composeChannels builds the configured channel set. Each instance carries the -// factory a restart uses to build a replacement from a new resolved -// configuration, which is what makes a channel with no in-place reload seam -// still restarted alone rather than through a process restart. +// composeChannels builds the configured channel set: the installed channel +// extensions that extension settings (or a [chat.telegram] file +// configuration) enable. Each instance carries the factory a restart uses to +// build a replacement from a new resolved configuration. func composeChannels(ctx context.Context, d deps) ([]*channelInstance, error) { - instances := make([]*channelInstance, 0, 3) - // Telegram is composed whether or not it is enabled: a channel that - // enablement can turn on has to exist for the supervisor to start. Its - // channel is nil until a token is configured (composeTelegram). The other - // channels are fixed by what the process can build at startup. - telegramInstance, err := composeTelegram(ctx, d) - if err != nil { - return nil, err - } - instances = append(instances, telegramInstance) + instances := make([]*channelInstance, 0, len(d.ExtensionChannels)) for _, instance := range d.ExtensionChannels { if slices.ContainsFunc(instances, func(have *channelInstance) bool { return have.name == instance.name }) { - d.Log.WarnContext(ctx, "channel extension skipped: a built-in channel has the same name", "channel", instance.name) + d.Log.WarnContext(ctx, "channel extension skipped: another channel has the same name", "channel", instance.name) continue } instances = append(instances, instance) @@ -205,40 +193,6 @@ func composeChannels(ctx context.Context, d deps) ([]*channelInstance, error) { return instances, nil } -func composeTelegram(ctx context.Context, d deps) (*channelInstance, error) { - build := func(cfg ResolvedConfig) (channels.Channel, error) { - if cfg.TelegramToken == "" { - return nil, nil - } - if len(cfg.Telegram.AllowedUserIDs) == 0 { - d.Log.WarnContext(ctx, "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(cfg.TelegramToken, cfg.Telegram.AllowedUserIDs, d.Log) - tg.Settings = d.Settings - configureTelegram(ctx, tg, cfg, d) - if err := tg.ValidateConfig(telegramValidateConfigMap(cfg.Telegram)); err != nil { - return nil, fmt.Errorf("chat.telegram config invalid: %w", err) - } - return tg, nil - } - ch, err := build(d.Config) - if err != nil { - return nil, err - } - return &channelInstance{name: "telegram", kind: "telegram", owner: storecontract.DefaultOrgID, channel: ch, rebuild: build}, nil -} - -// telegramValidateConfigMap builds the map Gateway.ValidateConfig expects -// from the typed config. -func telegramValidateConfigMap(cfg config.TelegramConfig) map[string]any { - m := map[string]any{} - if cfg.Token != (secret.SecretRef{}) { - m["token"] = map[string]any{"engine": cfg.Token.Engine, "key": cfg.Token.Key} - } - return m -} - // Start launches the configured messaging channels. func (s *Service) Start(ctx context.Context) error { s.mu.Lock() diff --git a/internal/app/archiemessaging/config.go b/internal/app/archiemessaging/config.go index a77901143..880e61129 100644 --- a/internal/app/archiemessaging/config.go +++ b/internal/app/archiemessaging/config.go @@ -11,20 +11,17 @@ import ( "github.com/samcharles93/archie-core/internal/domain/presence" "github.com/samcharles93/archie-core/internal/infrastructure/configuration" "github.com/samcharles93/archie-core/internal/infrastructure/rpctls" - "github.com/samcharles93/archie-core/internal/secret" ) // ResolvedConfig contains the resolved inputs needed by the Messaging Service. type ResolvedConfig struct { Options Options // Identity is this process's certificate; nil is plaintext, loopback only. - Identity *rpctls.Identity - TelegramToken string + Identity *rpctls.Identity + // Telegram is the [chat.telegram] configuration. It does not compose a + // channel in this process: it enables the telegram channel extension, with + // the same keys, through openExtensionChannels. Telegram config.TelegramConfig - // WorkDir and BotUser are not channel transport settings. They locate - // this identity's release-announcement and update-report state files. - WorkDir string - BotUser string ShowToolCalls bool Logging config.Config } @@ -35,8 +32,6 @@ type projection struct { messaging config.ServiceConnection tls config.TLS telegram config.TelegramConfig - workDir string - botUser string showToolCalls bool logging config.Config } @@ -70,8 +65,6 @@ func Resolve(o Options, log *slog.Logger) (ResolvedConfig, error) { Options: o, Identity: id, Telegram: proj.telegram, - WorkDir: proj.workDir, - BotUser: proj.botUser, ShowToolCalls: proj.showToolCalls, Logging: proj.logging, }, nil @@ -95,8 +88,6 @@ func project(cfg config.Config) projection { messaging: cfg.Services.Get(config.ServiceNameMessaging), tls: cfg.TLS, telegram: cfg.Chat.Telegram, - workDir: cfg.WorkDir, - botUser: cfg.BotUser, showToolCalls: cfg.Chat.ShowToolCalls, logging: config.Config{StateDir: cfg.StateDir, Log: cfg.Log, Telemetry: cfg.Telemetry}, } @@ -114,22 +105,3 @@ func merge(o Options, p projection) Options { } return o } - -// resolveTelegramToken resolves the configured bot token; an unset -// reference means the channel is off. -func resolveTelegramToken(cfg config.TelegramConfig, secrets *secret.Registry) (string, error) { - if cfg.Token == (secret.SecretRef{}) { - return "", nil - } - return secrets.Resolve(cfg.Token) -} - -// resolveTokens fills the channel credentials from the file configuration. -func (c *ResolvedConfig) resolveTokens(secrets *secret.Registry) error { - token, err := resolveTelegramToken(c.Telegram, secrets) - if err != nil { - return fmt.Errorf("resolve telegram token: %w", err) - } - c.TelegramToken = token - return nil -} diff --git a/internal/app/archiemessaging/enablement_test.go b/internal/app/archiemessaging/enablement_test.go index 7891ee305..dfd771cea 100644 --- a/internal/app/archiemessaging/enablement_test.go +++ b/internal/app/archiemessaging/enablement_test.go @@ -21,9 +21,10 @@ import ( type servingChannel struct { mu sync.Mutex starts int + show bool } -func (c *servingChannel) Name() string { return "telegram" } +func (c *servingChannel) Name() string { return "test" } func (c *servingChannel) Start(ctx context.Context, _ messaging.ChatContract, lifecycle channels.Lifecycle) error { c.mu.Lock() @@ -45,40 +46,37 @@ func (c *servingChannel) ConfigSchema() json.RawMessage { return nil } func (c *servingChannel) ValidateConfig(map[string]any) error { return nil } +func (c *servingChannel) SetShowToolCalls(show bool) { + c.mu.Lock() + defer c.mu.Unlock() + c.show = show +} + func (c *servingChannel) count() int { c.mu.Lock() defer c.mu.Unlock() return c.starts } -// waitCount blocks until count reaches want, so an async start is observed -// rather than slept for. -func waitCount(t *testing.T, count func() int, want int) { - t.Helper() - deadline := time.Now().Add(5 * time.Second) - for time.Now().Before(deadline) { - if count() >= want { - return - } - time.Sleep(time.Millisecond) - } - t.Fatalf("channel started %d times, want at least %d", count(), want) +func (c *servingChannel) showToolCalls() bool { + c.mu.Lock() + defer c.mu.Unlock() + return c.show } -// startEnablementService composes and starts a service with the Telegram -// channel's factory replaced by a scripted channel, so enablement can be driven -// without a real bot. -func startEnablementService(t *testing.T, ch *servingChannel) *Service { +// startTestService composes a service and adds one scripted channel instance +// under supervision, so enablement can be driven without a real channel. +func startTestService(t *testing.T, ch *servingChannel) *Service { t.Helper() srv, err := compose(context.Background(), deps{Log: slog.Default()}) if err != nil { t.Fatalf("compose: %v", err) } - inst := srv.instanceByID("telegram") - if inst == nil { - t.Fatal("telegram channel was not composed") + inst := &channelInstance{ + name: "test", kind: "test", + rebuild: func(ResolvedConfig) (channels.Channel, error) { return ch, nil }, + notify: make(chan struct{}, 1), } - inst.rebuild = func(ResolvedConfig) (channels.Channel, error) { return ch, nil } srv.retry = channelRetryPolicy{attempts: 3, backoff: time.Millisecond, maxBackoff: time.Millisecond} ctx, cancel := context.WithCancel(context.Background()) @@ -95,7 +93,8 @@ func startEnablementService(t *testing.T, ch *servingChannel) *Service { t.Error("service did not stop after cancel") } }) - waitSupervised(t, srv, "telegram") + srv.addChannel(ctx, inst) + waitSupervised(t, srv, "test") return srv } @@ -128,31 +127,45 @@ func channelByID(t *testing.T, srv *Service, id string) status.Status { return status.Status{} } -// TestChannelEnablementAppliesLive pins that enabling and disabling a channel +// waitCount blocks until count reaches want, so an async start is observed +// rather than slept for. +func waitCount(t *testing.T, count func() int, want int) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + if count() >= want { + return + } + time.Sleep(time.Millisecond) + } + t.Fatalf("channel started %d times, want at least %d", count(), want) +} + +// TestChannelEnableDisableLive pins that enabling and disabling a channel // starts and stops it without a service restart, and that its declaration // follows: a channel that was never configured is not reported as configured, // and one that enablement stopped is reported stopped and unconfigured. -func TestChannelEnablementAppliesLive(t *testing.T) { +func TestChannelEnableDisableLive(t *testing.T) { ch := &servingChannel{} - srv := startEnablementService(t, ch) + srv := startTestService(t, ch) - if before := channelByID(t, srv, "telegram"); before.Configured || before.State != status.StateStopped { - t.Fatalf("telegram before enable = %+v, want not configured and stopped", before) + if before := channelByID(t, srv, "test"); before.Configured || before.State != status.StateStopped { + t.Fatalf("test before enable = %+v, want not configured and stopped", before) } - if err := srv.enableChannel("telegram", ResolvedConfig{TelegramToken: "token"}); err != nil { + if err := srv.enableChannel("test", ResolvedConfig{}); err != nil { t.Fatalf("enable: %v", err) } waitCount(t, ch.count, 1) - if enabled := channelByID(t, srv, "telegram"); !enabled.Configured || enabled.State != status.StateRunning { - t.Fatalf("telegram after enable = %+v, want configured and running", enabled) + if enabled := channelByID(t, srv, "test"); !enabled.Configured || enabled.State != status.StateRunning { + t.Fatalf("test after enable = %+v, want configured and running", enabled) } - if err := srv.disableChannel("telegram"); err != nil { + if err := srv.disableChannel("test"); err != nil { t.Fatalf("disable: %v", err) } - if disabled := channelByID(t, srv, "telegram"); disabled.Configured || disabled.State != status.StateStopped { - t.Fatalf("telegram after disable = %+v, want not configured and stopped", disabled) + if disabled := channelByID(t, srv, "test"); disabled.Configured || disabled.State != status.StateStopped { + t.Fatalf("test after disable = %+v, want not configured and stopped", disabled) } } @@ -167,75 +180,68 @@ func (f fakeSettings) RuntimeChatConfig(context.Context, config.ChatConfig) (con return f.chat, f.version, nil } -// fakeEngine resolves every key, so a stored token reference is resolvable. -type fakeEngine struct{} - -func (fakeEngine) Name() string { return "test" } -func (fakeEngine) Resolve(key string) (string, error) { return "token-" + key, nil } - -// TestReconcileOnceEnablesAndDisables drives the whole stored-settings path: -// a settings version that configures a token enables the channel and is -// recorded as applied only once the channel is running it; a later version -// that clears the token disables it. -func TestReconcileOnceEnablesAndDisables(t *testing.T) { +// TestReconcileAppliesShowToolCalls pins the live settings path that remains: +// a stored channel-settings version newer than the applied one reaches the +// running channels that accept show_tool_calls, and is recorded as applied. +func TestReconcileAppliesShowToolCalls(t *testing.T) { ch := &servingChannel{} - srv := startEnablementService(t, ch) - srv.secrets = secret.NewRegistry() - srv.secrets.Register(fakeEngine{}) + srv := startTestService(t, ch) + if err := srv.enableChannel("test", ResolvedConfig{}); err != nil { + t.Fatalf("enable: %v", err) + } + waitCount(t, ch.count, 1) srv.settingsSource = fakeSettings{ - chat: config.ChatConfig{Telegram: config.TelegramConfig{Token: secret.SecretRef{Engine: "test", Key: "bot"}}}, + chat: config.ChatConfig{ShowToolCalls: true}, version: 1, } if err := srv.reconcileOnce(context.Background()); err != nil { - t.Fatalf("reconcile enable: %v", err) + t.Fatalf("reconcile: %v", err) } - waitCount(t, ch.count, 1) - if got := channelByID(t, srv, "telegram"); !got.Configured { - t.Fatalf("telegram not enabled by reconcile: %+v", got) + if !ch.showToolCalls() { + t.Fatal("show_tool_calls was not applied to the running channel") } if srv.appliedVersion.Load() != 1 { - t.Fatalf("appliedVersion = %d after enable, want 1", srv.appliedVersion.Load()) + t.Fatalf("appliedVersion = %d, want 1", srv.appliedVersion.Load()) + } + if srv.currentConfig().ShowToolCalls != true { + t.Fatal("running config does not carry the applied setting") } - srv.settingsSource = fakeSettings{version: 2} + // An older version is a no-op. + srv.settingsSource = fakeSettings{version: 1} if err := srv.reconcileOnce(context.Background()); err != nil { - t.Fatalf("reconcile disable: %v", err) - } - if got := channelByID(t, srv, "telegram"); got.Configured || got.State != status.StateStopped { - t.Fatalf("telegram not disabled by reconcile: %+v", got) - } - if srv.appliedVersion.Load() != 2 { - t.Fatalf("appliedVersion = %d after disable, want 2", srv.appliedVersion.Load()) + t.Fatalf("reconcile stale: %v", err) } } -// TestApplyChannelSettingsEnablesAndDisables pins the reconcile entry point: -// a settings change that turns a channel on or off starts or stops it and -// reports applied, and a tick that changes nothing is a no-op. -func TestApplyChannelSettingsEnablesAndDisables(t *testing.T) { - ch := &servingChannel{} - srv := startEnablementService(t, ch) - - applied, err := srv.applyChannelSettings(ResolvedConfig{TelegramToken: "token"}) - if err != nil || !applied { - t.Fatalf("enable: applied=%v err=%v", applied, err) +// TestTelegramFileSetting pins the mapping that keeps an existing +// [chat.telegram] file configuration working through the channel extension: +// the token stays a secret reference for the host to resolve, the allowlist +// joins the same way the extension parses it, and no token means no setting. +func TestTelegramFileSetting(t *testing.T) { + setting, ok := telegramFileSetting(config.TelegramConfig{ + Token: secret.SecretRef{Engine: "env", Key: "ARCHIE_TELEGRAM_TOKEN"}, + AllowedUserIDs: []int64{111, 222}, + }, true) + if !ok { + t.Fatal("setting not produced for a configured token") } - waitCount(t, ch.count, 1) - if got := channelByID(t, srv, "telegram"); !got.Configured || got.State == status.StateStopped { - t.Fatalf("telegram not enabled: %+v", got) + if setting.Name != "telegram" || !setting.Enabled { + t.Fatalf("setting = %+v, want name telegram enabled", setting) + } + want := map[string]string{ + "token_ref": "env:ARCHIE_TELEGRAM_TOKEN", + "allowed_user_ids": "111,222", + "show_tool_calls": "true", + } + for key, value := range want { + if setting.Settings[key] != value { + t.Errorf("settings[%q] = %q, want %q", key, setting.Settings[key], value) + } } - applied, err = srv.applyChannelSettings(ResolvedConfig{}) - if err != nil || !applied { - t.Fatalf("disable: applied=%v err=%v", applied, err) - } - if got := channelByID(t, srv, "telegram"); got.Configured || got.State != status.StateStopped { - t.Fatalf("telegram not disabled: %+v", got) - } - - applied, err = srv.applyChannelSettings(ResolvedConfig{}) - if err != nil || !applied { - t.Fatalf("no-op tick: applied=%v err=%v", applied, err) + if _, ok := telegramFileSetting(config.TelegramConfig{}, false); ok { + t.Fatal("empty token produced a setting, want none") } } diff --git a/internal/app/archiemessaging/extension_channels.go b/internal/app/archiemessaging/extension_channels.go index fefb7c539..7fc017093 100644 --- a/internal/app/archiemessaging/extension_channels.go +++ b/internal/app/archiemessaging/extension_channels.go @@ -4,15 +4,19 @@ import ( "context" "fmt" "log/slog" + "maps" "path/filepath" "slices" + "strconv" "strings" "github.com/samcharles93/archie-core/internal/app/servicekit" "github.com/samcharles93/archie-core/internal/channels" + "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/storepkg" "github.com/samcharles93/archie-core/internal/infrastructure/channelext" "github.com/samcharles93/archie-core/internal/infrastructure/configuration" + "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" "github.com/samcharles93/archie-core/internal/infrastructure/extension" "github.com/samcharles93/archie-core/internal/secret" ) @@ -20,28 +24,87 @@ import ( // refSuffix marks a setting that holds an "engine:key" secret reference. const refSuffix = "_ref" +// telegramChannel is the package name the Telegram channel extension installs +// under, and the config keys [chat.telegram] that enable it. +const telegramChannel = "telegram" + +// channelFactory builds extension channel instances on demand, so channels +// composed after startup (an org's own bot) are built exactly like the ones +// opened at startup. +type channelFactory struct { + host *extension.Host + source extension.Source + cacheDir string + secrets *secret.Registry +} + +// build launches the channel package pkg as a channel named name, with the +// given settings. +func (f *channelFactory) build(ctx context.Context, pkg storepkg.Installed, file, name string, settings map[string]string) (channels.Channel, error) { + if f == nil { + return nil, fmt.Errorf("channel extensions are unavailable") + } + return buildExtensionChannel(ctx, f.host, f.source, f.cacheDir, pkg, file, name, settings, f.secrets) +} + +// channelPackage finds an installed channel package by name and the binary it +// contributes on the channel surface. +func (f *channelFactory) channelPackage(ctx context.Context, name string) (storepkg.Installed, string, bool) { + if f == nil { + return storepkg.Installed{}, "", false + } + installed, err := f.source.Packages.ListInstalled(ctx) + if err != nil { + return storepkg.Installed{}, "", false + } + for _, pkg := range installed { + if pkg.Name != name || pkg.AcceptedAuthority == nil { + continue + } + index := slices.IndexFunc(pkg.Descriptor.Contributes.Extensions, func(x storepkg.Extension) bool { return x.Surface == storepkg.SurfaceChannel }) + if index < 0 { + continue + } + return pkg, pkg.Descriptor.Contributes.Extensions[index].Path, true + } + return storepkg.Installed{}, "", false +} + // openExtensionChannels builds a channel for each installed channel package -// whose authority is accepted and that extension-settings enables. Changing -// the set takes a restart, as every channel binding does. Running extensions -// stop with ctx. -func openExtensionChannels(ctx context.Context, source extension.Source, secrets *secret.Registry, log *slog.Logger) []*channelInstance { +// whose authority is accepted and that extension-settings enables. A +// [chat.telegram] file configuration enables the telegram package the same +// way, with the same config keys, so an existing config keeps working without +// a server login. Changing the set takes a restart, as every channel binding +// does. Running extensions stop with ctx. +func openExtensionChannels(ctx context.Context, source extension.Source, secrets *secret.Registry, log *slog.Logger, telegram config.TelegramConfig, showToolCalls bool) ([]*channelInstance, *channelFactory) { cache, err := configuration.DefaultCacheDir() if err != nil { log.WarnContext(ctx, "channel extensions unavailable: no cache directory", "err", err) - return nil + return nil, nil } settings, _, err := source.Enabled(ctx) if err != nil { log.WarnContext(ctx, "channel extensions unavailable: extension settings", "err", err) - return nil + return nil, nil } installed, err := source.Packages.ListInstalled(ctx) if err != nil { log.WarnContext(ctx, "channel extensions unavailable: installed packages", "err", err) - return nil + return nil, nil + } + if file, ok := telegramFileSetting(telegram, showToolCalls); ok { + stored := settings[telegramChannel] + if stored.Settings == nil { + stored.Settings = map[string]string{} + } + maps.Copy(stored.Settings, file.Settings) + stored.Name, stored.Enabled = telegramChannel, true + settings[telegramChannel] = stored } host := extension.NewHost(log) + factory := &channelFactory{host: host, source: source, cacheDir: filepath.Join(cache, "extensions", "channels"), secrets: secrets} var instances []*channelInstance + built := map[string]bool{} for _, pkg := range installed { setting, ok := settings[pkg.Name] if !ok || !setting.Enabled || pkg.AcceptedAuthority == nil { @@ -51,25 +114,52 @@ func openExtensionChannels(ctx context.Context, source extension.Source, secrets if index < 0 { continue } - ch, err := buildExtensionChannel(ctx, host, source, filepath.Join(cache, "extensions", "channels"), pkg, pkg.Descriptor.Contributes.Extensions[index].Path, setting.Settings, secrets) + ch, err := factory.build(ctx, pkg, pkg.Descriptor.Contributes.Extensions[index].Path, pkg.Name, setting.Settings) if err != nil { log.WarnContext(ctx, "channel extension not started", "channel", pkg.Name, "err", err) continue } + built[pkg.Name] = true instances = append(instances, &channelInstance{ name: pkg.Name, channel: ch, rebuild: func(ResolvedConfig) (channels.Channel, error) { return ch, nil }, }) } + if _, ok := telegramFileSetting(telegram, showToolCalls); ok && !built[telegramChannel] { + log.WarnContext(ctx, "chat.telegram is configured but the telegram channel package is not installed; install the telegram channel extension to enable the bot") + } go func() { <-ctx.Done() host.Close() }() - return instances + return instances, factory } -func buildExtensionChannel(ctx context.Context, host *extension.Host, source extension.Source, cacheDir string, pkg storepkg.Installed, file string, settings map[string]string, secrets *secret.Registry) (channels.Channel, error) { +// telegramFileSetting renders [chat.telegram] as the extension setting that +// enables the telegram channel package. The token stays a reference: the host +// resolves token_ref through the secret registry, so this process never holds +// the bot credential. +func telegramFileSetting(cfg config.TelegramConfig, showToolCalls bool) (controlplanerpc.ExtensionSetting, bool) { + if cfg.Token == (secret.SecretRef{}) { + return controlplanerpc.ExtensionSetting{}, false + } + ids := make([]string, 0, len(cfg.AllowedUserIDs)) + for _, id := range cfg.AllowedUserIDs { + ids = append(ids, strconv.FormatInt(id, 10)) + } + return controlplanerpc.ExtensionSetting{ + Name: telegramChannel, + Enabled: true, + Settings: map[string]string{ + "token_ref": cfg.Token.Engine + ":" + cfg.Token.Key, + "allowed_user_ids": strings.Join(ids, ","), + "show_tool_calls": strconv.FormatBool(showToolCalls), + }, + }, true +} + +func buildExtensionChannel(ctx context.Context, host *extension.Host, source extension.Source, cacheDir string, pkg storepkg.Installed, file, name string, settings map[string]string, secrets *secret.Registry) (channels.Channel, error) { binary, sum, err := extension.Materialize(ctx, source.Packages, cacheDir, pkg, file) if err != nil { return nil, err @@ -77,7 +167,7 @@ func buildExtensionChannel(ctx context.Context, host *extension.Host, source ext plain := make(map[string]string, len(settings)) resolved := make(map[string]string) for key, value := range settings { - name, isRef := strings.CutSuffix(key, refSuffix) + base, isRef := strings.CutSuffix(key, refSuffix) if !isRef { plain[key] = value continue @@ -90,8 +180,8 @@ func buildExtensionChannel(ctx context.Context, host *extension.Host, source ext if err != nil { return nil, fmt.Errorf("setting %q: %w", key, err) } - resolved[name] = secretValue + resolved[base] = secretValue } - spec := extension.Spec{Name: "channel/" + pkg.Name, Path: binary, SHA256: sum, Env: slices.Clone(pkg.AcceptedAuthority.Env), Egress: slices.Clone(pkg.AcceptedAuthority.EgressHosts)} - return channelext.New(host, pkg.Name, spec, plain, resolved, servicekit.ServerLimits()), nil + spec := extension.Spec{Name: "channel/" + name, Path: binary, SHA256: sum, Env: slices.Clone(pkg.AcceptedAuthority.Env), Egress: slices.Clone(pkg.AcceptedAuthority.EgressHosts)} + return channelext.New(host, name, spec, plain, resolved, servicekit.ServerLimits()), nil } diff --git a/internal/app/archiemessaging/org_channels.go b/internal/app/archiemessaging/org_channels.go index 27e70cced..d68838e4c 100644 --- a/internal/app/archiemessaging/org_channels.go +++ b/internal/app/archiemessaging/org_channels.go @@ -6,10 +6,11 @@ import ( "errors" "fmt" "slices" + "strconv" + "strings" "time" "github.com/samcharles93/archie-core/internal/channels" - "github.com/samcharles93/archie-core/internal/channels/telegram" "github.com/samcharles93/archie-core/internal/domain/access" "github.com/samcharles93/archie-core/internal/domain/identity" "github.com/samcharles93/archie-core/internal/domain/messaging" @@ -45,7 +46,7 @@ type orgChannelDeps struct { // currently resolve. type orgChannelPlan struct { org string - token string + binding secret.SecretRef allowed []int64 show bool agent access.Principal @@ -53,7 +54,7 @@ type orgChannelPlan struct { // same reports whether next needs no rebuild of the running channel. func (p orgChannelPlan) same(next orgChannelPlan) bool { - return p.token == next.token && slices.Equal(p.allowed, next.allowed) && p.agent.IdentityID == next.agent.IdentityID + return p.binding == next.binding && slices.Equal(p.allowed, next.allowed) && p.agent.IdentityID == next.agent.IdentityID } // orgChannelLoop keeps one channel per org that has settings, a bound bot token @@ -129,14 +130,7 @@ func (s *Service) planOrgChannel(ctx context.Context, entry controlplanerpc.OrgC if string(principal.Org) != entry.Org || !principal.Kind.Agent() { return orgChannelPlan{}, errors.New("agent is not an agent of this org") } - token, err := s.secrets.Resolve(binding) - if err != nil { - return orgChannelPlan{}, fmt.Errorf("resolve token: %w", err) - } - if token == "" { - return orgChannelPlan{}, errors.New("token resolved empty") - } - return orgChannelPlan{org: entry.Org, token: token, allowed: settings.Telegram.AllowedUserIDs, show: settings.ShowToolCalls, agent: principal}, nil + return orgChannelPlan{org: entry.Org, binding: binding, allowed: settings.Telegram.AllowedUserIDs, show: settings.ShowToolCalls, agent: principal}, nil } // telegramBindings maps each org to the secret its Telegram bot token is bound @@ -169,12 +163,16 @@ func (s *Service) applyOrgChannel(ctx context.Context, owner string, plan orgCha s.applyExistingOrgChannel(ctx, instance, plan) return } + ch, err := s.buildOrgChannel(ctx, plan) + if err != nil { + s.log.WarnContext(ctx, "org channel not built", "org", plan.org, "err", err) + return + } instance := &channelInstance{ name: owner + "/" + telegramCredential, kind: telegramCredential, owner: owner, chat: actingChat{ChatContract: s.chat, as: plan.agent}, plan: &plan, - notify: make(chan struct{}, 1), + channel: ch, notify: make(chan struct{}, 1), } - instance.channel = s.buildOrgTelegram(plan) s.addChannel(ctx, instance) } @@ -190,8 +188,13 @@ func (s *Service) applyExistingOrgChannel(ctx context.Context, instance *channel } return } + ch, err := s.buildOrgChannel(ctx, plan) + if err != nil { + s.log.WarnContext(ctx, "org channel not rebuilt", "org", plan.org, "err", err) + return + } instance.setPlan(plan, s.chat) - if err := s.setChannelState(instance, s.buildOrgTelegram(plan)); err != nil { + if err := s.setChannelState(instance, ch); err != nil { s.log.WarnContext(ctx, "org channel not restarted", "org", plan.org, "err", err) return } @@ -199,18 +202,32 @@ func (s *Service) applyExistingOrgChannel(ctx context.Context, instance *channel } func (s *Service) setOrgShowToolCalls(instance *channelInstance, show bool) { - if g, ok := instance.current().(*telegram.Gateway); ok { + if g, ok := instance.current().(channels.ShowToolCallsSetter); ok { g.SetShowToolCalls(show) } } -// buildOrgTelegram builds an org's bot. It carries none of the instance -// operator's seams: no settings command, update service or version report, so -// an org's chat users reach nothing but chat. -func (s *Service) buildOrgTelegram(plan orgChannelPlan) channels.Channel { - tg := telegram.New(plan.token, plan.allowed, s.log.With("org", plan.org)) - tg.SetShowToolCalls(plan.show) - return tg +// buildOrgChannel builds an org's bot as an instance of the telegram channel +// extension, bound to the org's credential binding. The token stays a +// reference: the host resolves it when the extension launches, so this +// process never holds an org's bot credential. The org's channel carries none +// of the instance operator's seams: an org's chat users reach nothing but +// chat. +func (s *Service) buildOrgChannel(ctx context.Context, plan orgChannelPlan) (channels.Channel, error) { + pkg, file, ok := s.extensions.channelPackage(ctx, telegramCredential) + if !ok { + return nil, fmt.Errorf("the %s channel package is not installed", telegramCredential) + } + ids := make([]string, 0, len(plan.allowed)) + for _, id := range plan.allowed { + ids = append(ids, strconv.FormatInt(id, 10)) + } + settings := map[string]string{ + "token_ref": plan.binding.Engine + ":" + plan.binding.Key, + "allowed_user_ids": strings.Join(ids, ","), + "show_tool_calls": strconv.FormatBool(plan.show), + } + return s.extensions.build(ctx, pkg, file, plan.org+"/"+telegramCredential, settings) } func (c *channelInstance) currentPlan() orgChannelPlan { diff --git a/internal/app/archiemessaging/reconcile.go b/internal/app/archiemessaging/reconcile.go index 276d0abf5..fa207c5ad 100644 --- a/internal/app/archiemessaging/reconcile.go +++ b/internal/app/archiemessaging/reconcile.go @@ -2,16 +2,11 @@ package archiemessaging import ( "context" - "errors" - "fmt" - "slices" - "strings" "time" - "github.com/samcharles93/archie-core/internal/channels/telegram" + "github.com/samcharles93/archie-core/internal/channels" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" - "github.com/samcharles93/archie-core/internal/secret" ) // chatSettingsSource reads the stored channel-settings resource and layers it @@ -38,7 +33,9 @@ func (s *Service) reconcileLoop(ctx context.Context) { } // reconcileOnce applies changed channel settings and records the outcome in -// apply status. +// apply status. Channels are composed at startup -- extension channels included +// -- so the live path today carries chat-level settings (show_tool_calls) to +// the running channels that accept them. func (s *Service) reconcileOnce(ctx context.Context) error { base, err := Resolve(s.currentConfig().Options, s.log) if err != nil { @@ -53,113 +50,27 @@ func (s *Service) reconcileOnce(ctx context.Context) error { if version == 0 || version <= s.appliedVersion.Load() { return nil } - next, err := resolveChatSecrets(base, layered, s.secrets) - if err != nil { - // A credential this process cannot resolve is a document rejection: the - // running channels keep serving and the version stays reported as not - // applied, so the operator sees the refusal rather than a false success. - s.report(ctx, version, err) - return err + next := base + next.Telegram, next.ShowToolCalls = layered.Telegram, layered.ShowToolCalls + if next.ShowToolCalls != base.ShowToolCalls { + s.applyShowToolCalls(next.ShowToolCalls) } - applied, outstanding := s.applyChannelSettings(next) - if applied { - s.appliedVersion.Store(version) - } - s.report(ctx, version, outstanding) + s.setConfig(next) + s.appliedVersion.Store(version) + s.report(ctx, version, nil) return nil } -// resolveChatSecrets carries the layered chat settings onto the resolved -// projection, resolving the store's secret references. A channel whose token -// cannot be resolved stays off rather than composing with an empty credential -// (the startup rule, config.go resolveTelegramToken). -func resolveChatSecrets(base ResolvedConfig, layered config.ChatConfig, secrets *secret.Registry) (ResolvedConfig, error) { - next := base - next.Telegram, next.ShowToolCalls = layered.Telegram, layered.ShowToolCalls - - token, err := resolveTelegramToken(layered.Telegram, secrets) - if err != nil { - return next, fmt.Errorf("resolve database telegram token: %w", err) - } - next.TelegramToken = token - return next, nil -} - -// applyChannelSettings applies the changed channel settings: channels whose -// enablement changed are started or stopped, channels whose transport settings -// changed are restarted, and the report is success only once every change is in -// effect. -func (s *Service) applyChannelSettings(next ResolvedConfig) (bool, error) { - current := s.currentConfig() - - if next.ShowToolCalls != current.ShowToolCalls { - s.applyShowToolCalls(next.ShowToolCalls) - } - - applied := true - outstanding := s.applyChannelEnablement(current, next) - if len(outstanding) > 0 { - applied = false - } - for _, id := range channelChanges(current, next) { - if err := s.restartChannel(id, next); err != nil { - outstanding = append(outstanding, err.Error()) - applied = false - } - } - // A failed change leaves the running configuration in place, so the next - // tick sees the same difference and retries it. - if applied { - s.setConfig(next) - } - if len(outstanding) == 0 { - return applied, nil - } - return applied, errors.New(strings.Join(outstanding, "; ")) -} - -// applyChannelEnablement starts or stops the channels whose enablement the -// stored settings changed, and reports only once the requested state is in -// effect. A channel whose enablement did not change is left alone. -func (s *Service) applyChannelEnablement(current, next ResolvedConfig) []string { - var outstanding []string - switch { - case current.TelegramToken != "" && next.TelegramToken == "": - if err := s.disableChannel("telegram"); err != nil { - outstanding = append(outstanding, err.Error()) - } - case current.TelegramToken == "" && next.TelegramToken != "": - if err := s.enableChannel("telegram", next); err != nil { - outstanding = append(outstanding, err.Error()) - } - } - return outstanding -} - -// applyShowToolCalls updates the running Telegram gateways in place. Nothing -// else consumes the setting, and it is read per reply, so it needs no restart. +// applyShowToolCalls updates the running channels that render tool calls in +// place. The setting is read per reply, so it needs no restart. func (s *Service) applyShowToolCalls(show bool) { for _, c := range s.instances() { - if g, ok := c.current().(*telegram.Gateway); ok { + if g, ok := c.current().(channels.ShowToolCallsSetter); ok { g.SetShowToolCalls(show) } } } -// channelChanges returns the composed channels whose transport settings differ -// between the running and the next configuration while remaining enabled. A -// channel absent from current (not composed) never appears, an unchanged -// channel is not restarted, and an enable or disable is applied as enablement -// rather than as a transport change. -func channelChanges(current, next ResolvedConfig) []string { - var changed []string - if current.TelegramToken != "" && next.TelegramToken != "" && - (current.TelegramToken != next.TelegramToken || !slices.Equal(current.Telegram.AllowedUserIDs, next.Telegram.AllowedUserIDs)) { - changed = append(changed, "telegram") - } - return changed -} - func (s *Service) report(ctx context.Context, version int64, applyErr error) { if s.reporter == nil { return diff --git a/internal/app/archiemessaging/run.go b/internal/app/archiemessaging/run.go index f32a8ecb4..73383d346 100644 --- a/internal/app/archiemessaging/run.go +++ b/internal/app/archiemessaging/run.go @@ -6,14 +6,12 @@ import ( "log/slog" "net" "os" - "path/filepath" "google.golang.org/grpc" "github.com/samcharles93/archie-core/internal/app/servicekit" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/applystatus" - "github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/domain/presence" "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" @@ -24,7 +22,6 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/secretengine" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" "github.com/samcharles93/archie-core/internal/logging" - "github.com/samcharles93/archie-core/internal/releaseupdate" "github.com/samcharles93/archie-core/internal/secret" ) @@ -57,11 +54,9 @@ func Run(ctx context.Context, o Options) error { secrets := secret.NewRegistry() health := newReadinessRegistry(cfg.Options, chat) - var settings *messaging.SettingsCommand // channelStatusStore is the same client, held where compose can reach it: the // channel report is published to the store this process already dials. var channelStatusStore storecontract.ChannelStatusStore - var presenceStore storecontract.PresenceStore // settingsSource and applyReporter are the live channel-settings path: the // control-plane client to re-read the resource, and the record of what this // process applied. Both stay nil without a State Store, which leaves the @@ -70,8 +65,8 @@ func Run(ctx context.Context, o Options) error { var applyReporter *applystatus.Reporter var appliedVersion int64 var orgChannels *orgChannelDeps - var updates *releaseupdate.Service var extensionChannels []*channelInstance + var extensionFactory *channelFactory if cfg.Options.StateStore.Target != "" { stateStore, closeClient, dialErr := staterpc.Dial(cfg.Options.StateStore.Target, presence.Messaging, cfg.Identity, staterpc.WaitForPeer) if dialErr != nil { @@ -92,36 +87,23 @@ func Run(ctx context.Context, o Options) error { go reporter.Run(ctx) go presence.Run(ctx, presence.Messaging, servicekit.Build(), stateStore, health, log) cfg.Telegram, cfg.ShowToolCalls = chatSettings.Telegram, chatSettings.ShowToolCalls - cfg.TelegramToken, settingsErr = resolveTelegramToken(chatSettings.Telegram, secrets) - if settingsErr != nil { - return fmt.Errorf("resolve database telegram token: %w", settingsErr) - } - extensionChannels = openExtensionChannels(ctx, extensions, secrets, log) - settings = messaging.NewSettingsCommand(controlplanerpc.NewSettingsClient(stateStore.ControlPlane())).WithIdentities(stateStore) - channelStatusStore, presenceStore = stateStore, stateStore + extensionChannels, extensionFactory = openExtensionChannels(ctx, extensions, secrets, log, cfg.Telegram, cfg.ShowToolCalls) + channelStatusStore = stateStore settingsSource, applyReporter, appliedVersion, orgChannels = controlPlaneClient, reporter, channelVersion, &orgChannelDeps{Source: controlPlaneClient, Principals: stateStore} - updates = controlplanerpc.UpdateService(controlPlaneClient, filepath.Join(cfg.WorkDir, "telegram-update-deferrals.json")) } - if cfg.Options.StateStore.Target == "" { - if err := cfg.resolveTokens(secrets); err != nil { - return err - } - } srv, err := compose(ctx, deps{ Secrets: secrets, ChannelStatus: channelStatusStore, - Presence: presenceStore, Config: cfg, ExtensionChannels: extensionChannels, + ExtensionFactory: extensionFactory, Log: log, Chat: chat, - Settings: settings, SettingsSource: settingsSource, OrgChannels: orgChannels, ApplyReporter: applyReporter, AppliedVersion: appliedVersion, - Updates: updates, }) if err != nil { return err diff --git a/internal/app/archiemessaging/telegram_features.go b/internal/app/archiemessaging/telegram_features.go deleted file mode 100644 index 690c51f9a..000000000 --- a/internal/app/archiemessaging/telegram_features.go +++ /dev/null @@ -1,95 +0,0 @@ -package archiemessaging - -import ( - "context" - "crypto/sha256" - "fmt" - "log/slog" - "path/filepath" - "time" - - configtemplate "github.com/samcharles93/archie-core" - "github.com/samcharles93/archie-core/internal/app/servicekit" - "github.com/samcharles93/archie-core/internal/buildinfo" - "github.com/samcharles93/archie-core/internal/channels/telegram" - "github.com/samcharles93/archie-core/internal/domain/messaging" - "github.com/samcharles93/archie-core/internal/releaseannounce" - "github.com/samcharles93/archie-core/internal/secret" -) - -// configureTelegram wires the operator seams telegram.Gateway leaves to its -// composition root. -func configureTelegram(ctx context.Context, g *telegram.Gateway, cfg ResolvedConfig, d deps) { - g.Version = gatewayVersionReporter(ctx, d.Chat, cfg.Options.DependencyTimeout) - g.SetShowToolCalls(cfg.ShowToolCalls) - g.Reload = telegramReloader(cfg.Options, d.Secrets, d.Log) - g.RunningVersions = servicekit.RunningVersions(ctx, d.Presence, cfg.Options.DependencyTimeout) - - if d.Updates != nil { - g.Updates = d.Updates - } - if cfg.WorkDir != "" { - g.UpdateReportPath = identityStatePath(cfg.WorkDir, "update-report", cfg.BotUser) - g.ReleaseAnnouncements = &releaseannounce.Announcer{ - StatePath: identityStatePath(cfg.WorkDir, "release-announcements", cfg.BotUser), - Components: []releaseannounce.Component{ - {ID: "archie", Label: "ARCHIE", Version: buildinfo.Version, Changelog: configtemplate.Changelog}, - }, - } - } -} - -// gatewayVersionReporter renders /version from the Gateway's build info, -// fetched per call with a timeout. -func gatewayVersionReporter(ctx context.Context, chat messaging.ChatContract, timeout time.Duration) func() string { - return func() string { - callCtx := ctx - if timeout > 0 { - var cancel context.CancelFunc - callCtx, cancel = context.WithTimeout(callCtx, timeout) - defer cancel() - } - snapshot, err := chat.Snapshot(callCtx) - if err != nil { - return "Version information is unavailable: the Gateway could not be reached." - } - if snapshot.Version == "" { - return "Version information is unavailable: the Gateway reported no build." - } - return snapshot.Version - } -} - -// telegramReloader re-resolves the token and allowlist from this service's own -// configuration on /restart. A reload that cannot produce a token is refused so -// the running bot keeps the credential it is already authenticated with. -func telegramReloader(o Options, secrets *secret.Registry, log *slog.Logger) func(*telegram.Gateway) error { - return func(g *telegram.Gateway) error { - reloaded, err := Resolve(o, log) - if err != nil { - return fmt.Errorf("reload config: %w", err) - } - if err := reloaded.resolveTokens(secrets); err != nil { - return fmt.Errorf("reload config: %w", err) - } - if reloaded.TelegramToken == "" { - return fmt.Errorf("reload config: chat.telegram token is empty") - } - g.Token = reloaded.TelegramToken - g.AllowedUserIDs = reloaded.Telegram.AllowedUserIDs - g.SetShowToolCalls(reloaded.ShowToolCalls) - log.Info("telegram config reloaded", - "allowed_user_ids", len(g.AllowedUserIDs), - "show_tool_calls", g.ShowToolCalls()) - return nil - } -} - -// identityStatePath names a per-identity state file under workDir. The identity -// is hashed so several identities sharing one work directory never collide. The -// scheme is the daemon's, unchanged: a different path would replay every -// release announcement the operator has already been shown. -func identityStatePath(workDir, kind, identity string) string { - identityHash := sha256.Sum256([]byte(identity)) - return filepath.Join(workDir, fmt.Sprintf("%s-%x.json", kind, identityHash[:8])) -} diff --git a/internal/channels/channel.go b/internal/channels/channel.go index 784aa44cf..623ac7f2b 100644 --- a/internal/channels/channel.go +++ b/internal/channels/channel.go @@ -33,5 +33,18 @@ type Sender interface { Send(ctx context.Context, chatID, text string) error } +// Reloader is a channel that can re-read its configuration in place. The +// capability a status report declares and the reload action both derive from +// this interface, so a channel cannot advertise one and answer nothing. +type Reloader interface { + Reload() error +} + +// ShowToolCallsSetter is a channel that renders completed tool calls in its +// replies when the operator turns chat.show_tool_calls on. +type ShowToolCallsSetter interface { + SetShowToolCalls(show bool) +} + // ErrNotRunning is returned by Send while the channel is stopped. var ErrNotRunning = errors.New("channel is not running") diff --git a/internal/channels/ephemeral.go b/internal/channels/ephemeral.go deleted file mode 100644 index 0d808e0ca..000000000 --- a/internal/channels/ephemeral.go +++ /dev/null @@ -1,88 +0,0 @@ -package channels - -import ( - "context" - "log/slog" - "sync" - "time" - - "github.com/samcharles93/archie-core/internal/domain/messaging" -) - -// defaultEphemeralDeleteTimeout bounds one retraction. It is independent of -// the turn's own context, which may already be cancelled by the time the TTL -// elapses: the message was sent, so it still has to be removed. -const defaultEphemeralDeleteTimeout = 30 * time.Second - -// SendFunc delivers one message and returns the platform's view of it, with -// at least the identifier a later retraction addresses. A sender whose -// platform cannot name a delivered message leaves ID empty, and a retraction -// of that message is then skipped rather than attempted blindly. -type SendFunc func(ctx context.Context, event messaging.MessageEvent) (messaging.MessageEvent, error) - -// EphemeralSender sends EphemeralReplies and deletes them after their TTL. -// after defaults to time.After. -type EphemeralSender struct { - after func(time.Duration) <-chan time.Time - timeout time.Duration - log *slog.Logger - wg sync.WaitGroup -} - -// NewEphemeralSender returns a sender whose retractions wait on after. -func NewEphemeralSender(log *slog.Logger, after func(time.Duration) <-chan time.Time) *EphemeralSender { - if after == nil { - after = time.After - } - if log == nil { - log = slog.New(slog.DiscardHandler) - } - return &EphemeralSender{ - after: after, - timeout: defaultEphemeralDeleteTimeout, - log: log, - } -} - -// Send delivers reply.Event and schedules its deletion after reply.TTL when -// sender supports Delete. A send error is returned; nothing is scheduled -// without a message ID or a positive TTL. -func (e *EphemeralSender) Send(ctx context.Context, sender any, reply messaging.EphemeralReply, send SendFunc) (messaging.MessageEvent, error) { - sent, err := send(ctx, reply.Event) - if err != nil { - return sent, err - } - // A reply with no lifetime, or a send the platform could not name, has - // nothing to schedule: there is either no deadline or no message to - // address. - if reply.TTL <= 0 || sent.ID == "" { - return sent, nil - } - - deleter, ok := messaging.DeleterOf(sender) - if !ok { - e.log.DebugContext(ctx, "channel cannot retract an ephemeral reply; leaving it in place", - "platform", reply.Event.Platform, "type", reply.Event.Type) - return sent, nil - } - - e.wg.Go(func() { - <-e.after(reply.TTL) - // The turn's context may already be cancelled by the time the TTL - // elapses -- a delivered message is still retracted -- so the - // retraction carries its own bounded, uncancellable context. - delCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), e.timeout) - defer cancel() - if err := deleter.DeleteMessage(delCtx, sent); err != nil { - e.log.WarnContext(ctx, "ephemeral reply retraction failed", - "platform", reply.Event.Platform, "error", err) - } - }) - return sent, nil -} - -// Wait blocks until every retraction started so far has finished. Tests only: -// production callers never wait on a retraction's own TTL. -func (e *EphemeralSender) Wait() { - e.wg.Wait() -} diff --git a/internal/channels/telegram/approval.go b/internal/channels/telegram/approval.go deleted file mode 100644 index 78c72b909..000000000 --- a/internal/channels/telegram/approval.go +++ /dev/null @@ -1,369 +0,0 @@ -package telegram - -import ( - "context" - "crypto/rand" - "encoding/hex" - "fmt" - "strings" - "time" - - "github.com/go-telegram/bot" - "github.com/go-telegram/bot/models" - - "github.com/samcharles93/archie-core/internal/domain/messaging" -) - -// approvalCallbackPrefix separates tool-approval callbacks from other -// callback types handled in defaultHandler. It is deliberately distinct -// from every other callback prefix. -const approvalCallbackPrefix = "approval:" - -// telegramApprover implements gateway.ApprovalRequester with an inline-button -// prompt, blocking until the operator decides, ctx ends or the window elapses. -type telegramApprover struct { - gw *Gateway - bot *bot.Bot - chatID int64 - threadID int - recipient int64 -} - -// pendingApproval records a tool-approval request waiting on an operator -// decision. It is kept separate so the -// tool-approval model (result channels) cannot entangle. -type pendingApproval struct { - token string - action string - description string - recipient int64 - expiresAt time.Time - resultCh chan approvalResult -} - -// approvalResult carries the operator's decision back to the blocked -// RequestApproval call. -type approvalResult struct { - decision messaging.ApprovalDecision - err error -} - -// Compile-time guard. -var ( - _ messaging.ApprovalRequester = (*telegramApprover)(nil) - _ messaging.CapabilityReporter = (*telegramApprover)(nil) -) - -// Capabilities reports native approval only. -func (a *telegramApprover) Capabilities() messaging.AdapterCapabilities { - return messaging.AdapterCapabilities{Approval: true} -} - -// NewApprover returns an ApprovalRequester that renders prompts in the -// given chat. recipient is the Telegram user who may approve; in a private -// DM this is the same as chatID, in a group it is the sender of the turn -// that triggered the gated tool call. -func (g *Gateway) NewApprover(b *bot.Bot, chatID int64, threadID int, recipient int64) messaging.ApprovalRequester { - return &telegramApprover{ - gw: g, - bot: b, - chatID: chatID, - threadID: threadID, - recipient: recipient, - } -} - -// RequestApproval asks the recipient to approve action. A current permanent -// approval returns ApprovalPermanentlyApproved without prompting. -func (a *telegramApprover) RequestApproval(ctx context.Context, action, description string) (messaging.ApprovalDecision, error) { - // Compose the lookup key so a permanent approval is scoped to - // the specific resource: "Approve Permanently" on "delete session - // abc123" only permanently approves that one session, not every - // session_delete forever. - permKey := action + "\x00" + description - if a.gw.hasPermanentApprovalExact(a.recipient, permKey) { - return messaging.ApprovalPermanentlyApproved, nil - } - - token := makeCallbackToken() - resultCh := make(chan approvalResult, 1) - a.gw.registerPendingApproval(pendingApproval{ - token: token, - action: action, - description: description, - recipient: a.recipient, - expiresAt: time.Now().Add(messaging.ToolApprovalTimeout), - resultCh: resultCh, - }) - - params := &bot.SendMessageParams{ - ChatID: a.chatID, - Text: approvalPromptText(action, description), - ReplyMarkup: a.gw.approvalKeyboard(token), - } - if a.threadID != 0 { - params.MessageThreadID = a.threadID - } - - approvalCtx, cancel := context.WithTimeout(ctx, messaging.ToolApprovalTimeout) - defer cancel() - - if _, err := a.bot.SendMessage(approvalCtx, params); err != nil { - a.gw.removePendingApproval(token) - if approvalCtx.Err() != nil { - return messaging.ApprovalDenied, approvalCtx.Err() - } - a.gw.log.ErrorContext(ctx, "send approval prompt failed", "error", err) - return messaging.ApprovalDenied, fmt.Errorf("send approval prompt: %w", err) - } - - select { - case result := <-resultCh: - return a.applyApprovalDecision(action, description, result) - case <-approvalCtx.Done(): - // A decision may have raced the timeout: drain it rather than - // discarding a valid approval. - select { - case result := <-resultCh: - return a.applyApprovalDecision(action, description, result) - default: - a.gw.removePendingApproval(token) - return messaging.ApprovalDenied, approvalCtx.Err() - } - } -} - -// applyApprovalDecision maps an operator decision to the gateway contract, -// recording a permanent approval when the operator asked for one. -func (a *telegramApprover) applyApprovalDecision(action, description string, result approvalResult) (messaging.ApprovalDecision, error) { - switch result.decision { - case messaging.ApprovalApproved: - return messaging.ApprovalApproved, nil - case messaging.ApprovalPermanentlyApproved: - // Scoped: permanently approving "delete session abc123" only - // silences the prompt for that one resource, not every call to - // the same tool. - a.gw.recordPermanentApproval(a.recipient, action+"\x00"+description) - return messaging.ApprovalPermanentlyApproved, nil - case messaging.ApprovalDenied: - if result.err != nil { - return messaging.ApprovalDenied, result.err - } - return messaging.ApprovalDenied, messaging.ErrApprovalDenied - default: - return messaging.ApprovalDenied, fmt.Errorf("unexpected approval decision %v", result.decision) - } -} - -// approvalKeyboard builds the three-button inline keyboard for a tool -// approval: "Approve this time", "Approve Permanently", "Deny". It mirrors -// the approval: callback prefix. -func (g *Gateway) approvalKeyboard(token string) *models.InlineKeyboardMarkup { - return &models.InlineKeyboardMarkup{ - InlineKeyboard: [][]models.InlineKeyboardButton{ - { - { - Text: "Approve this time", - CallbackData: approvalCallbackPrefix + "approve:" + token, - }, - }, - { - { - Text: "Approve Permanently", - CallbackData: approvalCallbackPrefix + "permanent:" + token, - }, - }, - { - { - Text: "Deny", - CallbackData: approvalCallbackPrefix + "deny:" + token, - }, - }, - }, - } -} - -// registerPendingApproval stores a pending tool approval, pruning any that -// have already expired. -func (g *Gateway) registerPendingApproval(pa pendingApproval) { - g.approvalMu.Lock() - defer g.approvalMu.Unlock() - - now := time.Now() - for key, existing := range g.pendingApprovals { - if !existing.expiresAt.After(now) { - delete(g.pendingApprovals, key) - } - } - g.pendingApprovals[pa.token] = &pa -} - -// removePendingApproval drops a pending tool approval, if present. -func (g *Gateway) removePendingApproval(token string) { - g.approvalMu.Lock() - defer g.approvalMu.Unlock() - delete(g.pendingApprovals, token) -} - -// consumePendingApproval validates and atomically consumes the pending -// approval for the callback. It rejects expired tokens and callbacks from -// anyone other than the intended recipient, and enforces single use. -func (g *Gateway) consumePendingApproval(token string, recipient int64) (*pendingApproval, bool) { - g.approvalMu.Lock() - defer g.approvalMu.Unlock() - - pa, found := g.pendingApprovals[token] - if found && pa.recipient == recipient && pa.expiresAt.After(time.Now()) { - delete(g.pendingApprovals, token) - } - return pa, found && pa.recipient == recipient && pa.expiresAt.After(time.Now()) -} - -// handleApprovalCallback is the entrypoint for tool-approval inline-button -// taps. It validates the token (recipient, expiry, single use) and delivers -// the decision to the blocked RequestApproval call. -func (g *Gateway) handleApprovalCallback(ctx context.Context, b *bot.Bot, update *models.Update) { - query := update.CallbackQuery - if query == nil { - return - } - if !g.isSenderAllowed(query.From.ID) { - g.log.WarnContext(ctx, "approval callback from unauthorized sender", "user_id", query.From.ID) - g.answerCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true) - return - } - - decision, token := parseApprovalCallback(query.Data) - if decision == "" { - g.answerCallback(ctx, b, query.ID, "That action is no longer valid.", true) - return - } - - pa, ok := g.consumePendingApproval(token, query.From.ID) - if !ok { - g.answerCallback(ctx, b, query.ID, "That action is no longer valid.", true) - return - } - - g.log.InfoContext(ctx, - "tool approval decision", - "action", pa.action, "decision", decision, - "recipient", query.From.ID, "username", query.From.Username, - ) - - switch decision { - case "approve": - pa.resultCh <- approvalResult{decision: messaging.ApprovalApproved} - g.answerCallback(ctx, b, query.ID, "Approved and executed.", false) - g.editCallbackMessage(ctx, b, query, "βœ… Approved: "+pa.description) - case "permanent": - pa.resultCh <- approvalResult{decision: messaging.ApprovalPermanentlyApproved} - g.answerCallback(ctx, b, query.ID, "Permanently approved (valid 24h).", false) - g.editCallbackMessage(ctx, b, query, "βœ… Approved (permanent, 24h): "+pa.description) - case "deny": - pa.resultCh <- approvalResult{decision: messaging.ApprovalDenied, err: messaging.ErrApprovalDenied} - g.answerCallback(ctx, b, query.ID, "Action denied.", false) - g.editCallbackMessage(ctx, b, query, "❌ Denied: "+pa.description) - } -} - -// parseApprovalCallback splits an approval callback into decision -// ("approve", "permanent", "deny") and token. -func parseApprovalCallback(data string) (decision, token string) { - data = strings.TrimPrefix(data, approvalCallbackPrefix) - decision, token, _ = strings.Cut(data, ":") - if decision != "approve" && decision != "permanent" && decision != "deny" { - return "", "" - } - return decision, token -} - -// approvalPromptText renders the message shown above the approval keyboard. -// The expiry figure is derived from the shared constant so a change to the -// approval window cannot leave the prompt out of date. -func approvalPromptText(action, description string) string { - minutes := int(messaging.ToolApprovalTimeout.Minutes()) - return fmt.Sprintf( - "⚠️ Approval required\n\n"+ - "Action: %s\n"+ - "%s\n\n"+ - "This request expires in %d minutes.", - action, description, minutes, - ) -} - -// answerCallback is the common acknowledge/shake response. -func (g *Gateway) answerCallback(ctx context.Context, b *bot.Bot, queryID, text string, alert bool) { - if _, err := b.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{ - CallbackQueryID: queryID, - Text: text, - ShowAlert: alert, - }); err != nil { - g.log.WarnContext(ctx, "answer callback failed", "error", err) - } -} - -func (g *Gateway) editCallbackMessage(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, text string) { - if query.Message.Message == nil { - return - } - message := query.Message.Message - if _, err := b.EditMessageText(ctx, &bot.EditMessageTextParams{ - ChatID: message.Chat.ID, - MessageID: message.ID, - Text: text, - }); err != nil { - g.log.WarnContext(ctx, "edit callback message failed", "error", err) - } -} - -func makeCallbackToken() string { - bytes := make([]byte, 16) - if _, err := rand.Read(bytes); err != nil { - panic("crypto/rand: " + err.Error()) - } - return hex.EncodeToString(bytes) -} - -// permanentApproval records an operator's decision to approve one tool for 24 -// hours. Scope and lifetime are explicit. -type permanentApproval struct { - Pattern string - Recipient int64 - ExpiresAt time.Time -} - -func (g *Gateway) recordPermanentApproval(recipient int64, pattern string) { - g.permanentMu.Lock() - defer g.permanentMu.Unlock() - g.permanentApprovals = append(g.livePermanentApprovals(), permanentApproval{ - Pattern: pattern, Recipient: recipient, ExpiresAt: time.Now().Add(24 * time.Hour), - }) - g.log.Info("tool permanently approved for 24h", "tool", pattern, "recipient", recipient) -} - -// hasPermanentApprovalExact reports whether recipient approved pattern within -// the last 24 hours. -func (g *Gateway) hasPermanentApprovalExact(recipient int64, pattern string) bool { - g.permanentMu.Lock() - defer g.permanentMu.Unlock() - g.permanentApprovals = g.livePermanentApprovals() - for _, pa := range g.permanentApprovals { - if pa.Recipient == recipient && pa.Pattern == pattern { - return true - } - } - return false -} - -// livePermanentApprovals drops expired approvals. permanentMu must be held. -func (g *Gateway) livePermanentApprovals() []permanentApproval { - now := time.Now() - kept := g.permanentApprovals[:0] - for _, pa := range g.permanentApprovals { - if pa.ExpiresAt.After(now) { - kept = append(kept, pa) - } - } - return kept -} diff --git a/internal/channels/telegram/commands.go b/internal/channels/telegram/commands.go deleted file mode 100644 index c523f4e16..000000000 --- a/internal/channels/telegram/commands.go +++ /dev/null @@ -1,99 +0,0 @@ -package telegram - -import ( - "context" - "fmt" - "strings" - - "github.com/go-telegram/bot" - "github.com/go-telegram/bot/models" -) - -type commandSpec struct { - Command string - Description string - Usage string -} - -// gatewayCommandSpecs is the single source of truth for both Telegram's -// published command menu and /help. Keeping the discoverability surfaces -// together prevents a newly registered command from being omitted from help. -var gatewayCommandSpecs = []commandSpec{ - {Command: "status", Description: "Show health: queue depth, broker, and the last chat-model call", Usage: "/status"}, - {Command: "tasks", Description: "Show your tasks: state, stage, age, parked reason", Usage: "/tasks"}, - {Command: "version", Description: "Show installed Archie versions", Usage: "/version"}, - {Command: "update", Description: "Check for Archie updates", Usage: "/update"}, - {Command: "model", Description: "Choose a provider and model or switch directly", Usage: "/model [provider/model]"}, - {Command: "spawn", Description: "Create a tracked task", Usage: "/spawn [identity=name] [repo=owner/name] [workflow=name] "}, - {Command: "settings", Description: "Inspect or change runtime settings", Usage: "/settings [list|get <kind>|set <kind> <field>=<value> ...]"}, - {Command: "approve", Description: "Approve a waiting task", Usage: "/approve [identity=name] <task-id>"}, - {Command: "cancel", Description: "Cancel a queued or waiting task", Usage: "/cancel [identity=name] <task-id>"}, - {Command: "start", Description: "Confirm that Archie is running", Usage: "/start"}, - {Command: "new", Description: "Start a fresh session, clearing conversation history", Usage: "/new [title]"}, - {Command: "reset", Description: "Alias for /new", Usage: "/reset [title]"}, - {Command: "topic", Description: "List or switch sessions for this channel", Usage: "/topic [off|help|<session-id>]"}, - {Command: "retry", Description: "Replay the last message with a fresh reply", Usage: "/retry"}, - {Command: "undo", Description: "Remove the last N messages from the session", Usage: "/undo [N]"}, - {Command: "title", Description: "Show or set the current session's title", Usage: "/title [name]"}, - {Command: "branch", Description: "Create a child session that inherits the current history", Usage: "/branch [name]"}, - {Command: "fork", Description: "Alias for /branch", Usage: "/fork [name]"}, - {Command: "compress", Description: "Compress the current session's context", Usage: "/compress [here [N]|focus <topic>|--preview|--dry-run]"}, - {Command: "compact", Description: "Alias for /compress", Usage: "/compact [here [N]|focus <topic>|--preview|--dry-run]"}, - {Command: "whoami", Description: "Show the active identity and model", Usage: "/whoami"}, - {Command: "profile", Description: "Show the active identity's profile", Usage: "/profile"}, - {Command: "sessions", Description: "List this channel's sessions", Usage: "/sessions"}, - {Command: "resume", Description: "Switch to a session by id or unique prefix", Usage: "/resume <session-id>"}, - {Command: "delete", Description: "Permanently delete a session and its history", Usage: "/delete <session-id>"}, - {Command: "agents", Description: "List tasks currently being worked", Usage: "/agents"}, - {Command: "stop", Description: "Stop the running reply, else this chat's tasks; or one task", Usage: "/stop [task-id]"}, - {Command: "restart", Description: "Reload Archie and its configuration", Usage: "/restart"}, - {Command: "help", Description: "See what Archie can do", Usage: "/help"}, -} - -var gatewayCommands = func() []models.BotCommand { - commands := make([]models.BotCommand, 0, len(gatewayCommandSpecs)) - for _, spec := range gatewayCommandSpecs { - commands = append(commands, models.BotCommand{ - Command: spec.Command, - Description: spec.Description, - }) - } - return commands -}() - -func gatewayHelpText() string { - var help strings.Builder - help.WriteString("πŸ€– **Archie**\n\n") - help.WriteString("Send a message to chat with Archie. Replies stream into Telegram as they are generated.\n\n") - help.WriteString("**Commands**\n") - for _, spec := range gatewayCommandSpecs { - fmt.Fprintf(&help, "`%s`\n%s\n\n", spec.Usage, spec.Description) - } - return strings.TrimSpace(help.String()) -} - -// commandScopes are the scopes the command menu is published to. Publishing -// to every scope overwrites menus left on narrower scopes. -var commandScopes = []models.BotCommandScope{ - &models.BotCommandScopeDefault{}, - &models.BotCommandScopeAllPrivateChats{}, - &models.BotCommandScopeAllGroupChats{}, -} - -// registerCommands publishes the command menu to every scope. A failure -// here costs discoverability, not function -- every command still works -// when typed -- so it is logged rather than treated as fatal, and one -// failing scope does not stop the others. -func (g *Gateway) registerCommands(ctx context.Context, b *bot.Bot) { - for _, scope := range commandScopes { - if _, err := b.SetMyCommands(ctx, &bot.SetMyCommandsParams{ - Commands: gatewayCommands, - Scope: scope, - }); err != nil { - g.log.WarnContext(ctx, "set command menu failed", "scope", fmt.Sprintf("%T", scope), "error", err) - continue - } - } - g.log.InfoContext(ctx, "command menu registered", - "commands", len(gatewayCommands), "scopes", len(commandScopes)) -} diff --git a/internal/channels/telegram/ephemeral.go b/internal/channels/telegram/ephemeral.go deleted file mode 100644 index 32c6fabf5..000000000 --- a/internal/channels/telegram/ephemeral.go +++ /dev/null @@ -1,53 +0,0 @@ -package telegram - -import ( - "context" - "fmt" - "strconv" - - "github.com/go-telegram/bot" - - "github.com/samcharles93/archie-core/internal/domain/messaging" -) - -// telegramMessageDeleter deletes messages through the bot it was built with. -type telegramMessageDeleter struct { - bot *bot.Bot - chatID int64 -} - -var ( - _ messaging.MessageDeleter = (*telegramMessageDeleter)(nil) - _ messaging.CapabilityReporter = (*telegramMessageDeleter)(nil) -) - -// NewMessageDeleter returns a MessageDeleter bound to one chat and to the bot -// instance of the launch that created it. Construct it per launch, from the -// same b that handled the update. -func (g *Gateway) NewMessageDeleter(b *bot.Bot, chatID int64) messaging.MessageDeleter { - return &telegramMessageDeleter{bot: b, chatID: chatID} -} - -// Capabilities reports Delete support. Telegram can remove any message the -// bot sent in a chat it administers, so this is unconditionally true. -func (d *telegramMessageDeleter) Capabilities() messaging.AdapterCapabilities { - return messaging.AdapterCapabilities{Delete: true} -} - -// DeleteMessage removes the message event names. The event's ID is the -// Telegram message ID the send returned; a non-numeric one cannot address a -// platform message, so it is reported rather than sent to the API as a -// doomed request. -func (d *telegramMessageDeleter) DeleteMessage(ctx context.Context, event messaging.MessageEvent) error { - id, err := strconv.Atoi(event.ID) - if err != nil { - return fmt.Errorf("telegram delete: message id %q is not numeric: %w", event.ID, err) - } - if _, err := d.bot.DeleteMessage(ctx, &bot.DeleteMessageParams{ - ChatID: d.chatID, - MessageID: id, - }); err != nil { - return fmt.Errorf("telegram delete message %d: %w", id, err) - } - return nil -} diff --git a/internal/channels/telegram/ephemeral_send.go b/internal/channels/telegram/ephemeral_send.go deleted file mode 100644 index d3efe0b28..000000000 --- a/internal/channels/telegram/ephemeral_send.go +++ /dev/null @@ -1,53 +0,0 @@ -package telegram - -import ( - "context" - "fmt" - "time" - - "github.com/go-telegram/bot" - - "github.com/samcharles93/archie-core/internal/domain/messaging" -) - -// statusNoticeTTL is how long a transient status notice stays in the chat -// before it is retracted: long enough to be read, short enough not to become -// history next to the conversation it reported on. -const statusNoticeTTL = 8 * time.Second - -// sendEphemeral sends text and deletes it after statusNoticeTTL. Failures are -// logged. -func (g *Gateway) sendEphemeral(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, text string) { - sender := g.newEphemeralSender() - _, err := sender.Send(ctx, g.NewMessageDeleter(b, chatID), messaging.EphemeralReply{ - Event: messaging.MessageEvent{ - Type: messaging.MsgText, - Text: text, - ChannelID: fmt.Sprintf("%d", chatID), - Platform: "telegram", - }, - TTL: statusNoticeTTL, - }, func(ctx context.Context, event messaging.MessageEvent) (messaging.MessageEvent, error) { - id := g.sendTextMessage(ctx, b, chatID, messageThreadID, event.Text) - if id == 0 { - // Nothing was delivered, so there is nothing to name or retract. - return messaging.MessageEvent{}, nil - } - event.ID = fmt.Sprintf("%d", id) - return event, nil - }) - if err != nil { - g.log.ErrorContext(ctx, "ephemeral notice send failed", "error", err) - } -} - -// sendTextMessage sends one message and returns its ID, or 0 when the text -// had to be split. -func (g *Gateway) sendTextMessage(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, text string) int { - blocks := markdownToBlocks(text) - if blockTextLen(blocks) > messageMaxLen { - g.sendMessage(ctx, b, chatID, messageThreadID, text) - return 0 - } - return g.sendBlocks(ctx, b, chatID, messageThreadID, blocks, "send ephemeral message failed") -} diff --git a/internal/channels/telegram/inboundmedia.go b/internal/channels/telegram/inboundmedia.go deleted file mode 100644 index df4de0811..000000000 --- a/internal/channels/telegram/inboundmedia.go +++ /dev/null @@ -1,198 +0,0 @@ -package telegram - -import ( - "context" - "errors" - "fmt" - "io" - "net/http" - - "github.com/go-telegram/bot" - "github.com/go-telegram/bot/models" - - "github.com/samcharles93/archie-core/internal/domain/messaging" -) - -// inboundMedia pairs an inbound attachment with the textual note the -// transcript stores in its place: stored history is text-only, so the -// note is what later turns read once the attachment's bytes are gone. -type inboundMedia struct { - attachment messaging.MediaAttachment - // note is a bracketed, self-describing placeholder such as "[photo]" - // or "[document: report.pdf]". - note string -} - -// extractInboundMedia maps a Telegram message onto the attachment it -// carries. A Telegram message carries at most one file (a photo is the -// set of its resolutions and collapses into one image), so the boolean is -// false exactly for messages with nothing to download. -func extractInboundMedia(msg *models.Message) (inboundMedia, bool) { - switch { - case len(msg.Photo) > 0: - att := messaging.MediaAttachment{Type: "image", MIMEType: "image/jpeg"} - for _, size := range msg.Photo { - if largestPhoto(size, att) { - att.FileID = size.FileID - att.Width, att.Height = &size.Width, &size.Height - if size.FileSize != 0 { - att.FileSize = new(int64(size.FileSize)) - } - } - } - return inboundMedia{attachment: att, note: "[photo]"}, true - - case msg.Document != nil: - return inboundMedia{attachment: messaging.MediaAttachment{ - Type: "document", - FileID: msg.Document.FileID, - MIMEType: msg.Document.MimeType, - FileName: msg.Document.FileName, - FileSize: nilIfZero(msg.Document.FileSize), - }, note: documentNote(msg.Document.FileName)}, true - - case msg.Video != nil: - return inboundMedia{attachment: videoAttachment(msg.Video.FileID, msg.Video.MimeType, nilIfZero(msg.Video.FileSize), &msg.Video.Width, &msg.Video.Height, &msg.Video.Duration), note: "[video]"}, true - - case msg.VideoNote != nil: - size := int64(msg.VideoNote.FileSize) - return inboundMedia{attachment: videoAttachment(msg.VideoNote.FileID, "video/mp4", nilIfZero(size), nil, nil, &msg.VideoNote.Duration), note: "[video message]"}, true - - case msg.Audio != nil: - return inboundMedia{attachment: messaging.MediaAttachment{ - Type: "audio", - FileID: msg.Audio.FileID, - MIMEType: msg.Audio.MimeType, - FileName: msg.Audio.FileName, - FileSize: nilIfZero(msg.Audio.FileSize), - Duration: &msg.Audio.Duration, - }, note: "[audio]"}, true - - case msg.Voice != nil: - return inboundMedia{attachment: messaging.MediaAttachment{ - Type: messaging.MediaTypeVoice, - FileID: msg.Voice.FileID, - MIMEType: msg.Voice.MimeType, - FileSize: nilIfZero(msg.Voice.FileSize), - Duration: &msg.Voice.Duration, - }, note: "[voice message]"}, true - } - return inboundMedia{}, false -} - -// largestPhoto reports whether candidate is larger than the best size -// recorded so far in att's width/height pair. -func largestPhoto(candidate models.PhotoSize, att messaging.MediaAttachment) bool { - if att.Width == nil { - return true - } - candidateArea, bestArea := candidate.Width*candidate.Height, *att.Width**att.Height - return candidateArea > bestArea -} - -func videoAttachment(fileID, mimeType string, fileSize *int64, width, height, duration *int) messaging.MediaAttachment { - return messaging.MediaAttachment{ - Type: "video", FileID: fileID, MIMEType: mimeType, - FileSize: fileSize, Width: width, Height: height, Duration: duration, - } -} - -func documentNote(name string) string { - if name == "" { - return "[document]" - } - return fmt.Sprintf("[document: %s]", name) -} - -func nilIfZero(v int64) *int64 { - if v == 0 { - return nil - } - return &v -} - -// maxInboundDownloadBytes is the Bot API download limit. -var maxInboundDownloadBytes int64 = messaging.MaxInboundAttachmentBytes - -var errInboundMediaTooLarge = errors.New("file exceeds the bot download limit") - -// downloadMedia turns a Telegram file id into the file's bytes: getFile -// resolves the transfer path, then the file is fetched from the Bot API -// server. Called on the turn lane, which is already running the rest of -// the download-and-chat work for this message. The size ceiling is the caller's -// check (messaging.ValidateInbound, before the download); what this enforces is -// the bytes Telegram did not declare. -func (g *Gateway) downloadMedia(ctx context.Context, b *bot.Bot, att messaging.MediaAttachment) ([]byte, error) { - if att.FileID == "" { - return nil, fmt.Errorf("media attachment carries no file id") - } - file, err := b.GetFile(ctx, &bot.GetFileParams{FileID: att.FileID}) - if err != nil { - return nil, fmt.Errorf("resolve telegram file: %w", err) - } - req, err := http.NewRequestWithContext(ctx, http.MethodGet, b.FileDownloadLink(file), nil) - if err != nil { - return nil, fmt.Errorf("download telegram file: %w", err) - } - resp, err := http.DefaultClient.Do(req) - if err != nil { - return nil, fmt.Errorf("download telegram file: %w", err) - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("download telegram file: status %d", resp.StatusCode) - } - data, err := io.ReadAll(io.LimitReader(resp.Body, maxInboundDownloadBytes+1)) - if err != nil { - return nil, fmt.Errorf("download telegram file: %w", err) - } - if int64(len(data)) > maxInboundDownloadBytes { - return nil, errInboundMediaTooLarge - } - return data, nil -} - -// turnMessageText returns the message text, or the attachment note plus -// caption for a message with a file. -func turnMessageText(msg *models.Message, media inboundMedia, hasMedia bool) string { - if !hasMedia { - return msg.Text - } - if msg.Caption == "" { - return media.note - } - return media.note + "\n" + msg.Caption -} - -// unsupportedMediaNotice returns the refusal for unreadable content, or "" -// for updates that need no reply. -func unsupportedMediaNotice(msg *models.Message) string { - switch { - case msg.Sticker != nil: - return "I can't read stickers β€” send the image or file directly and I'll take a look." - case msg.Location != nil: - return "I can't use locations yet." - case msg.Contact != nil: - return "I can't use contact cards yet." - case msg.Poll != nil: - return "I can't use polls yet." - } - return "" -} - -// mediaReplyLabel names an attachment the turn could not serve, in the -// sentence the sender reads. -func mediaReplyLabel(att messaging.MediaAttachment) string { - switch { - case att.Type == "image": - return "I received your photo " - case att.Type == "document" && att.FileName != "": - return fmt.Sprintf("I received %s ", att.FileName) - case att.Type == "document": - return "I received your file " - case att.Type == "video": - return "I received your video " - default: - return "I received your audio attachment " - } -} diff --git a/internal/channels/telegram/interactive.go b/internal/channels/telegram/interactive.go deleted file mode 100644 index d6057ce4a..000000000 --- a/internal/channels/telegram/interactive.go +++ /dev/null @@ -1,209 +0,0 @@ -package telegram - -import ( - "context" - "fmt" - "strings" - "time" - - "github.com/go-telegram/bot" - "github.com/go-telegram/bot/models" - - "github.com/samcharles93/archie-core/internal/domain/messaging" -) - -// interactiveReplyTimeout bounds how long one clarify or picker request waits -// for the user's reply. It matches the approval window so the two blocking -// interactions expire together and neither can wedge a turn indefinitely. -const interactiveReplyTimeout = messaging.ToolApprovalTimeout - -// pendingReplyKey identifies the chat a blocked clarify/picker prompt belongs -// to, so only the addressed user's next text is consumed as the answer. -type pendingReplyKey struct { - chatID int64 - threadID int - recipient int64 -} - -// pendingReply is one clarify/picker prompt waiting on the user's next text. -// It is the text-reply analogue of pendingApproval, kept separate so the -// button (callback) and message (text) models cannot entangle. -type pendingReply struct { - resultCh chan replyResult - expiresAt time.Time -} - -// replyResult carries the user's typed answer (or the wait's error) back to -// the blocked interaction. -type replyResult struct { - text string - err error -} - -// telegramInteractor carries clarify and picker questions as plain text the -// user replies to. -type telegramInteractor struct { - gw *Gateway - bot *bot.Bot - chatID int64 - threadID int - recipient int64 -} - -// Compile-time guards: the adapter carries both interactions and reports them -// through the capability contract, so ClarifierOf/PickerOf resolve it. -var ( - _ messaging.ClarifyRequester = (*telegramInteractor)(nil) - _ messaging.PickerRequester = (*telegramInteractor)(nil) - _ messaging.CapabilityReporter = (*telegramInteractor)(nil) -) - -// Capabilities reports clarify and picker support. -func (i *telegramInteractor) Capabilities() messaging.AdapterCapabilities { - return messaging.AdapterCapabilities{Clarify: true, Picker: true} -} - -// NewInteractor returns the channel's clarify/picker adapter for one chat, -// already resolved to the requesters its capability report advertises. The -// gateway turn stores it with WithInteractive so its question tool can reach -// the user. -func (g *Gateway) NewInteractor(b *bot.Bot, chatID int64, threadID int, recipient int64) messaging.Interactive { - i := &telegramInteractor{ - gw: g, - bot: b, - chatID: chatID, - threadID: threadID, - recipient: recipient, - } - return messaging.InteractiveOf(i) -} - -// RequestClarification poses the question as text and blocks for the reply. -func (i *telegramInteractor) RequestClarification(ctx context.Context, req messaging.ClarifyRequest) (string, error) { - ctx, cancel := context.WithTimeout(ctx, interactiveReplyTimeout) - defer cancel() - fallback := i.fallback() - return fallback.RequestClarification(ctx, req) -} - -// RequestChoice poses the options as numbered text and matches the typed -// reply. The domain's text fallback owns the rendering and matching, so the -// degrade is one implementation rather than a second parser here. -func (i *telegramInteractor) RequestChoice(ctx context.Context, req messaging.PickerRequest) (messaging.InteractiveChoice, error) { - ctx, cancel := context.WithTimeout(ctx, interactiveReplyTimeout) - defer cancel() - fallback := i.fallback() - return fallback.RequestChoice(ctx, req) -} - -// fallback builds a fresh text fallback for one interaction. Registering the -// pending reply inside Send, before the prompt is delivered, closes the race -// where a fast reply arrives before the blocked call is listening. -func (i *telegramInteractor) fallback() messaging.TextFallback { - key := pendingReplyKey{chatID: i.chatID, threadID: i.threadID, recipient: i.recipient} - ch := make(chan replyResult, 1) - return messaging.TextFallback{ - Send: func(ctx context.Context, text string) error { - i.gw.registerPendingReply(key, pendingReply{ - resultCh: ch, - expiresAt: time.Now().Add(interactiveReplyTimeout), - }) - if err := i.send(ctx, text); err != nil { - i.gw.removePendingReply(key) - return err - } - return nil - }, - Reply: func(ctx context.Context) (string, error) { - select { - case res := <-ch: - return res.text, res.err - case <-ctx.Done(): - i.gw.removePendingReply(key) - return "", ctx.Err() - } - }, - } -} - -// send delivers one prompt. ForceReply makes the reply affordance explicit in -// a chat with other traffic, so the user answers the question rather than -// sending a message the turn cannot tell apart from a new request. -func (i *telegramInteractor) send(ctx context.Context, text string) error { - params := &bot.SendMessageParams{ - ChatID: i.chatID, - Text: text, - ReplyMarkup: &models.ForceReply{ForceReply: true, Selective: true}, - } - if i.threadID != 0 { - params.MessageThreadID = i.threadID - } - if _, err := i.bot.SendMessage(ctx, params); err != nil { - return fmt.Errorf("send interactive prompt: %w", err) - } - return nil -} - -// registerPendingReply stores a pending interaction, pruning any that have -// already expired. -func (g *Gateway) registerPendingReply(key pendingReplyKey, pr pendingReply) { - g.interactiveMu.Lock() - defer g.interactiveMu.Unlock() - now := time.Now() - for existing, pending := range g.pendingReplies { - if !pending.expiresAt.After(now) { - delete(g.pendingReplies, existing) - } - } - g.pendingReplies[key] = &pr -} - -// removePendingReply drops a pending interaction, if present. -func (g *Gateway) removePendingReply(key pendingReplyKey) { - g.interactiveMu.Lock() - defer g.interactiveMu.Unlock() - delete(g.pendingReplies, key) -} - -// consumePendingReply atomically claims the pending interaction for the chat -// and delivers the typed answer. It rejects expired entries and reports -// whether the text was consumed as an answer. -func (g *Gateway) consumePendingReply(key pendingReplyKey, text string) bool { - g.interactiveMu.Lock() - pr, found := g.pendingReplies[key] - expired := !found || !pr.expiresAt.After(time.Now()) - if !expired { - delete(g.pendingReplies, key) - } - g.interactiveMu.Unlock() - if expired { - return false - } - select { - case pr.resultCh <- replyResult{text: text}: - return true - default: - // The channel already has a result (the wait timed out between the - // expiry check and now); do not report a reply that was not taken. - return false - } -} - -// deliverInteractiveReply routes a text reply to a blocked clarify/picker -// request when one is pending for this chat and sender, and reports whether -// the message was consumed. A consumed reply is not dispatched as a new turn; -// a command is never consumed, so /stop still cancels the blocked turn. -func (g *Gateway) deliverInteractiveReply(msg *models.Message) bool { - if msg == nil || msg.From == nil { - return false - } - text := strings.TrimSpace(msg.Text) - if text == "" || strings.HasPrefix(text, "/") { - return false - } - return g.consumePendingReply(pendingReplyKey{ - chatID: msg.Chat.ID, - threadID: msg.MessageThreadID, - recipient: msg.From.ID, - }, text) -} diff --git a/internal/channels/telegram/live.go b/internal/channels/telegram/live.go deleted file mode 100644 index 4cb585e98..000000000 --- a/internal/channels/telegram/live.go +++ /dev/null @@ -1,656 +0,0 @@ -package telegram - -import ( - "context" - "errors" - "fmt" - "slices" - "strings" - "sync" - "time" - "unicode/utf8" - - "github.com/go-telegram/bot" - "github.com/go-telegram/bot/models" - - "github.com/samcharles93/archie-core/internal/domain/messaging" -) - -const ( - // liveInterval is the minimum gap between live updates. Telegram rate - // limits per-chat writes, and an LLM emits tokens far faster than any - // human reads, so deltas are coalesced into one edit per tick rather - // than sent individually. - liveInterval = 1 * time.Second - - // liveCursor marks the reply as still being written. It is appended at - // render time and never stored in the buffer, so every frame carries - // exactly one cursor and it is always at the current end. - liveCursor = "β–Œ" - - // fallbackMediaLinePrefix opens the line Media appends when it could - // not deliver an attachment inline, so the user still gets the asset. - fallbackMediaLinePrefix = "πŸ“Ž " - - // liveBodyMaxRunes bounds one mid-turn frame below Telegram's message limit. - // finalize sends the full reply. - liveBodyMaxRunes = 3900 - - // Keep tool activity to a minority of a live frame so the answer remains - // readable even when a turn makes many calls. The remainder is reserved - // for the answer (and the cursor). - liveToolMaxRunes = (liveBodyMaxRunes - 2) / 3 -) - -// liveReply streams one chat turn into a single Telegram message, editing it -// on each update. Rendering is best-effort; finalize writes the final reply. -type liveReply struct { - g *Gateway - b *bot.Bot - chatID int64 - messageThreadID int - showToolCalls bool - // interval throttles updates; zero renders every change. - interval time.Duration - - // newMediaSender builds the MediaSender Media delivers through. - newMediaSender func(b *bot.Bot, chatID int64, threadID int) messaging.MediaSender - - cancelRender context.CancelFunc - renderRequests chan chan struct{} - renderDone chan struct{} - - mu sync.Mutex - // answerBuf is the streamed answer text; tool activity is kept in toolLines. - answerBuf strings.Builder - // toolLines holds the tool activity for this turn, in call order, so - // every rendering stage can lead with it rather than have it buried - // mid-answer or clamped away. - toolLines []string - // failureLines and failureCounts let ToolCall replace a repeated failure - // in place with one counted entry instead of appending noisy retries. - failureLines map[string]int - failureCounts map[string]int - // rendered is the last body actually sent. Telegram rejects an edit - // that changes nothing, so an unchanged body is not sent at all. - rendered string - messageID int - last time.Time - // finalized is set once rendering stops; later writers must send their own - // message. - finalized bool - - // terminal ensures only one of finalize and abandon runs. - terminal sync.Once -} - -// newLiveReply creates a renderer bound to one chat/thread. showToolCalls is -// copied into the reply so a config reload cannot change a turn mid-stream. -func (g *Gateway) newLiveReply(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, showToolCalls bool) *liveReply { - renderCtx, cancelRender := context.WithCancel(ctx) - live := &liveReply{ - g: g, - b: b, - chatID: chatID, - messageThreadID: messageThreadID, - showToolCalls: showToolCalls, - interval: liveInterval, - newMediaSender: g.NewMediaSender, - cancelRender: cancelRender, - renderRequests: make(chan chan struct{}, 1), - renderDone: make(chan struct{}), - failureLines: make(map[string]int), - failureCounts: make(map[string]int), - } - go live.runRenderer(renderCtx) - g.registerLive(ctx, live) - return live -} - -// resetLiveRegistry clears the stopped mark at the start of a launch. -func (g *Gateway) resetLiveRegistry() { - g.liveMu.Lock() - g.liveStopped = false - g.liveMu.Unlock() -} - -// registerLive adds l to the set Stop drains, or abandons it at once if the -// registry is already stopped. -func (g *Gateway) registerLive(ctx context.Context, l *liveReply) { - g.liveMu.Lock() - if g.liveStopped { - g.liveMu.Unlock() - go l.abandonRestarted(context.WithoutCancel(ctx)) - return - } - if g.liveReplies == nil { - g.liveReplies = make(map[*liveReply]struct{}) - } - g.liveReplies[l] = struct{}{} - g.liveMu.Unlock() -} - -// forgetLive removes l from the registry. -func (g *Gateway) forgetLive(l *liveReply) { - g.liveMu.Lock() - defer g.liveMu.Unlock() - delete(g.liveReplies, l) -} - -// abandonAllLiveTimeout bounds how long Stop waits for in-flight replies. -const abandonAllLiveTimeout = 5 * time.Second - -// abandonAllLive marks every still-streaming reply as interrupted on stop or -// restart, and stops the registry under the same lock. -func (g *Gateway) abandonAllLive(ctx context.Context) { - g.liveMu.Lock() - g.liveStopped = true - live := make([]*liveReply, 0, len(g.liveReplies)) - for l := range g.liveReplies { - live = append(live, l) - } - clear(g.liveReplies) - g.liveMu.Unlock() - - if len(live) == 0 { - return - } - - timeout := g.liveDrainTimeout - if timeout <= 0 { - timeout = abandonAllLiveTimeout - } - - done := make(chan struct{}) - go func() { - defer close(done) - var wg sync.WaitGroup - for _, l := range live { - wg.Go(func() { l.abandonRestarted(ctx) }) - } - wg.Wait() - }() - - select { - case <-done: - case <-time.After(timeout): - g.log.WarnContext(ctx, "gateway stop: gave up waiting for in-flight replies to be marked as restarted", - "pending", len(live), "timeout", timeout) - } -} - -func (l *liveReply) runRenderer(ctx context.Context) { - defer close(l.renderDone) - for { - select { - case <-ctx.Done(): - return - case completed := <-l.renderRequests: - l.render(ctx) - if completed != nil { - close(completed) - } - } - } -} - -func (l *liveReply) requestRender() { - select { - case l.renderRequests <- nil: - default: - } -} - -func (l *liveReply) flushRendering() { - completed := make(chan struct{}) - select { - case l.renderRequests <- completed: - case <-l.renderDone: - return - } - select { - case <-completed: - case <-l.renderDone: - } -} - -func (l *liveReply) stopRendering() { - l.cancelRender() - <-l.renderDone - l.mu.Lock() - l.finalized = true - l.mu.Unlock() -} - -// Delta appends the next fragment of assistant text. It satisfies -// gateway.TurnStream. -func (l *liveReply) Delta(text string) { - if text == "" { - return - } - l.mu.Lock() - l.answerBuf.WriteString(text) - throttled := time.Since(l.last) < l.interval - l.mu.Unlock() - if throttled { - return - } - l.requestRender() -} - -// ToolCall appends one escaped tool-activity line, when tool display is on. -func (l *liveReply) ToolCall(event messaging.ToolCallEvent) { - if !l.showToolCalls || event.Name == "" { - return - } - // Render the completed result as a compact fenced block. Do not append the - // raw/JSON-shaped parameters: they are noisy, can expose secrets, and were - // the source of unreadable schema placeholders in Telegram. - line := messaging.RenderToolCall(event) - key := messaging.FailureKey(event) - - l.mu.Lock() - if index, ok := l.failureLines[key]; key != "" && ok { - l.failureCounts[key]++ - l.toolLines[index] = countedToolLine(line, l.failureCounts[key]) - } else { - l.toolLines = append(l.toolLines, line) - if key != "" { - l.failureLines[key] = len(l.toolLines) - 1 - l.failureCounts[key] = 1 - } - } - l.mu.Unlock() - - // A tool call is a discrete event rather than a token, and there are - // few of them: wake the renderer immediately so the user sees what ran - // while it is still relevant. The callback itself never waits on HTTP. - l.requestRender() -} - -// toolLineSeparator ends each tool line with a Markdown hard break. -const toolLineSeparator = " \n" - -func countedToolLine(line string, count int) string { - if count <= 1 { - return line - } - marker := fmt.Sprintf(" Γ—%d", count) - if cut := strings.Index(line, messaging.ToolPreviewSeparator); cut >= 0 { - return line[:cut] + marker + line[cut:] - } - return line + marker -} - -// mediaSendTimeout bounds one Media delivery, independent of the turn. -const mediaSendTimeout = 30 * time.Second - -// Media uploads the attachment in the background. An attachment with no URL -// or Path is skipped. -func (l *liveReply) Media(ctx context.Context, event messaging.MediaEvent) { - if event.Attachment.URL == "" && event.Attachment.Path == "" { - return - } - - go func() { - sender := l.newMediaSender(l.b, l.chatID, l.messageThreadID) - - // Checked before attempting delivery, not just on failure: that is - // the entire point of CapabilityReporter over attempt-then-catch - // -- a sender that already knows it cannot deliver a given media - // kind should never cost a doomed network round trip to find out. - if !messaging.CapabilitiesOf(sender).Media { - l.g.log.DebugContext(ctx, "channel cannot deliver media inline, falling back to a link", - "tool", event.ToolName, "type", event.Attachment.Type) - l.appendFallbackLine(ctx, event.Attachment) - return - } - - sendCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), mediaSendTimeout) - defer cancel() - - _, err := sender.SendMedia(sendCtx, messaging.MessageEvent{ - Media: []messaging.MediaAttachment{event.Attachment}, - }) - if err == nil { - return - } - - l.g.log.WarnContext(ctx, "media delivery failed, falling back to a link", - "tool", event.ToolName, "type", event.Attachment.Type, "error", err) - l.appendFallbackLine(ctx, event.Attachment) - }() -} - -// appendFallbackLine renders att as a visible link in the reply, for a -// MediaEvent that could not be (or was not attempted to be) delivered -// inline. -func (l *liveReply) appendFallbackLine(ctx context.Context, att messaging.MediaAttachment) { - // A local attachment has no URL to fall back to, and printing an empty - // one reads as a delivered file. Say plainly that it was not sent: - // the whole defect this path exists around is that non-delivery and - // success looked the same to everyone downstream, the agent included. - line := fallbackMediaLinePrefix + bot.EscapeMarkdown(att.Type) + ": " + att.URL - if att.URL == "" { - name := att.FileName - if name == "" { - name = att.Path - } - line = fallbackMediaLinePrefix + "could not send " + bot.EscapeMarkdown(name) - } - - l.mu.Lock() - if l.finalized { - // The renderer that would have picked up toolLines is already - // gone -- requestRender below would be a silent no-op, and the - // live message it would have edited is done being edited. Send - // this as its own message instead of dropping it. - l.mu.Unlock() - sendCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), mediaSendTimeout) - defer cancel() - l.g.sendMessage(sendCtx, l.b, l.chatID, l.messageThreadID, line) - return - } - l.toolLines = append(l.toolLines, line) - l.mu.Unlock() - l.requestRender() -} - -// render writes the current buffer, cursor and all, to the live message. -func (l *liveReply) render(ctx context.Context) { - l.mu.Lock() - body := l.body() - if body == "" || body == l.rendered { - l.mu.Unlock() - return - } - messageID := l.messageID - l.mu.Unlock() - - // Mid-stream text is frequently unbalanced Markdown (an unclosed ** or - // code fence); a rejected update is logged and skipped, and the next - // tick -- or finalize -- corrects it. - if messageID == 0 { - l.open(ctx, markdownToBlocks(body)) - return - } - if err := l.edit(ctx, messageID, markdownToBlocks(body)); err == nil { - l.markRendered(body) - } -} - -func (l *liveReply) markRendered(body string) { - l.mu.Lock() - l.rendered = body - l.last = time.Now() - l.mu.Unlock() -} - -// finalize replaces the live message with the tool activity and the final -// reply, or sends a new message if nothing streamed. It ignores ctx -// cancellation and runs at most once. -func (l *liveReply) finalize(ctx context.Context, reply string) { - ctx = context.WithoutCancel(ctx) - l.terminal.Do(func() { l.doFinalize(ctx, reply) }) -} - -func (l *liveReply) doFinalize(ctx context.Context, reply string) { - l.g.forgetLive(l) - - // Finish any queued live frame before replacing it, then retire the - // worker so no stale edit can race the authoritative delivery. - l.flushRendering() - l.stopRendering() - - l.mu.Lock() - content := l.finalText(reply) - messageID := l.messageID - l.mu.Unlock() - - if content == "" { - l.abandonStopped(ctx) - return - } - if messageID == 0 { - l.g.sendMessage(ctx, l.b, l.chatID, l.messageThreadID, content) - return - } - - // Edit the first part into the live message and send the rest; if the edit - // fails, send the whole reply. - parts := splitBlocks(markdownToBlocks(content), messageMaxLen) - if len(parts) == 0 { - l.abandonStopped(ctx) - return - } - if err := l.edit(ctx, messageID, parts[0]); err != nil { - l.g.sendMessage(ctx, l.b, l.chatID, l.messageThreadID, content) - return - } - l.markRendered(strings.Join(blocksToPlainText(parts[0]), "\n\n")) - for _, part := range parts[1:] { - l.g.sendBlocks(ctx, l.b, l.chatID, l.messageThreadID, part, "send message part failed") - } -} - -// abandonMarker is appended to a failed turn's partial text so it cannot be -// mistaken for a finished answer: without it, a truncated reply and a -// completed one are visually identical, and Telegram messages are -// immutable, so nothing can correct that impression after the fact. -const abandonMarker = "\n\n❌ _turn failed before finishing_" - -// abandon leaves a stopped turn's partial text without the cursor. It ignores -// ctx cancellation and runs at most once. -func (l *liveReply) abandon(ctx context.Context) { - ctx = context.WithoutCancel(ctx) - l.terminal.Do(func() { l.doAbandon(ctx) }) -} - -func (l *liveReply) doAbandon(ctx context.Context) { - l.g.forgetLive(l) - l.stopRendering() - l.abandonStopped(ctx) -} - -// abandonFailed leaves a failed turn readable and visibly marked as failed, -// unlike abandon: a provider error is not an acknowledged interruption, so -// the partial text alone would read as the finished answer and the user -// could act on incomplete information. -func (l *liveReply) abandonFailed(ctx context.Context) { - l.mu.Lock() - l.answerBuf.WriteString(abandonMarker) - l.mu.Unlock() - l.abandon(ctx) -} - -// restartMarker marks a turn cut off by a gateway restart. -const restartMarker = "\n\n⚠️ _archie restarted before finishing -- send your message again_" - -// abandonRestarted marks a turn interrupted by a gateway stop or restart. -func (l *liveReply) abandonRestarted(ctx context.Context) { - l.mu.Lock() - l.answerBuf.WriteString(restartMarker) - l.mu.Unlock() - l.abandon(ctx) -} - -func (l *liveReply) abandonStopped(ctx context.Context) { - l.mu.Lock() - answer := strings.TrimRight(l.answerBuf.String(), " \t\n") - // Bounded for the same reason a live frame is: this is still one edit - // of one message, and a stopped turn that had already streamed past - // the limit would keep its cursor if the edit were rejected. - text := l.framedText(answer) - messageID := l.messageID - if text == "" || text == l.rendered { - l.mu.Unlock() - return - } - l.mu.Unlock() - - if messageID == 0 { - l.g.sendMessage(ctx, l.b, l.chatID, l.messageThreadID, text) - return - } - if err := l.edit(ctx, messageID, markdownToBlocks(text)); err == nil { - l.markRendered(text) - } -} - -// body renders a mid-turn frame: tool activity so far, then the answer text -// streamed so far, then the cursor. The caller holds the lock. -func (l *liveReply) body() string { - answer := strings.TrimRight(l.answerBuf.String(), " \t\n") - if answer == "" && len(l.toolLines) == 0 { - return "" - } - return l.framedText(answer) + " " + liveCursor -} - -// framedText composes tool activity ahead of the answer text and clamps the -// whole thing to fit one Telegram message. The caller holds the lock. -func (l *liveReply) framedText(answer string) string { - if len(l.toolLines) == 0 { - return l.clampAnswer(answer, liveBodyMaxRunes-2) - } - block := l.toolBlock() - if answer == "" { - return block - } - // Reserve the larger share of the frame for the answer. The two extra - // runes are the separator and the cursor appended by body. - budget := liveBodyMaxRunes - 2 - utf8.RuneCountInString(block) - 2 - if budget <= 0 { - return block - } - return block + "\n\n" + l.clampAnswer(answer, budget) -} - -// clampAnswer keeps the newest budget runes of answer, prefixed with an -// ellipsis when cut. -func (l *liveReply) clampAnswer(answer string, budget int) string { - return clampToRunes(answer, budget) -} - -// toolBlock returns the newest tool lines that fit the budget, prefixed with -// a count of the rest. The caller holds the lock. -func (l *liveReply) toolBlock() string { - if len(l.toolLines) == 0 { - return "" - } - best := -1 - for start := range slices.Backward(l.toolLines) { - if utf8.RuneCountInString(l.toolBlockWith(start)) > liveToolMaxRunes { - break - } - best = start - } - if best >= 0 { - return l.toolBlockWith(best) - } - // Even the newest line alone overflows, so it is the only line retained - // and every older line must be reflected in the indicator. - omitted := len(l.toolLines) - 1 - prefix := "" - if omitted > 0 { - prefix = fmt.Sprintf("+%d earlier\n\n", omitted) - } - available := liveToolMaxRunes - utf8.RuneCountInString(prefix) - if available <= 0 { - return clampToRunes(prefix, liveToolMaxRunes) - } - return prefix + clampToRunes(l.toolLines[len(l.toolLines)-1], available) -} - -// toolBlockWith renders the activity from index start to the newest line, -// including the "+N earlier" indicator for whatever precedes start. -func (l *liveReply) toolBlockWith(start int) string { - prefix := "" - if omitted := start; omitted > 0 { - prefix = fmt.Sprintf("+%d earlier\n\n", omitted) - } - return prefix + strings.Join(l.toolLines[start:], toolLineSeparator) -} - -// clampToRunes cuts s to its last maxRunes runes, marking the cut with a -// leading ellipsis. -func clampToRunes(s string, maxRunes int) string { - runes := []rune(s) - if len(runes) <= maxRunes { - return s - } - if maxRunes <= 1 { - return "…" - } - return "…" + string(runes[len(runes)-(maxRunes-1):]) -} - -// finalText returns the tool activity followed by reply, noting when tools -// ran without a reply. The caller holds the lock. -func (l *liveReply) finalText(reply string) string { - reply = strings.TrimSpace(reply) - if len(l.toolLines) == 0 { - return reply - } - block := strings.Join(l.toolLines, toolLineSeparator) - if reply == "" { - return block + "\n\n_(no response)_" - } - return block + "\n\n" + reply -} - -// open creates the live message and records its ID for later edits. -func (l *liveReply) open(ctx context.Context, blocks []models.InputRichBlock) { - params := &bot.SendRichMessageParams{ - ChatID: l.chatID, - RichMessage: models.InputRichMessage{Blocks: blocks}, - } - if l.messageThreadID != 0 { - params.MessageThreadID = l.messageThreadID - } - msg, err := l.b.SendRichMessage(ctx, params) - if err != nil { - l.g.log.DebugContext(ctx, "live reply rich send failed, retrying unformatted", "error", err) - plain := &bot.SendMessageParams{ChatID: l.chatID, Text: strings.Join(blocksToPlainText(blocks), "\n\n")} - if l.messageThreadID != 0 { - plain.MessageThreadID = l.messageThreadID - } - msg, err = l.b.SendMessage(ctx, plain) - if err != nil { - l.g.log.DebugContext(ctx, "live reply send failed", "error", err) - return - } - } - l.mu.Lock() - l.messageID = msg.ID - l.rendered = strings.Join(blocksToPlainText(blocks), "\n\n") - l.last = time.Now() - l.mu.Unlock() -} - -// edit replaces the live message's content, retrying as plain text if the -// rich body is rejected. -func (l *liveReply) edit(ctx context.Context, messageID int, blocks []models.InputRichBlock) error { - _, richErr := l.b.EditMessageText(ctx, &bot.EditMessageTextParams{ - ChatID: l.chatID, - MessageID: messageID, - RichMessage: &models.InputRichMessage{Blocks: blocks}, - }) - if richErr == nil { - return nil - } - l.g.log.DebugContext(ctx, "live reply rich edit failed, retrying unformatted", "error", richErr) - - if _, plainErr := l.b.EditMessageText(ctx, &bot.EditMessageTextParams{ - ChatID: l.chatID, - MessageID: messageID, - Text: strings.Join(blocksToPlainText(blocks), "\n\n"), - }); plainErr != nil { - l.g.log.DebugContext(ctx, "live reply edit failed", "error", plainErr) - return errors.Join( - fmt.Errorf("rich edit: %w", richErr), - fmt.Errorf("plain edit: %w", plainErr), - ) - } - return nil -} diff --git a/internal/channels/telegram/media.go b/internal/channels/telegram/media.go deleted file mode 100644 index 3102d44ff..000000000 --- a/internal/channels/telegram/media.go +++ /dev/null @@ -1,213 +0,0 @@ -package telegram - -import ( - "context" - "errors" - "fmt" - "os" - "path/filepath" - - "github.com/go-telegram/bot" - "github.com/go-telegram/bot/models" - - "github.com/samcharles93/archie-core/internal/domain/messaging" -) - -// telegramMediaSender sends attachments through the media Bot API methods, -// using the bot it was built with. A URL is fetched by Telegram; a Path is -// uploaded. FileIDs are not accepted. -type telegramMediaSender struct { - bot *bot.Bot - chatID int64 - threadID int -} - -var ( - _ messaging.MediaSender = (*telegramMediaSender)(nil) - _ messaging.CapabilityReporter = (*telegramMediaSender)(nil) -) - -// NewMediaSender returns a MediaSender bound to one chat and to the bot -// instance of the launch that created it. Construct it per launch, from -// the same b that handled the update, never from a stored field. -func (g *Gateway) NewMediaSender(b *bot.Bot, chatID int64, threadID int) messaging.MediaSender { - return &telegramMediaSender{bot: b, chatID: chatID, threadID: threadID} -} - -// Capabilities reports Media support. Telegram implements every media -// kind MediaAttachment can describe, so this is unconditionally true. -func (s *telegramMediaSender) Capabilities() messaging.AdapterCapabilities { - return messaging.AdapterCapabilities{Media: true} -} - -// errNoMedia and errNoSource are the two ways an event can be -// undeliverable before any request is made. -var ( - errNoMedia = errors.New("message event carries no media attachment") - // errNoSource replaces the former errNoURL: an attachment is now - // deliverable with either a URL or a local Path, so having neither -- - // not having no URL -- is what makes it undeliverable. - errNoSource = errors.New("media attachment has neither a URL nor a local path") -) - -// Bot API upload ceilings, in bytes. Photos are capped far lower than -// everything else, and exceeding either is a 400 from Telegram with a -// message the operator never sees; checking here turns that into a -// reported failure with the actual size in it. -const ( - maxPhotoUploadBytes int64 = 10 * 1024 * 1024 - maxFileUploadBytes int64 = 50 * 1024 * 1024 -) - -// SendMedia delivers the event's first attachment, captioned with the -// event text. Only the first is sent: a caption belongs to one file, and -// batching several into a media group is a distinct API with its own -// caption semantics. -func (s *telegramMediaSender) SendMedia(ctx context.Context, event messaging.MessageEvent) (messaging.SendResult, error) { - if len(event.Media) == 0 { - return invalidMedia(errNoMedia) - } - att := event.Media[0] - if att.URL == "" && att.Path == "" { - return invalidMedia(fmt.Errorf("%w (type %q)", errNoSource, att.Type)) - } - - file, closeFile, err := s.source(att) - if err != nil { - return invalidMedia(err) - } - defer closeFile() - - msg, err := s.dispatch(ctx, att, file, event.Text) - if err != nil { - if errors.Is(err, errUnsupportedMediaType) { - return invalidMedia(err) - } - res := classifySendError(err) - res.Error = fmt.Errorf("send %s: %w", att.Type, err) - return res, res.Error - } - - id := "" - if msg != nil { - id = fmt.Sprintf("%d", msg.ID) - } - return messaging.SendResult{Success: true, MessageID: id}, nil -} - -var ( - errUnsupportedMediaType = errors.New("unsupported media type") - errNotRegularFile = errors.New("not a regular file") - errTooLarge = errors.New("file exceeds the Telegram upload limit") -) - -// source returns the Bot API file for att and a release function. It refuses -// a local file over the size limit. -func (s *telegramMediaSender) source(att messaging.MediaAttachment) (models.InputFile, func(), error) { - noop := func() {} - if att.Path == "" { - return &models.InputFileString{Data: att.URL}, noop, nil - } - - info, err := os.Stat(att.Path) - if err != nil { - return nil, noop, fmt.Errorf("attach %s: %w", att.Path, err) - } - if !info.Mode().IsRegular() { - return nil, noop, fmt.Errorf("attach %s: %w", att.Path, errNotRegularFile) - } - if limit := uploadLimit(att.Type); info.Size() > limit { - return nil, noop, fmt.Errorf("attach %s: %w: %d bytes exceeds %d", - att.Path, errTooLarge, info.Size(), limit) - } - - f, err := os.Open(att.Path) - if err != nil { - return nil, noop, fmt.Errorf("attach %s: %w", att.Path, err) - } - - name := att.FileName - if name == "" { - name = filepath.Base(att.Path) - } - return &models.InputFileUpload{Filename: name, Data: f}, func() { _ = f.Close() }, nil -} - -// uploadLimit reports the Bot API ceiling for a media kind. Photos have -// their own, much lower one; everything else shares the general file -// limit. -func uploadLimit(mediaType string) int64 { - if mediaType == "image" { - return maxPhotoUploadBytes - } - return maxFileUploadBytes -} - -// dispatch routes an attachment to the Bot API method for its kind. The -// media type, not the MessageEvent type, decides: the event type describes -// the message while the attachment describes the file, and Telegram -// rejects a video sent through sendPhoto. -func (s *telegramMediaSender) dispatch(ctx context.Context, att messaging.MediaAttachment, file models.InputFile, caption string) (*models.Message, error) { - switch att.Type { - case "video": - p := &bot.SendVideoParams{ChatID: s.chatID, Video: file, Caption: caption} - p.MessageThreadID = s.threadID - if att.Width != nil { - p.Width = *att.Width - } - if att.Height != nil { - p.Height = *att.Height - } - if att.Duration != nil { - p.Duration = *att.Duration - } - return s.bot.SendVideo(ctx, p) - case "image": - p := &bot.SendPhotoParams{ChatID: s.chatID, Photo: file, Caption: caption} - p.MessageThreadID = s.threadID - return s.bot.SendPhoto(ctx, p) - case "audio": - p := &bot.SendAudioParams{ChatID: s.chatID, Audio: file, Caption: caption} - p.MessageThreadID = s.threadID - if att.Duration != nil { - p.Duration = *att.Duration - } - return s.bot.SendAudio(ctx, p) - case "document": - p := &bot.SendDocumentParams{ChatID: s.chatID, Document: file, Caption: caption} - p.MessageThreadID = s.threadID - return s.bot.SendDocument(ctx, p) - default: - return nil, fmt.Errorf("%w %q", errUnsupportedMediaType, att.Type) - } -} - -// invalidMedia reports a failure that was detected before any request was -// made. Never retryable: resending an event that carries nothing, or names -// a type Telegram has no method for, fails identically every time. -func invalidMedia(err error) (messaging.SendResult, error) { - return messaging.SendResult{ - Success: false, - Retryable: false, - Error: err, - ErrorCode: "invalid_message", - }, err -} - -// classifySendError maps a Bot API error to a SendResult. Unrecognised errors -// are retryable. -func classifySendError(err error) messaging.SendResult { - res := messaging.SendResult{Success: false, Error: err} - - switch { - case bot.IsTooManyRequestsError(err) || errors.Is(err, bot.ErrorTooManyRequests): - res.Retryable, res.ErrorCode = true, "rate_limited" - case errors.Is(err, bot.ErrorUnauthorized), errors.Is(err, bot.ErrorForbidden): - res.Retryable, res.ErrorCode = false, "auth" - case errors.Is(err, bot.ErrorBadRequest), errors.Is(err, bot.ErrorNotFound): - res.Retryable, res.ErrorCode = false, "invalid_message" - default: - res.Retryable, res.ErrorCode = true, "network" - } - return res -} diff --git a/internal/channels/telegram/model.go b/internal/channels/telegram/model.go deleted file mode 100644 index 0ad5f6743..000000000 --- a/internal/channels/telegram/model.go +++ /dev/null @@ -1,557 +0,0 @@ -package telegram - -import ( - "context" - "crypto/sha256" - "fmt" - "strings" - - "github.com/go-telegram/bot" - "github.com/go-telegram/bot/models" - - "github.com/samcharles93/archie-core/internal/domain/messaging" -) - -const ( - modelCallbackPrefix = "model:" - modelPageCallbackPrefix = "modelpage:" - modelBackCallback = "modelback" - modelCancelCallback = "modelcancel" - modelNoopCallback = "modelnoop" - modelPageSize = 8 -) - -type modelPage struct { - Provider string - Page int -} - -func isModelSelectorRequest(text string) bool { - fields := strings.Fields(text) - if len(fields) != 1 { - return false - } - command, _, _ := strings.Cut(fields[0], "@") - return command == "/model" -} - -// isModelCommand checks whether text is a /model command, with or without -// arguments. When the user provides a model ref or flags, the inline -// selector is skipped and the command is handled directly. -func isModelCommand(text string) bool { - fields := strings.Fields(text) - if len(fields) == 0 { - return false - } - command, _, _ := strings.Cut(fields[0], "@") - return command == "/model" -} - -// parseModelRest extracts model, provider, and scope flags from the text -// after the /model command token. It handles --provider=<name>, -// --provider <name>, --global, --session, and --refresh. -func parseModelRest(rest string) (model, provider string, global, session, refresh bool) { - provider, fields := splitProviderFlag(strings.Fields(rest)) - var modelParts []string - for _, f := range fields { - switch f { - case "--global": - global = true - case "--session": - session = true - case "--refresh": - refresh = true - default: - modelParts = append(modelParts, f) - } - } - model = strings.Join(modelParts, " ") - return model, provider, global, session, refresh -} - -// splitProviderFlag extracts --provider=<value> or --provider <value> and -// returns the provider along with the fields that remain. -func splitProviderFlag(fields []string) (provider string, remaining []string) { - for i := 0; i < len(fields); i++ { - f := fields[i] - if !strings.HasPrefix(f, "--provider") { - remaining = append(remaining, f) - continue - } - if after, ok := strings.CutPrefix(f, "--provider="); ok { - provider = after - continue - } - // --provider <value> (space-separated) - if i+1 < len(fields) && !strings.HasPrefix(fields[i+1], "--") { - provider = fields[i+1] - i++ - } - } - return provider, remaining -} - -// handleModelCommand handles /model with arguments, performing direct -// model/provider switching, scope selection, and model refresh. -func (g *Gateway) handleModelCommand( - ctx context.Context, - b *bot.Bot, - msg *models.Message, - client messaging.ChatContract, -) { - snap, err := client.Snapshot(ctx) - if err != nil || len(snap.Models) == 0 { - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Model switching is not configured.") - return - } - - text := strings.TrimSpace(msg.Text) - fields := strings.Fields(text) - rest := "" - if len(fields) > 1 { - cmdToken := fields[0] - if _, after, ok := strings.Cut(text, cmdToken); ok { - rest = strings.TrimSpace(after) - } - } - - model, provider, global, _, refresh := parseModelRest(rest) - - // --refresh: no-op for now (catalog is loaded at startup). Show current. - if refresh { - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, - fmt.Sprintf("Active model: %s.", modelDisplayName(snap.ActiveModel, ""))) - return - } - - // --provider without a specific model: switch provider only. - if provider != "" && model == "" { - models := snap.ModelsByProvider[provider] - if len(models) == 0 { - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Provider switching is not configured.") - return - } - g.switchModel(ctx, b, msg, client, models[0], global) - return - } - - // A provider-qualified direct selection is one atomic model mutation. - if provider != "" && model != "" { - if !strings.HasPrefix(model, provider+"/") { - model = provider + "/" + model - } - } - - // Switch model. - if model != "" { - g.switchModel(ctx, b, msg, client, model, global) - return - } - - // Neither model nor provider: delegate to inline selector. - g.sendModelSelector(ctx, b, msg, client) -} - -// switchModel activates a model and sends confirmation. When global is true -// the new selection is persisted across restarts. -func (g *Gateway) switchModel( - ctx context.Context, - b *bot.Bot, - msg *models.Message, - client messaging.ChatContract, - model string, - global bool, -) { - reply, err := client.Route(ctx, messaging.Inbound{ - Message: messaging.Message{ - ConversationID: conversationID(msg), - Sender: msg.From.Username, - Role: messaging.RoleUser, - Text: "/model " + model, - }, - }) - if err != nil { - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, - fmt.Sprintf("Cannot switch: %v", err)) - return - } - if strings.HasPrefix(reply.Text, "Cannot switch") { - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply.Text) - return - } - provider, _, _ := strings.Cut(model, "/") - result := fmt.Sprintf("Model changed to %s.", modelDisplayName(model, provider)) - if global { - result += " (global persistence is not configured)" - } - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, result) -} - -func (g *Gateway) sendModelSelector( - ctx context.Context, - b *bot.Bot, - msg *models.Message, - client messaging.ChatContract, -) { - snap, err := client.Snapshot(ctx) - if err != nil || len(snap.Models) == 0 { - reply, err := client.Route(ctx, messaging.Inbound{ - Message: messaging.Message{Role: messaging.RoleUser, Text: "/model"}, - }) - if err != nil { - g.log.ErrorContext(ctx, "model selector fallback failed", "error", err) - return - } - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply.Text) - return - } - - params := &bot.SendMessageParams{ - ChatID: msg.Chat.ID, - Text: modelSelectorText(snap.ActiveModel), - ReplyMarkup: g.modelSelectorKeyboard(snap.ActiveModel, snap.Models, snap.ActiveProvider, snap.ModelsByProvider), - } - if msg.MessageThreadID != 0 { - params.MessageThreadID = msg.MessageThreadID - } - if _, err := b.SendMessage(ctx, params); err != nil { - g.log.ErrorContext(ctx, "send model selector failed", "error", err) - } -} - -func modelSelectorText(active string) string { - if active == "" { - return "Select a model:" - } - provider, _, ok := strings.Cut(active, "/") - if !ok { - return "Select a model:\nActive: " + active - } - return "Select a model:\nCurrent Provider: " + providerDisplayName(provider) + - "\nActive: " + modelDisplayName(active, provider) -} - -func modelSelectorTextForProvider(provider string, page, count int) string { - start, end := pageBounds(page, count) - return fmt.Sprintf("βš™ Model Configuration\n\nProvider: %s (%d–%d of %d)\nSelect a model:", - providerDisplayName(provider), start+1, end, count) -} - -func (g *Gateway) modelSelectorKeyboard(active string, models []string, activeProvider string, modelsByProvider map[string][]string) *models.InlineKeyboardMarkup { - provider := activeProvider - available := models - if provider != "" && len(modelsByProvider[provider]) > 0 { - available = modelsByProvider[provider] - } - return g.modelSelectorKeyboardPage(active, available, provider, 0) -} - -func (g *Gateway) modelSelectorKeyboardPage(active string, available []string, provider string, page int) *models.InlineKeyboardMarkup { - start, end := pageBounds(page, len(available)) - buttons := make([]models.InlineKeyboardButton, 0, end-start) - for _, model := range available[start:end] { - label := modelDisplayName(model, provider) - if model == active { - label = "βœ“ " + label - } - buttons = append(buttons, models.InlineKeyboardButton{ - Text: label, - CallbackData: g.modelCallbackToken(model), - }) - } - rows := make([][]models.InlineKeyboardButton, 0, (len(buttons)+1)/2+2) - for i := 0; i < len(buttons); i += 2 { - rows = append(rows, buttons[i:min(i+2, len(buttons))]) - } - pages := max(1, (len(available)+modelPageSize-1)/modelPageSize) - if pages > 1 { - var nav []models.InlineKeyboardButton - if page > 0 { - nav = append(nav, models.InlineKeyboardButton{ - Text: "β—€ Prev", CallbackData: g.modelPageCallbackToken(provider, page-1), - }) - } - nav = append(nav, models.InlineKeyboardButton{ - Text: fmt.Sprintf("%d/%d", page+1, pages), CallbackData: modelNoopCallback, - }) - if page+1 < pages { - nav = append(nav, models.InlineKeyboardButton{ - Text: "Next β–Ά", CallbackData: g.modelPageCallbackToken(provider, page+1), - }) - } - rows = append(rows, nav) - } - rows = append(rows, []models.InlineKeyboardButton{ - {Text: "β—€ Back", CallbackData: modelBackCallback}, - {Text: "βœ— Cancel", CallbackData: modelCancelCallback}, - }) - return &models.InlineKeyboardMarkup{InlineKeyboard: rows} -} - -func pageBounds(page, count int) (int, int) { - pages := max(1, (count+modelPageSize-1)/modelPageSize) - page = max(0, min(page, pages-1)) - start := page * modelPageSize - return start, min(start+modelPageSize, count) -} - -func (g *Gateway) modelPageCallbackToken(provider string, page int) string { - sum := sha256.Sum256(fmt.Appendf(nil, "%s:%d", provider, page)) - token := fmt.Sprintf("%s%x", modelPageCallbackPrefix, sum[:24]) - g.modelMu.Lock() - g.modelPages[token] = modelPage{Provider: provider, Page: page} - g.modelMu.Unlock() - return token -} - -func (g *Gateway) modelPageForCallback(token string) (modelPage, bool) { - g.modelMu.RLock() - defer g.modelMu.RUnlock() - page, ok := g.modelPages[token] - return page, ok -} - -func (g *Gateway) modelCallbackToken(model string) string { - sum := sha256.Sum256([]byte(model)) - token := fmt.Sprintf("%s%x", modelCallbackPrefix, sum[:24]) - g.modelMu.Lock() - g.modelCallbacks[token] = model - g.modelMu.Unlock() - return token -} - -func (g *Gateway) modelForCallback(token string) (string, bool) { - g.modelMu.RLock() - defer g.modelMu.RUnlock() - model, ok := g.modelCallbacks[token] - return model, ok -} - -func modelDisplayName(ref, provider string) string { - name := strings.TrimPrefix(ref, provider+"/") - if slash := strings.LastIndexByte(name, '/'); slash >= 0 { - name = name[slash+1:] - } - return name -} - -func (g *Gateway) handleModelCallback( - ctx context.Context, - b *bot.Bot, - update *models.Update, - client messaging.ChatContract, -) { - query := update.CallbackQuery - if query == nil { - return - } - if !g.isSenderAllowed(query.From.ID) { - g.log.WarnContext(ctx, "model callback from unauthorized sender", "user_id", query.From.ID) - g.answerModelCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true) - return - } - selected, ok := g.modelForCallback(query.Data) - if !ok { - g.answerModelCallback(ctx, b, query.ID, "That model selection is no longer valid.", true) - return - } - - reply, err := client.Route(ctx, messaging.Inbound{ - Message: messaging.Message{ - Role: messaging.RoleUser, - Text: "/model " + selected, - }, - }) - if err != nil { - g.answerModelCallback(ctx, b, query.ID, fmt.Sprintf("Cannot switch: %v", err), true) - return - } - if strings.HasPrefix(reply.Text, "Cannot switch") { - g.answerModelCallback(ctx, b, query.ID, reply.Text, true) - return - } - - provider, _, _ := strings.Cut(selected, "/") - g.answerModelCallback(ctx, b, query.ID, - "The model has been changed to: "+modelDisplayName(selected, provider), false) - g.editModelPicker(ctx, b, query, modelSelectionConfirmation(client, selected), nil) -} - -func modelSelectionConfirmation(manager any, ref string) string { - provider, _, _ := strings.Cut(ref, "/") - var b strings.Builder - fmt.Fprintf(&b, "Model switched to %s\nProvider: %s", - modelDisplayName(ref, provider), providerDisplayName(provider)) - detailed, ok := manager.(messaging.DetailedModelManager) - if !ok { - b.WriteString("\n\n_(active for this daemon process; resets on restart)_") - return b.String() - } - details, ok := detailed.ModelDetails(ref) - if !ok { - b.WriteString("\n\n_(active for this daemon process; resets on restart)_") - return b.String() - } - if details.ContextWindow > 0 { - fmt.Fprintf(&b, "\nContext: %d tokens", details.ContextWindow) - } - if details.MaxOutputTokens > 0 { - fmt.Fprintf(&b, "\nMax output: %d tokens", details.MaxOutputTokens) - } - var capabilities []string - if details.Reasoning { - capabilities = append(capabilities, "reasoning") - } - if details.Tools { - capabilities = append(capabilities, "tools") - } - for _, modality := range details.InputModalities { - if modality != "text" { - capabilities = append(capabilities, modality) - } - } - if details.Attachment { - capabilities = append(capabilities, "attachments") - } - if details.Structured { - capabilities = append(capabilities, "structured output") - } - if len(capabilities) > 0 { - fmt.Fprintf(&b, "\nCapabilities: %s", strings.Join(capabilities, ", ")) - } - b.WriteString("\n\n_(active for this daemon process; resets on restart)_") - return b.String() -} - -func (g *Gateway) handleModelPageCallback( - ctx context.Context, - b *bot.Bot, - update *models.Update, - client messaging.ChatContract, -) { - query := update.CallbackQuery - if query == nil { - return - } - if !g.isSenderAllowed(query.From.ID) { - g.answerModelCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true) - return - } - snap, err := client.Snapshot(ctx) - if err != nil || len(snap.Models) == 0 { - g.answerModelCallback(ctx, b, query.ID, "Model switching is not configured.", true) - return - } - page, ok := g.modelPageForCallback(query.Data) - if !ok { - g.answerModelCallback(ctx, b, query.ID, "That model page is no longer valid.", true) - return - } - models := snap.ModelsByProvider[page.Provider] - if page.Page < 0 || page.Page*modelPageSize >= len(models) { - g.answerModelCallback(ctx, b, query.ID, "That model page is no longer valid.", true) - return - } - g.answerModelCallback(ctx, b, query.ID, "", false) - g.editModelPicker(ctx, b, query, - modelSelectorTextForProvider(page.Provider, page.Page, len(models)), - g.modelSelectorKeyboardPage(snap.ActiveModel, models, page.Provider, page.Page)) -} - -func (g *Gateway) handleModelBackCallback( - ctx context.Context, - b *bot.Bot, - update *models.Update, - client messaging.ChatContract, -) { - query := update.CallbackQuery - if query == nil { - return - } - if !g.isSenderAllowed(query.From.ID) { - g.answerModelCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true) - return - } - snap, err := client.Snapshot(ctx) - if err != nil || len(snap.Providers) == 0 { - g.answerModelCallback(ctx, b, query.ID, "Model switching is not configured.", true) - return - } - g.answerModelCallback(ctx, b, query.ID, "", false) - g.editModelPicker(ctx, b, query, - providerSelectorText(snap.ActiveModel, snap.ActiveProvider), - g.providerSelectorKeyboard(snap.ActiveProvider, snap.Providers, snap.ModelsByProvider)) -} - -func (g *Gateway) handleModelCancelCallback(ctx context.Context, b *bot.Bot, update *models.Update) { - query := update.CallbackQuery - if query == nil { - return - } - if !g.isSenderAllowed(query.From.ID) { - g.answerModelCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true) - return - } - g.answerModelCallback(ctx, b, query.ID, "", false) - params := &bot.EditMessageTextParams{ - Text: "Model selection cancelled.", - } - switch { - case query.Message.Message != nil: - params.ChatID = query.Message.Message.Chat.ID - params.MessageID = query.Message.Message.ID - case query.InlineMessageID != "": - params.InlineMessageID = query.InlineMessageID - default: - return - } - if _, err := b.EditMessageText(ctx, params); err != nil { - g.log.WarnContext(ctx, "cancel model selector failed", "error", err) - } -} - -func (g *Gateway) handleModelNoopCallback(ctx context.Context, b *bot.Bot, update *models.Update) { - query := update.CallbackQuery - if query == nil { - return - } - g.answerModelCallback(ctx, b, query.ID, "", false) -} - -func (g *Gateway) answerModelCallback(ctx context.Context, b *bot.Bot, queryID, text string, alert bool) { - params := &bot.AnswerCallbackQueryParams{ - CallbackQueryID: queryID, - Text: text, - ShowAlert: alert, - } - if _, err := b.AnswerCallbackQuery(ctx, params); err != nil { - g.log.WarnContext(ctx, "answer model callback query failed", "error", err) - } -} - -func (g *Gateway) editModelPicker( - ctx context.Context, - b *bot.Bot, - query *models.CallbackQuery, - text string, - markup *models.InlineKeyboardMarkup, -) { - params := &bot.EditMessageTextParams{ - Text: text, - } - if markup != nil { - params.ReplyMarkup = markup - } - switch { - case query.Message.Message != nil: - params.ChatID = query.Message.Message.Chat.ID - params.MessageID = query.Message.Message.ID - case query.InlineMessageID != "": - params.InlineMessageID = query.InlineMessageID - default: - return - } - if _, err := b.EditMessageText(ctx, params); err != nil { - g.log.WarnContext(ctx, "edit model picker failed", "error", err) - } -} diff --git a/internal/channels/telegram/polling_readiness.go b/internal/channels/telegram/polling_readiness.go deleted file mode 100644 index 6366e0717..000000000 --- a/internal/channels/telegram/polling_readiness.go +++ /dev/null @@ -1,68 +0,0 @@ -package telegram - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "net/http" - "strings" - "sync/atomic" - "time" - - "github.com/go-telegram/bot" - "github.com/go-telegram/bot/models" -) - -const telegramPollTimeout = time.Minute - -// pollReadinessClient observes the same successful getUpdates response the -// Telegram library is about to decode. The library keeps polling errors inside -// its worker goroutine, so the HTTP boundary is the only place Start can prove -// that long polling is actually usable instead of merely spawned. -type pollReadinessClient struct { - client bot.HttpClient - onRunning func() - reported atomic.Bool -} - -func (c *pollReadinessClient) Do(req *http.Request) (*http.Response, error) { - resp, err := c.client.Do(req) - if err != nil || c.reported.Load() || !strings.HasSuffix(req.URL.Path, "/getUpdates") { - return resp, err - } - - body, err := io.ReadAll(resp.Body) - closeErr := resp.Body.Close() - if err != nil { - return nil, fmt.Errorf("read Telegram polling response: %w", err) - } - resp.Body = &replayBody{Reader: bytes.NewReader(body), closeErr: closeErr} - if successfulPollResponse(body) && c.reported.CompareAndSwap(false, true) && c.onRunning != nil { - c.onRunning() - } - return resp, nil -} - -func successfulPollResponse(body []byte) bool { - var response struct { - OK bool `json:"ok"` - Result json.RawMessage `json:"result"` - } - if err := json.Unmarshal(body, &response); err != nil || !response.OK { - return false - } - var updates []*models.Update - return json.Unmarshal(response.Result, &updates) == nil -} - -type replayBody struct { - *bytes.Reader - closeErr error -} - -func (b *replayBody) Close() error { - err := b.closeErr - b.closeErr = nil - return err -} diff --git a/internal/channels/telegram/provider.go b/internal/channels/telegram/provider.go deleted file mode 100644 index b173a53f7..000000000 --- a/internal/channels/telegram/provider.go +++ /dev/null @@ -1,165 +0,0 @@ -package telegram - -import ( - "context" - "crypto/sha256" - "fmt" - "strings" - - "github.com/go-telegram/bot" - "github.com/go-telegram/bot/models" - - "github.com/samcharles93/archie-core/internal/domain/messaging" -) - -const providerCallbackPrefix = "provider:" - -func (g *Gateway) sendProviderSelector( - ctx context.Context, - b *bot.Bot, - msg *models.Message, - client messaging.ChatContract, -) { - snap, err := client.Snapshot(ctx) - if err != nil || len(snap.Providers) == 0 { - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Provider switching is not configured.") - return - } - params := &bot.SendMessageParams{ - ChatID: msg.Chat.ID, - Text: providerSelectorText(snap.ActiveModel, snap.ActiveProvider), - ReplyMarkup: g.providerSelectorKeyboard(snap.ActiveProvider, snap.Providers, snap.ModelsByProvider), - } - if msg.MessageThreadID != 0 { - params.MessageThreadID = msg.MessageThreadID - } - if _, err := b.SendMessage(ctx, params); err != nil { - g.log.ErrorContext(ctx, "send provider selector failed", "error", err) - } -} - -func providerSelectorText(activeModel, activeProvider string) string { - return "βš™ Model Configuration\n\nCurrent model: " + - modelDisplayName(activeModel, activeProvider) + - "\nProvider: " + providerDisplayName(activeProvider) + - "\n\nSelect a provider:" -} - -func (g *Gateway) providerSelectorKeyboard(active string, providers []string, modelsByProvider map[string][]string) *models.InlineKeyboardMarkup { - buttons := make([]models.InlineKeyboardButton, 0, len(providers)) - for _, provider := range providers { - count := len(modelsByProvider[provider]) - label := fmt.Sprintf("%s (%d)", providerDisplayName(provider), count) - if provider == active { - label = "βœ“ " + label - } - buttons = append(buttons, models.InlineKeyboardButton{ - Text: label, - CallbackData: g.providerCallbackToken(provider), - }) - } - rows := make([][]models.InlineKeyboardButton, 0, (len(buttons)+1)/2) - for i := 0; i < len(buttons); i += 2 { - end := min(i+2, len(buttons)) - rows = append(rows, buttons[i:end]) - } - rows = append(rows, []models.InlineKeyboardButton{{ - Text: "βœ— Cancel", CallbackData: modelCancelCallback, - }}) - return &models.InlineKeyboardMarkup{InlineKeyboard: rows} -} - -func (g *Gateway) providerCallbackToken(provider string) string { - sum := sha256.Sum256([]byte(provider)) - token := fmt.Sprintf("%s%x", providerCallbackPrefix, sum[:24]) - g.providerMu.Lock() - g.providerCallbacks[token] = provider - g.providerMu.Unlock() - return token -} - -func (g *Gateway) providerForCallback(token string) (string, bool) { - g.providerMu.RLock() - defer g.providerMu.RUnlock() - provider, ok := g.providerCallbacks[token] - return provider, ok -} - -func providerDisplayName(provider string) string { - switch strings.ToLower(provider) { - case "openai": - return "OpenAI" - case "openrouter": - return "OpenRouter" - case "anthropic": - return "Anthropic" - case "deepseek": - return "DeepSeek" - case "google": - return "Google" - case "ollama": - return "Ollama" - default: - return provider - } -} - -func (g *Gateway) handleProviderCallback( - ctx context.Context, - b *bot.Bot, - update *models.Update, - client messaging.ChatContract, -) { - query := update.CallbackQuery - if query == nil { - return - } - if !g.isSenderAllowed(query.From.ID) { - g.log.WarnContext(ctx, "provider callback from unauthorized sender", "user_id", query.From.ID) - g.answerModelCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true) - return - } - snap, err := client.Snapshot(ctx) - if err != nil || len(snap.Providers) == 0 { - g.answerModelCallback(ctx, b, query.ID, "Provider switching is not configured.", true) - return - } - selected, ok := g.providerForCallback(query.Data) - if !ok { - g.answerModelCallback(ctx, b, query.ID, "That provider selection is no longer valid.", true) - return - } - providerModels := snap.ModelsByProvider[selected] - if len(providerModels) == 0 { - g.answerModelCallback(ctx, b, query.ID, "That provider has no selectable models.", true) - return - } - g.answerModelCallback(ctx, b, query.ID, "", false) - g.updateModelSelectorForProvider(ctx, b, query, snap.ActiveModel, providerModels, selected) -} - -func (g *Gateway) updateModelSelectorForProvider( - ctx context.Context, - b *bot.Bot, - query *models.CallbackQuery, - activeModel string, - providerModels []string, - provider string, -) { - params := &bot.EditMessageTextParams{ - Text: modelSelectorTextForProvider(provider, 0, len(providerModels)), - ReplyMarkup: g.modelSelectorKeyboardPage(activeModel, providerModels, provider, 0), - } - switch { - case query.Message.Message != nil: - params.ChatID = query.Message.Message.Chat.ID - params.MessageID = query.Message.Message.ID - case query.InlineMessageID != "": - params.InlineMessageID = query.InlineMessageID - default: - return - } - if _, err := b.EditMessageText(ctx, params); err != nil { - g.log.WarnContext(ctx, "update provider selector failed", "error", err) - } -} diff --git a/internal/channels/telegram/ratelimit.go b/internal/channels/telegram/ratelimit.go deleted file mode 100644 index c24fb6ee3..000000000 --- a/internal/channels/telegram/ratelimit.go +++ /dev/null @@ -1,20 +0,0 @@ -package telegram - -import ( - "context" - "errors" - - "github.com/go-telegram/bot" -) - -// pipelineErrorHandler logs update-loop failures. -func (g *Gateway) pipelineErrorHandler(ctx context.Context) func(error) { - return func(err error) { - if tooMany, ok := errors.AsType[*bot.TooManyRequestsError](err); ok { - g.log.WarnContext(ctx, "telegram rate limited", "retry_after", tooMany.RetryAfter, - "component", "gateway-telegram") - return - } - g.log.ErrorContext(ctx, "telegram pipeline error", "error", err) - } -} diff --git a/internal/channels/telegram/restart.go b/internal/channels/telegram/restart.go deleted file mode 100644 index 151cad27e..000000000 --- a/internal/channels/telegram/restart.go +++ /dev/null @@ -1,48 +0,0 @@ -package telegram - -import ( - "context" - - "github.com/go-telegram/bot" - "github.com/go-telegram/bot/models" -) - -// restartRequest identifies who asked for a restart, so the relaunched -// instance can confirm back to the same chat. -type restartRequest struct { - chatID int64 - threadID int -} - -// restartHandler serves /restart, relaunching the bot to reload config. Only -// allowlisted senders reach it. -func (g *Gateway) restartHandler() bot.HandlerFunc { - return func(ctx context.Context, b *bot.Bot, update *models.Update) { - msg, ok := g.authorizedMessage(ctx, b, update) - if !ok { - return - } - - // Refuse to restart while an update is installing. - g.updateMu.Lock() - updating := g.updateInProgress - g.updateMu.Unlock() - if updating { - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "⚠️ An update is currently installing -- restarting now would kill it mid-install. Wait for it to finish, then try again.") - return - } - - // Acknowledge on the current instance: it is about to be torn - // down, and the relaunched one confirms completion. - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "πŸ”„ Reloading Archie…") - - // Hand off to the supervisor rather than tearing down from inside - // this handler, which runs on the very bot being stopped. Never - // block: a restart already in flight makes this request redundant. - select { - case g.restartCh <- restartRequest{chatID: msg.Chat.ID, threadID: msg.MessageThreadID}: - default: - g.log.WarnContext(ctx, "restart already in progress, ignoring duplicate request") - } - } -} diff --git a/internal/channels/telegram/richblocks.go b/internal/channels/telegram/richblocks.go deleted file mode 100644 index 81e9eb3b4..000000000 --- a/internal/channels/telegram/richblocks.go +++ /dev/null @@ -1,603 +0,0 @@ -package telegram - -import ( - "regexp" - "strings" - "unicode" - "unicode/utf8" - - "github.com/go-telegram/bot/models" -) - -// Markdown is rendered as Telegram rich blocks, with inline formatting -// reduced to plain text. - -var ( - inlineLinkHTML = regexp.MustCompile(`\[([^\]]*)\]\(([^)]+)\)`) - codeBlockMark = regexp.MustCompile("`([^`]*)`") -) - -// emphasisMarkers are the delimiters stripEmphasis pairs, longest first so -// "**" is consumed before the "*" pass can see it as two single markers. -var emphasisMarkers = []string{"~~", "**", "__", "*", "_"} - -// richText builds a plain Text; an empty RichText.Type serializes as a JSON -// string, which is exactly what a plain-text rich block wants. -func richText(text string) models.RichText { - return models.RichText{PlainText: text} -} - -func paragraphBlock(text string) models.InputRichBlock { - return models.InputRichBlock{ - Type: models.RichBlockTypeParagraph, - InputRichBlockParagraph: &models.InputRichBlockParagraph{ - Type: models.RichBlockTypeParagraph, - Text: richText(text), - }, - } -} - -func headingBlock(line string) models.InputRichBlock { - depth := headingDepth(line) - text := stripInlineMarkdown(strings.TrimSpace(line[depth:])) - return models.InputRichBlock{ - Type: models.RichBlockTypeSectionHeading, - InputRichBlockSectionHeading: &models.InputRichBlockSectionHeading{ - Type: models.RichBlockTypeSectionHeading, - Text: richText(text), - Size: depth, - }, - } -} - -func preformattedBlock(text, lang string) models.InputRichBlock { - return models.InputRichBlock{ - Type: models.RichBlockTypePreformatted, - InputRichBlockPreformatted: &models.InputRichBlockPreformatted{ - Type: models.RichBlockTypePreformatted, - Text: richText(text), - Language: lang, - }, - } -} - -func headingDepth(line string) int { - n := 0 - for n < len(line) && n < 6 && line[n] == '#' { - n++ - } - if n == 0 { - return 0 - } - if n < len(line) && line[n] != ' ' { - return 0 - } - return n -} - -var ( - bulletListMarkers = []string{"- ", "* ", "+ "} - orderedListMark = regexp.MustCompile(`^[0-9]+[.)] `) -) - -func isListItem(line string) bool { - for _, marker := range bulletListMarkers { - if strings.HasPrefix(line, marker) { - return true - } - } - return orderedListMark.MatchString(line) -} - -func listItemText(line string) string { - for _, marker := range bulletListMarkers { - if strings.HasPrefix(line, marker) { - return stripInlineMarkdown(strings.TrimSpace(line[len(marker):])) - } - } - if loc := orderedListMark.FindStringIndex(line); loc != nil { - return stripInlineMarkdown(strings.TrimSpace(line[loc[1]:])) - } - return "" -} - -// stripInlineMarkdown reduces inline emphasis, inline code and links to plain -// text, dropping the markers so none of them can leak into the rendered block. -func stripInlineMarkdown(s string) string { - s = inlineLinkHTML.ReplaceAllString(s, "$1 ($2)") - for _, marker := range emphasisMarkers { - s = stripEmphasis(s, marker) - } - return codeBlockMark.ReplaceAllString(s, "$1") -} - -// stripEmphasis removes paired emphasis delimiters, keeping their content, -// using CommonMark's flanking rules. -func stripEmphasis(s, marker string) string { - var b strings.Builder - for i := 0; i < len(s); { - if !strings.HasPrefix(s[i:], marker) { - b.WriteByte(s[i]) - i++ - continue - } - end := i + len(marker) - if canOpen, _ := flanking(s, i, end, marker); canOpen { - if closer := findCloser(s, end, marker); closer >= 0 { - b.WriteString(s[end:closer]) - i = closer + len(marker) - continue - } - } - b.WriteString(marker) - i = end - } - return b.String() -} - -// findCloser returns the offset of the first delimiter at or after from that -// may close emphasis, or -1 when the run is unpaired. -func findCloser(s string, from int, marker string) int { - for i := from; i+len(marker) <= len(s); i++ { - if !strings.HasPrefix(s[i:], marker) { - continue - } - if _, canClose := flanking(s, i, i+len(marker), marker); canClose { - return i - } - } - return -1 -} - -// delimiterFlanks carries CommonMark's flanking facts about one delimiter -// run: whether it is left- and/or right-flanking, and whether the characters -// either side are punctuation, which the underscore rules also need. -type delimiterFlanks struct { - left, right bool - prevPunct, nextPunct bool -} - -// flanksOf computes the flanking facts for the delimiter run s[i:j]. -func flanksOf(s string, i, j int) delimiterFlanks { - prev := ' ' - if i > 0 { - prev, _ = utf8.DecodeLastRuneInString(s[:i]) - } - next := ' ' - if j < len(s) { - next, _ = utf8.DecodeRuneInString(s[j:]) - } - prevSpace, nextSpace := unicode.IsSpace(prev), unicode.IsSpace(next) - f := delimiterFlanks{prevPunct: isPunct(prev), nextPunct: isPunct(next)} - f.left = !nextSpace && (!f.nextPunct || prevSpace || f.prevPunct) - f.right = !prevSpace && (!f.prevPunct || nextSpace || f.nextPunct) - return f -} - -// flanking reports whether the delimiter run s[i:j] may open or close -// emphasis, per CommonMark, except that a single "*" may not open on -// punctuation. -func flanking(s string, i, j int, marker string) (canOpen, canClose bool) { - f := flanksOf(s, i, j) - switch marker { - case "_", "__": - return f.left && (!f.right || f.prevPunct), f.right && (!f.left || f.nextPunct) - case "*": - return f.left && !f.nextPunct, f.right - default: - return f.left, f.right - } -} - -func isPunct(r rune) bool { - return unicode.IsPunct(r) || unicode.IsSymbol(r) -} - -// markdownToBlocks converts a Markdown document into Telegram rich-message -// blocks. It is intentionally conservative: unknown constructs fall back to a -// plain paragraph rather than risking literal markers in the rendered output. -func markdownToBlocks(md string) []models.InputRichBlock { - if strings.TrimSpace(md) == "" { - return nil - } - p := &markdownBlockParser{} - for raw := range strings.SplitSeq(md, "\n") { - p.handleLine(strings.TrimRight(raw, "\r")) - } - p.closeCode() - p.flush() - return p.blocks -} - -// markdownBlockParser holds the mutable state markdownToBlocks threads -// through its line-by-line scan: the accumulated blocks, and whichever -// multi-line construct (paragraph, code fence, list, block quote) is -// currently open. -type markdownBlockParser struct { - blocks []models.InputRichBlock - paragraph strings.Builder - codeLines []string - codeLang string - inCode bool - indented bool - // fenceChar and fenceLen record the opening fence, so only a run of the - // same character that is at least as long closes the block. Without - // them a fence could never wrap content containing a shorter one. - fenceChar byte - fenceLen int - listItems [][]models.InputRichBlock - quoteLines []string - // hardBreak records that the line just consumed ended in CommonMark's - // line-break marker, so the next line starts its own block. - hardBreak bool - // tightNext suppresses the spacer before the next block, keeping the - // lines of one hard-broken stanza visually together. - tightNext bool -} - -// handleLine processes one line of input, dispatching to whichever -// construct is open or starting a new one. -func (p *markdownBlockParser) handleLine(line string) { - trimmed := strings.TrimSpace(line) - - if p.inCode && p.consumeCodeLine(line, trimmed) { - return - } - - switch { - case isFence(trimmed): - char, length, info := parseFence(trimmed) - p.flush() - p.codeLang, p.fenceChar, p.fenceLen = info, char, length - p.inCode = true - p.codeLines = nil - case headingDepth(trimmed) > 0: - p.flush() - p.appendBlock(headingBlock(trimmed)) - case isListItem(trimmed): - p.flushParagraph() - p.flushQuote() - if len(p.listItems) == 0 { - p.flushList() - } - p.listItems = append(p.listItems, []models.InputRichBlock{paragraphBlock(listItemText(trimmed))}) - case p.startsIndentedCode(line): - // CommonMark's other code form. Models emit it constantly, and - // without this it fell to the paragraph case below, which - // space-joins its lines into one run-on line. - p.flush() - p.inCode, p.indented, p.codeLang = true, true, "" - p.codeLines = []string{stripCodeIndent(line)} - case len(trimmed) > 1 && trimmed[0] == '>': - p.flushParagraph() - p.flushList() - p.quoteLines = append(p.quoteLines, line) - case trimmed == "": - p.flush() - default: - // A normal line ends a list or quote and continues the paragraph with a - // space. A line ending in a hard break closes its own block. - p.flushList() - p.flushQuote() - switch { - case p.hardBreak: - p.flushParagraph() - p.tightNext = true - case p.paragraph.Len() > 0: - p.paragraph.WriteString(" ") - } - p.hardBreak = endsWithHardBreak(line) - p.paragraph.WriteString(trimHardBreak(trimmed)) - } -} - -// endsWithHardBreak reports whether line carries CommonMark's line-break -// marker: two or more trailing spaces, or a trailing backslash. -func endsWithHardBreak(line string) bool { - if strings.TrimSpace(line) == "" { - return false - } - if strings.HasSuffix(strings.TrimRight(line, " \t"), "\\") { - return true - } - return strings.HasSuffix(line, " ") -} - -// trimHardBreak removes a trailing backslash marker, which unlike trailing -// spaces would otherwise survive into the rendered text. -func trimHardBreak(trimmed string) string { - return strings.TrimRight(strings.TrimSuffix(trimmed, "\\"), " ") -} - -// fenceRun measures the leading run of CommonMark's two fence characters, -// returning the character, its run length and the rest of the line. A run -// shorter than three is not a fence, and is reported as length zero. -func fenceRun(trimmed string) (byte, int, string) { - if trimmed == "" || (trimmed[0] != '`' && trimmed[0] != '~') { - return 0, 0, "" - } - char := trimmed[0] - n := 0 - for n < len(trimmed) && trimmed[n] == char { - n++ - } - if n < 3 { - return 0, 0, "" - } - return char, n, strings.TrimSpace(trimmed[n:]) -} - -// isFence reports whether trimmed opens or closes a fenced code block. -func isFence(trimmed string) bool { - _, n, _ := fenceRun(trimmed) - return n > 0 -} - -// parseFence splits an opening fence into its character, run length and info -// string. A backtick fence may not carry a backtick in its info string, which -// is what keeps an inline code span from being read as a fence. -func parseFence(trimmed string) (byte, int, string) { - char, n, info := fenceRun(trimmed) - if char == '`' && strings.Contains(info, "`") { - return char, n, "" - } - return char, n, info -} - -// closesFence reports whether trimmed ends the open fenced block: the same -// character, a run at least as long as the opening one, and nothing after it. -// A shorter run, the other character, or a trailing info string is ordinary -// content and stays in the block. -func (p *markdownBlockParser) closesFence(trimmed string) bool { - char, n, info := fenceRun(trimmed) - return n > 0 && char == p.fenceChar && n >= p.fenceLen && info == "" -} - -// consumeCodeLine handles one line while a code block is open, reporting -// whether that block claimed it. A fenced block ends at its closing fence; an -// indented block ends at the first non-indented, non-blank line, which is not -// a terminator and must still be parsed normally. -func (p *markdownBlockParser) consumeCodeLine(line, trimmed string) bool { - if !p.indented { - if p.closesFence(trimmed) { - p.closeCode() - } else { - p.codeLines = append(p.codeLines, line) - } - return true - } - if trimmed == "" || indentedCodeLine(line) { - p.codeLines = append(p.codeLines, stripCodeIndent(line)) - return true - } - p.closeCode() - return false -} - -// startsIndentedCode reports whether line opens an indented code block. It may -// not interrupt an open paragraph, list or quote, so a wrapped prose line that -// happens to be indented stays prose. -func (p *markdownBlockParser) startsIndentedCode(line string) bool { - return indentedCodeLine(line) && p.paragraph.Len() == 0 && - len(p.listItems) == 0 && len(p.quoteLines) == 0 -} - -// flush closes every open construct, in the order that keeps blocks in -// source order. -func (p *markdownBlockParser) flush() { - p.flushList() - p.flushQuote() - p.flushParagraph() -} - -// appendBlock adds block, preceded by an empty paragraph as a spacer unless -// it follows a heading. -func (p *markdownBlockParser) appendBlock(block models.InputRichBlock) { - tight := p.tightNext - p.tightNext = false - if !tight && len(p.blocks) > 0 && p.blocks[len(p.blocks)-1].Type != models.RichBlockTypeSectionHeading { - p.blocks = append(p.blocks, paragraphBlock("")) - } - p.blocks = append(p.blocks, block) -} - -func (p *markdownBlockParser) flushParagraph() { - // A pending hard break belongs to the paragraph being closed. Left set, it - // would make the next block hug whatever came before a blank line. - p.hardBreak = false - if p.paragraph.Len() == 0 { - return - } - if text := strings.TrimSpace(p.paragraph.String()); text != "" { - p.appendBlock(paragraphBlock(stripInlineMarkdown(text))) - } - p.paragraph.Reset() -} - -func (p *markdownBlockParser) flushList() { - if len(p.listItems) == 0 { - return - } - items := make([]models.InputRichBlockListItem, 0, len(p.listItems)) - for _, item := range p.listItems { - items = append(items, models.InputRichBlockListItem{Blocks: item}) - } - p.appendBlock(models.InputRichBlock{ - Type: models.RichBlockTypeList, - InputRichBlockList: &models.InputRichBlockList{ - Type: models.RichBlockTypeList, - Items: items, - }, - }) - p.listItems = nil -} - -func (p *markdownBlockParser) flushQuote() { - if len(p.quoteLines) == 0 { - return - } - var inner []models.InputRichBlock - for _, line := range p.quoteLines { - body := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), ">")) - if body == "" { - continue - } - inner = append(inner, paragraphBlock(stripInlineMarkdown(body))) - } - if len(inner) > 0 { - p.appendBlock(models.InputRichBlock{ - Type: models.RichBlockTypeBlockQuotation, - InputRichBlockBlockQuotation: &models.InputRichBlockBlockQuotation{ - Type: models.RichBlockTypeBlockQuotation, - Blocks: inner, - }, - }) - } - p.quoteLines = nil -} - -// closeCode emits the open code block. The text is passed through verbatim: -// code is not prose, and running the emphasis stripper over it turned -// *sql.Tx into sql.Tx and ate same-line snake_case pairs. -func (p *markdownBlockParser) closeCode() { - lines := p.codeLines - if p.indented { - for len(lines) > 0 && strings.TrimSpace(lines[len(lines)-1]) == "" { - lines = lines[:len(lines)-1] - } - } - if len(lines) > 0 || p.codeLang != "" { - p.appendBlock(preformattedBlock(strings.Join(lines, "\n"), p.codeLang)) - } - p.codeLines, p.codeLang, p.inCode, p.indented = nil, "", false, false - p.fenceChar, p.fenceLen = 0, 0 -} - -// indentedCodeLine reports whether line opens or continues an indented code -// block: four spaces or a tab, and something other than whitespace after. -func indentedCodeLine(line string) bool { - if strings.TrimSpace(line) == "" { - return false - } - return strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") -} - -// stripCodeIndent removes the one level of indentation that marks the block, -// so the code reads at its own natural margin. -func stripCodeIndent(line string) string { - if strings.HasPrefix(line, "\t") { - return line[1:] - } - return strings.TrimPrefix(line, " ") -} - -// blocksToPlainText flattens blocks into readable plain text for the fallback -// send, joining each block's text with a blank line. Because it derives from -// the structured blocks there are no Markdown markers left to strip. -func blocksToPlainText(blocks []models.InputRichBlock) []string { - var out []string - for _, block := range blocks { - switch block.Type { - case models.RichBlockTypeParagraph, models.RichBlockTypeSectionHeading, models.RichBlockTypePreformatted, - models.RichBlockTypeFooter, models.RichBlockTypePullQuotation: - if text := blockPlainText(block); text != "" { - out = append(out, text) - } - case models.RichBlockTypeList: - if text := listBlockPlainText(block); text != "" { - out = append(out, text) - } - case models.RichBlockTypeBlockQuotation: - if text := quoteBlockPlainText(block); text != "" { - out = append(out, text) - } - case models.RichBlockTypeDivider: - out = append(out, "β€”β€”β€”") - } - } - return out -} - -// listBlockPlainText renders a list block's items as newline-joined plain -// text, or "" if it has none. -func listBlockPlainText(block models.InputRichBlock) string { - if block.InputRichBlockList == nil { - return "" - } - var items []string - for _, item := range block.InputRichBlockList.Items { - for _, inner := range item.Blocks { - if text := blockPlainText(inner); text != "" { - items = append(items, text) - } - } - } - return strings.Join(items, "\n") -} - -// quoteBlockPlainText renders a block quotation's inner blocks as -// newline-joined plain text, or "" if it has none. -func quoteBlockPlainText(block models.InputRichBlock) string { - if block.InputRichBlockBlockQuotation == nil { - return "" - } - var inner []string - for _, b := range block.InputRichBlockBlockQuotation.Blocks { - if text := blockPlainText(b); text != "" { - inner = append(inner, text) - } - } - return strings.Join(inner, "\n") -} - -func blockPlainText(block models.InputRichBlock) string { - switch block.Type { - case models.RichBlockTypeParagraph: - if block.InputRichBlockParagraph != nil { - return block.InputRichBlockParagraph.Text.PlainText - } - case models.RichBlockTypeSectionHeading: - if block.InputRichBlockSectionHeading != nil { - return block.InputRichBlockSectionHeading.Text.PlainText - } - case models.RichBlockTypePreformatted: - if block.InputRichBlockPreformatted != nil { - return block.InputRichBlockPreformatted.Text.PlainText - } - case models.RichBlockTypeFooter: - if block.InputRichBlockFooter != nil { - return block.InputRichBlockFooter.Text.PlainText - } - case models.RichBlockTypePullQuotation: - if block.InputRichBlockPullQuotation != nil { - return block.InputRichBlockPullQuotation.Text.PlainText - } - } - return "" -} - -// splitBlocks divides blocks into chunks that each fit within maxLen runes, -// ending a chunk only at a block boundary so a code block or heading is never -// cut in half. Every block is retained; ordering is preserved. A single block -// larger than maxLen is returned on its own so it is not silently dropped. -func splitBlocks(blocks []models.InputRichBlock, maxLen int) [][]models.InputRichBlock { - if len(blocks) == 0 || maxLen <= 0 { - return [][]models.InputRichBlock{blocks} - } - var chunks [][]models.InputRichBlock - var current []models.InputRichBlock - var currentLen int - for _, block := range blocks { - blockLen := len([]rune(strings.Join(blocksToPlainText([]models.InputRichBlock{block}), "\n"))) - if len(current) > 0 && currentLen+blockLen > maxLen { - chunks = append(chunks, current) - current, currentLen = nil, 0 - } - current = append(current, block) - currentLen += blockLen - } - if len(current) > 0 { - chunks = append(chunks, current) - } - return chunks -} diff --git a/internal/channels/telegram/stop.go b/internal/channels/telegram/stop.go deleted file mode 100644 index 24266f15d..000000000 --- a/internal/channels/telegram/stop.go +++ /dev/null @@ -1,116 +0,0 @@ -package telegram - -import ( - "context" - "fmt" - "strconv" - "strings" - - "github.com/go-telegram/bot" - "github.com/go-telegram/bot/models" - - "github.com/samcharles93/archie-core/internal/domain/messaging" -) - -// stopHandler serves /stop. Bare /stop cancels the chat agent's running -// reply; when nothing is replying it stops the tasks this conversation's -// agent created. /stop <id> stops that one task. -func (g *Gateway) stopHandler(client messaging.ChatContract) bot.HandlerFunc { - return func(ctx context.Context, b *bot.Bot, update *models.Update) { - msg, ok := g.authorizedMessage(ctx, b, update) - if !ok { - return - } - rest := strings.TrimSpace(restAfterTelegram(msg.Text, "/stop", "")) - if rest == "" { - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, g.stopConversation(ctx, msg, client)) - return - } - id, err := strconv.ParseInt(strings.TrimPrefix(rest, "#"), 10, 64) - if err != nil || id <= 0 { - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Usage: /stop, or /stop <task-id>") - return - } - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, stopTasks(ctx, client, "", id)) - } -} - -// stopConversation cancels the running reply and queued messages; with none -// running it stops the conversation's tasks instead. -func (g *Gateway) stopConversation(ctx context.Context, msg *models.Message, client messaging.ChatContract) string { - var cancelled bool - var dropped int - session := conversationID(msg).String() - if g.turns != nil { - cancelled, dropped = g.turns.Stop(session) - g.log.InfoContext(ctx, "stop requested", "session", session, "cancelled", cancelled, "dropped", dropped) - } - if client == nil { - return stopReport(cancelled, dropped, nil) - } - if res, err := client.Cancel(ctx, session); err == nil { - cancelled = cancelled || res.Cancelled - dropped += res.Dropped - } - if cancelled || dropped > 0 { - return stopReport(cancelled, dropped, nil) - } - return stopTasks(ctx, client, messaging.Origin("telegram", conversationID(msg)), 0) -} - -func stopTasks(ctx context.Context, client messaging.ChatContract, origin string, id int64) string { - if client == nil { - return "Task control is not configured." - } - stopped, err := client.StopTasks(ctx, origin, id) - report := stopReport(false, 0, stopped) - if err != nil { - return report + "\n\nCould not stop: " + err.Error() - } - return report -} - -// stopReport describes what a /stop stopped. -func stopReport(cancelled bool, dropped int, tasks []int64) string { - var parts []string - if cancelled { - parts = append(parts, "the running reply") - } - if dropped > 0 { - parts = append(parts, fmt.Sprintf("%d queued message(s)", dropped)) - } - if len(tasks) > 0 { - ids := make([]string, len(tasks)) - for i, id := range tasks { - ids[i] = fmt.Sprintf("#%d", id) - } - parts = append(parts, "task(s) "+strings.Join(ids, ", ")) - } - if len(parts) == 0 { - return "Nothing is running." - } - return "πŸ›‘ Stopped " + joinWithAnd(parts) + "." -} - -// joinWithAnd renders a list the way it would be read aloud. -func joinWithAnd(parts []string) string { - switch len(parts) { - case 1: - return parts[0] - case 2: - return parts[0] + " and " + parts[1] - default: - return strings.Join(parts[:len(parts)-1], ", ") + " and " + parts[len(parts)-1] - } -} - -// restAfterTelegram strips a slash-command token from a Telegram message -// text, including an optional @bot suffix. -func restAfterTelegram(text, cmd, gatewayName string) string { - s := text - if gatewayName != "" { - s = strings.TrimPrefix(s, cmd+"@"+gatewayName) - } - s = strings.TrimPrefix(s, cmd) - return s -} diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go deleted file mode 100644 index ed8484421..000000000 --- a/internal/channels/telegram/telegram.go +++ /dev/null @@ -1,988 +0,0 @@ -// 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" - "encoding/json" - "errors" - "fmt" - "log/slog" - "net/http" - "runtime/debug" - "slices" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" - - "github.com/go-telegram/bot" - "github.com/go-telegram/bot/models" - - "github.com/samcharles93/archie-core/internal/channels" - "github.com/samcharles93/archie-core/internal/domain/messaging" - "github.com/samcharles93/archie-core/internal/releaseupdate" -) - -// Gateway is a Telegram gateway.Gateway backed by go-telegram/bot. -type Gateway struct { - Token string - // AllowedUserIDs lists the sender IDs allowed to use the bot. Empty denies - // everyone. - AllowedUserIDs []int64 - // Reload re-reads configuration during /restart and applies it to g. - // Supplied by the composition root, which owns config paths. Nil - // restarts with the settings already in memory. - Reload func(*Gateway) error - // ReleaseAnnouncements sends one-time upgrade notes to authorized users. - // It is supplied by the composition root because version, changelog, and - // persistence paths are deployment concerns. - ReleaseAnnouncements ReleaseAnnouncer - // Version reports installed component versions. The composition root owns - // build metadata; Telegram only renders it for authorized users. - Version func() string - // Updates is injected by the composition root. It owns release discovery, - // deferral persistence, and installation; Telegram only presents it. - Updates UpdateService - // Settings executes control-plane commands in this authenticated adapter. - Settings *messaging.SettingsCommand - // ResolveActor maps a channel-native sender to an authenticated Archie - // identity. Nil deliberately permits reads but makes writes fail closed. - ResolveActor func(int64) (string, bool) - - // UpdateReportPath is where the update watchdog leaves an update's outcome, - // relayed on each launch. Empty disables it. - UpdateReportPath string - - // RunningVersions reports the version each component reports for itself, to - // verify update reports. Nil leaves claims unverified. - RunningVersions func() map[string]string - - // showToolCalls controls whether new live replies render completed tool - // calls. Each reply snapshots it so reloads affect only later turns. - showToolCalls atomic.Bool - - // restartCh carries /restart requests from a bot handler to the - // supervisor loop in Start. Buffered so a handler never blocks. - restartCh chan restartRequest - pendingRestart *restartRequest - modelMu sync.RWMutex - modelCallbacks map[string]string - modelPages map[string]modelPage - providerMu sync.RWMutex - providerCallbacks map[string]string - updateMu sync.Mutex - updateInProgress bool - updateActions map[string]updateAction - updateReportMu sync.Mutex - - // tool approval state (gateway.ApprovalRequester): tool approvals - // deliver the operator's decision on a channel to the blocked - // RequestApproval call. - approvalMu sync.Mutex - pendingApprovals map[string]*pendingApproval - // permanentMu guards the 24-hour approvals an operator granted per tool. - permanentMu sync.Mutex - permanentApprovals []permanentApproval - - // interactive state (gateway clarify/picker). A blocked clarify or - // picker waits on one entry here, keyed by the chat it was posed to, so - // the next text from that user is consumed as the answer rather than - // dispatched as a new turn. - interactiveMu sync.Mutex - pendingReplies map[pendingReplyKey]*pendingReply - - // turns serialises chat turns per session off the update worker and - // makes the running one cancellable by /stop. Rebuilt on every launch - // so a restart abandons in-flight turns with the old bot instance. - turns *messaging.Turns - - // liveMu guards liveReplies and liveStopped. - liveMu sync.Mutex - // liveReplies tracks in-flight live replies so Stop can abandon them. - liveReplies map[*liveReply]struct{} - // liveDrainTimeout bounds abandonAllLive's wait for in-flight replies to - // be marked. Zero uses abandonAllLiveTimeout; tests shrink it so a - // deliberately-hung reply doesn't make the suite slow. - liveDrainTimeout time.Duration - // liveStopped is set when abandonAllLive claims the registry, and reset at - // the next launch. - liveStopped bool - - log *slog.Logger - bot *bot.Bot - running bool - // outbound is the running bot as Send sees it: Send is called from the - // Messaging Service's RPC goroutines, not the update loop that owns bot. - outbound atomic.Pointer[bot.Bot] - - // serverURL redirects the Bot API at a test server. Empty in production, - // where the library's default endpoint is used. It exists so launch's - // wiring can be tested without reaching api.telegram.org. - serverURL string - - // newEphemeralSender builds the retracting sender sendEphemeral uses. - // Defaults to channels.NewEphemeralSender; tests override it to inject a - // clock so a status notice's retraction fires without waiting out its - // TTL, matching liveReply's newMediaSender seam. - newEphemeralSender func() *channels.EphemeralSender -} - -type UpdateService interface { - Check(context.Context, int64) (releaseupdate.Snapshot, error) - Defer(context.Context, int64, releaseupdate.Snapshot) error - Install(context.Context, releaseupdate.Snapshot, releaseupdate.InstallMeta, func(string)) (releaseupdate.Result, error) - CanInstall() bool -} - -type ReleaseAnnouncer interface { - Announce( - ctx context.Context, - recipients []int64, - send func(context.Context, int64, string) error, - ) error -} - -// New returns an unstarted Gateway. Call Start to begin long-polling. -func New(token string, allowedUserIDs []int64, log *slog.Logger) *Gateway { - g := &Gateway{ - Token: token, - AllowedUserIDs: allowedUserIDs, - restartCh: make(chan restartRequest, 1), - modelCallbacks: make(map[string]string), - modelPages: make(map[string]modelPage), - providerCallbacks: make(map[string]string), - updateActions: make(map[string]updateAction), - pendingApprovals: make(map[string]*pendingApproval), - pendingReplies: make(map[pendingReplyKey]*pendingReply), - log: log.With("component", "gateway-telegram"), - } - g.newEphemeralSender = func() *channels.EphemeralSender { - return channels.NewEphemeralSender(g.log, nil) - } - return g -} - -func (g *Gateway) Name() string { return "telegram" } - -// SetShowToolCalls controls tool visibility for replies created after the call. -func (g *Gateway) SetShowToolCalls(show bool) { - g.showToolCalls.Store(show) -} - -// ShowToolCalls reports the visibility setting that a new reply must snapshot. -func (g *Gateway) ShowToolCalls() bool { - return g.showToolCalls.Load() -} - -// RequestRestart asks the gateway supervisor to reload this adapter. It is -// safe for callers outside Telegram (such as the local Web UI) and never -// blocks when a restart is already queued. -func (g *Gateway) RequestRestart() error { - select { - case g.restartCh <- restartRequest{}: - return nil - default: - return errors.New("telegram gateway restart already in progress") - } -} - -// Start runs the bot and relaunches it on restart requests until ctx ends. -func (g *Gateway) Start(ctx context.Context, client messaging.ChatContract, lifecycle channels.Lifecycle) error { - if g.Token == "" { - return fmt.Errorf("telegram bot token is required") - } - g.log.InfoContext(ctx, "starting telegram gateway") - - for { - lifecycle.ReportStarting() - runCtx, cancel := context.WithCancel(ctx) - b, err := g.launch(runCtx, client, lifecycle) - if err != nil { - cancel() - return err - } - // Confirm the restart with a self-deleting notice. - if req := g.pendingRestart; req != nil && req.chatID != 0 { - g.sendEphemeral(runCtx, b, req.chatID, req.threadID, "βœ… Archie reloaded.") - } - if g.pendingRestart != nil { - g.pendingRestart = nil - } - - select { - case <-ctx.Done(): - cancel() - return g.Stop(context.WithoutCancel(ctx)) - case req := <-g.restartCh: - g.log.InfoContext(ctx, "restarting telegram gateway", "requested_by", req.chatID) - cancel() - if err := g.Stop(context.WithoutCancel(ctx)); err != nil { - g.log.WarnContext(ctx, "stop during restart failed", "error", err) - } - if g.Reload != nil { - if err := g.Reload(g); err != nil { - // Keep the previous settings rather than dying: a bad - // config edit must not take the gateway down for good. - g.log.ErrorContext(ctx, "config reload failed, restarting with previous settings", "error", err) - } - } - g.pendingRestart = &req - } - } -} - -// telegramTextHandler is one text command the Telegram adapter answers itself, -// before the shared router sees it. -type telegramTextHandler struct { - command string - match bot.MatchType - build func(*Gateway, messaging.ChatContract) bot.HandlerFunc -} - -// telegramTextHandlers is the single source for the commands Telegram answers -// locally. -var telegramTextHandlers = []telegramTextHandler{ - {"/status", bot.MatchTypeExact, func(g *Gateway, c messaging.ChatContract) bot.HandlerFunc { return g.statusHandler(c) }}, - {"/whoami", bot.MatchTypeExact, func(g *Gateway, c messaging.ChatContract) bot.HandlerFunc { return g.whoamiHandler(c) }}, - {"/profile", bot.MatchTypeExact, func(g *Gateway, c messaging.ChatContract) bot.HandlerFunc { return g.profileHandler(c) }}, - {"/sessions", bot.MatchTypeExact, func(g *Gateway, c messaging.ChatContract) bot.HandlerFunc { return g.sessionsHandler(c) }}, - {"/resume", bot.MatchTypeExact, func(g *Gateway, c messaging.ChatContract) bot.HandlerFunc { return g.resumeHandler(c) }}, - {"/agents", bot.MatchTypeExact, func(g *Gateway, c messaging.ChatContract) bot.HandlerFunc { return g.agentsHandler(c) }}, - {"/version", bot.MatchTypeExact, func(g *Gateway, _ messaging.ChatContract) bot.HandlerFunc { return g.versionHandler() }}, - {"/update", bot.MatchTypeExact, func(g *Gateway, _ messaging.ChatContract) bot.HandlerFunc { return g.updateHandler() }}, - {"/settings", bot.MatchTypePrefix, func(g *Gateway, _ messaging.ChatContract) bot.HandlerFunc { return g.settingsHandler() }}, - {"/start", bot.MatchTypeExact, func(g *Gateway, _ messaging.ChatContract) bot.HandlerFunc { return g.startHandler() }}, - {"/help", bot.MatchTypeExact, func(g *Gateway, _ messaging.ChatContract) bot.HandlerFunc { return g.helpHandler() }}, - {"/restart", bot.MatchTypeExact, func(g *Gateway, _ messaging.ChatContract) bot.HandlerFunc { return g.restartHandler() }}, - {"/stop", bot.MatchTypePrefix, func(g *Gateway, c messaging.ChatContract) bot.HandlerFunc { return g.stopHandler(c) }}, -} - -func (g *Gateway) registerCommandHandlers(b *bot.Bot, client messaging.ChatContract) { - for _, handler := range telegramTextHandlers { - b.RegisterHandler(bot.HandlerTypeMessageText, handler.command, handler.match, handler.build(g, client)) - } -} - -func (g *Gateway) startListening(ctx context.Context, b *bot.Bot, _ channels.Lifecycle) error { - g.dropPendingUpdates(ctx, b) - g.running = true - go b.Start(ctx) - return nil -} - -// launch builds one bot instance, registers handlers and starts its -// long-poll delivery worker. Readiness is reported by pollReadinessClient -// after the first successful getUpdates response. -func (g *Gateway) launch(ctx context.Context, client messaging.ChatContract, lifecycle channels.Lifecycle) (*bot.Bot, error) { - // Turns are per-launch. Each queued turn carries the update handler's - // context, which is this launch's, so a /restart cancels everything - // still running under the outgoing bot instance. - g.turns = messaging.NewTurns(g.log) - g.resetLiveRegistry() - - opts := []bot.Option{ - bot.WithErrorsHandler(g.pipelineErrorHandler(ctx)), - bot.WithDebugHandler(func(format string, args ...any) { - g.log.DebugContext(ctx, "telegram debug", "message", fmt.Sprintf(format, args...)) - }), - bot.WithDefaultHandler(g.defaultHandler(client)), - bot.WithMiddlewares(g.panicRecoveryMiddleware(), g.updateLoggingMiddleware()), - bot.WithHTTPClient(telegramPollTimeout, &pollReadinessClient{ - client: &http.Client{Timeout: telegramPollTimeout}, - onRunning: lifecycle.ReportRunning, - }), - } - if g.serverURL != "" { - opts = append(opts, bot.WithServerURL(g.serverURL), bot.WithSkipGetMe()) - } - - b, err := bot.New(g.Token, opts...) - if err != nil { - return nil, fmt.Errorf("create bot: %w", err) - } - g.bot = b - g.outbound.Store(b) - - g.registerCommandHandlers(b, client) - - // Publish the command list so Telegram renders a menu. Without this - // the commands are undiscoverable and the LLM, having no idea they - // exist, tells users there are none. - g.registerCommands(ctx, b) - g.notifyLaunch(ctx, b) - - if err := g.startListening(ctx, b, lifecycle); err != nil { - return nil, err - } - - return b, nil -} - -// notifyLaunch sends the one-time notifications that belong to every -// gateway launch, not just a process boot: a newly installed release's -// changelog, and the phase-2 outcome of an update the watchdog finished -// while this gateway was down. -func (g *Gateway) notifyLaunch(ctx context.Context, b *bot.Bot) { - g.announceRelease(ctx, b) - g.reportPendingUpdate(ctx, b) - go g.watchPendingUpdate(ctx, b) -} - -// watchPendingUpdate closes the watchdog/startup race: the watchdog writes -// the health result only after this process answers its health probe, so the -// launch-time read can miss the report for the boot it describes. -func (g *Gateway) watchPendingUpdate(ctx context.Context, b *bot.Bot) { - ticker := time.NewTicker(2 * time.Second) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - g.reportPendingUpdate(ctx, b) - } - } -} - -func (g *Gateway) announceRelease(ctx context.Context, b *bot.Bot) { - if g.ReleaseAnnouncements == nil { - return - } - err := g.ReleaseAnnouncements.Announce( - ctx, - slices.Clone(g.AllowedUserIDs), - func(ctx context.Context, recipient int64, message string) error { - _, err := b.SendMessage(ctx, &bot.SendMessageParams{ - ChatID: recipient, - Text: message, - }) - return err - }, - ) - if err != nil { - // Notifications are ancillary to chat availability. Keep the gateway - // running and let the announcer retry unrecorded recipients next time. - g.log.WarnContext(ctx, "release announcement failed", "error", err) - } -} - -// Stop gracefully shuts down the bot. -func (g *Gateway) Stop(ctx context.Context) error { - if !g.running { - return nil - } - g.log.InfoContext(ctx, "stopping telegram gateway") - g.running = false - g.outbound.Store(nil) - - g.abandonAllLive(ctx) - - return nil -} - -// ── command handlers (gateway-local -- no LLM) ──────────────── - -func (g *Gateway) statusHandler(client messaging.ChatContract) bot.HandlerFunc { - return g.routeCmdHandler(client, "/status") -} - -func (g *Gateway) whoamiHandler(client messaging.ChatContract) bot.HandlerFunc { - return g.routeCmdHandler(client, "/whoami") -} - -func (g *Gateway) profileHandler(client messaging.ChatContract) bot.HandlerFunc { - return g.routeCmdHandler(client, "/profile") -} - -func (g *Gateway) sessionsHandler(client messaging.ChatContract) bot.HandlerFunc { - return g.routeCmdHandler(client, "/sessions") -} - -func (g *Gateway) agentsHandler(client messaging.ChatContract) bot.HandlerFunc { - return g.routeCmdHandler(client, "/agents") -} - -func (g *Gateway) resumeHandler(client messaging.ChatContract) 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 := client.Route(ctx, messaging.Inbound{Platform: "telegram", Message: messaging.Message{ - ConversationID: conversationID(msg), - Sender: msg.From.Username, - Role: messaging.RoleUser, - Text: msg.Text, - }}) - if err != nil { - g.log.ErrorContext(ctx, "resume handler failed", "error", err) - return - } - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply.Text) - } -} - -// routeCmdHandler builds a handler that routes a fixed command through the -// messaging.ChatContract and sends the reply. -func (g *Gateway) routeCmdHandler(client messaging.ChatContract, cmd string) 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 := client.Route(ctx, messaging.Inbound{Platform: "telegram", Message: messaging.Message{ - ConversationID: conversationID(msg), - Sender: msg.From.Username, - Role: messaging.RoleUser, - Text: cmd, - }}) - if err != nil { - g.log.ErrorContext(ctx, "command handler failed", "command", cmd, "error", err) - return - } - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply.Text) - } -} - -func (g *Gateway) settingsHandler() bot.HandlerFunc { - return func(ctx context.Context, b *bot.Bot, update *models.Update) { - msg, ok := g.authorizedMessage(ctx, b, update) - if !ok { - return - } - actor := "" - if g.ResolveActor != nil { - actor, _ = g.ResolveActor(msg.From.ID) - } - input := strings.TrimSpace(strings.TrimPrefix(msg.Text, "/settings")) - reply := g.Settings.Execute(ctx, actor, input) - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply) - } -} - -func (g *Gateway) versionHandler() bot.HandlerFunc { - return func(ctx context.Context, b *bot.Bot, update *models.Update) { - msg, ok := g.authorizedMessage(ctx, b, update) - if !ok { - return - } - if g.Version == nil { - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Version information is not configured.") - return - } - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, g.Version()) - } -} - -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, msg.MessageThreadID, gatewayHelpText()) - } -} - -func (g *Gateway) startHandler() 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, msg.MessageThreadID, - "Archie is running. Send a message to chat, or type /help for available commands.") - } -} - -// ── default handler (commands and non-command messages β†’ router) ───── - -func (g *Gateway) defaultHandler(client messaging.ChatContract) bot.HandlerFunc { - return func(ctx context.Context, b *bot.Bot, update *models.Update) { - if update.CallbackQuery != nil { - g.handleCallback(ctx, b, update, client) - return - } - - msg, ok := g.authorizedMessage(ctx, b, update) - if !ok { - return - } - // A text reply to a pending clarify/picker prompt is consumed here so - // it answers the blocked interaction instead of starting a new turn. - if g.deliverInteractiveReply(msg) { - return - } - // Media messages arrive before the text gates: a photo has no text, - // so checking it first is what keeps attachments from being dropped. - if _, isMedia := extractInboundMedia(msg); isMedia { - g.submitTurn(ctx, b, msg, client) - return - } - if notice := unsupportedMediaNotice(msg); notice != "" { - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, notice) - return - } - if msg.Text == "" { - return - } - if isModelSelectorRequest(msg.Text) { - g.sendProviderSelector(ctx, b, msg, client) - return - } - if isModelCommand(msg.Text) { - g.handleModelCommand(ctx, b, msg, client) - return - } - g.submitTurn(ctx, b, msg, client) - } -} - -// handleCallback dispatches an inline-button callback query to the handler -// for its prefix. Callback prefixes are mutually exclusive; an unknown -// callback is ignored. -func (g *Gateway) handleCallback(ctx context.Context, b *bot.Bot, update *models.Update, client messaging.ChatContract) { - switch { - case strings.HasPrefix(update.CallbackQuery.Data, approvalCallbackPrefix): - g.handleApprovalCallback(ctx, b, update) - case strings.HasPrefix(update.CallbackQuery.Data, providerCallbackPrefix): - g.handleProviderCallback(ctx, b, update, client) - case strings.HasPrefix(update.CallbackQuery.Data, modelCallbackPrefix): - g.handleModelCallback(ctx, b, update, client) - case strings.HasPrefix(update.CallbackQuery.Data, modelPageCallbackPrefix): - g.handleModelPageCallback(ctx, b, update, client) - case update.CallbackQuery.Data == modelBackCallback: - g.handleModelBackCallback(ctx, b, update, client) - case update.CallbackQuery.Data == modelCancelCallback: - g.handleModelCancelCallback(ctx, b, update) - case update.CallbackQuery.Data == modelNoopCallback: - g.handleModelNoopCallback(ctx, b, update) - case strings.HasPrefix(update.CallbackQuery.Data, updateCallbackPrefix): - g.handleUpdateCallback(ctx, b, update) - } -} - -// turnInbound converts a Telegram message into an inbound turn. ok is false -// for messages with no text or media. -func turnInbound(msg *models.Message, media inboundMedia, hasMedia bool) (messaging.Inbound, bool) { - if !hasMedia && msg.Text == "" { - return messaging.Inbound{}, false - } - gm := messaging.Inbound{ - Platform: "telegram", - Message: messaging.Message{ - // The message ID makes redelivery idempotent. - SourceID: fmt.Sprintf("%d", msg.ID), - ConversationID: conversationID(msg), - Sender: msg.From.Username, - SenderID: fmt.Sprintf("%d", msg.From.ID), - Role: messaging.RoleUser, - Text: turnMessageText(msg, media, hasMedia), - At: time.Unix(int64(msg.Date), 0).UTC(), - }, - } - if hasMedia { - gm.Media = []messaging.MediaAttachment{media.attachment} - } - return gm, true -} - -func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Message, client messaging.ChatContract) { - media, hasMedia := extractInboundMedia(msg) - gm, isTurn := turnInbound(msg, media, hasMedia) - if !isTurn { - return - } - - // The lane key must be the session, so that /stop -- which resolves - // the same key -- reaches the turn the sender is actually watching. - session := conversationID(msg).String() - chatID, threadID := msg.Chat.ID, msg.MessageThreadID - g.turns.Submit(ctx, session, func(turnCtx context.Context) { - if !g.fetchTurnMedia(turnCtx, b, &gm, chatID, threadID) { - return - } - - // If the turn invokes a tool that requires operator approval, - // the dispatch layer blocks on this approver. Nil is fine - // β€” most turns need no gating. - approver := g.NewApprover(b, chatID, threadID, msg.From.ID) - turnCtx = messaging.WithApprovalRequester(turnCtx, approver) - - // A clarify or picker prompt blocks the turn on this adapter; when the - // channel cannot carry one the question tool is simply not offered. - turnCtx = messaging.WithInteractive(turnCtx, g.NewInteractor(b, chatID, threadID, msg.From.ID)) - - // reply appears as it is written; the typing indicator covers the - // gap before the first token and any non-streaming path. - stopTyping := g.startTyping(turnCtx, b, chatID, threadID) - live := g.newLiveReply(turnCtx, b, chatID, threadID, g.ShowToolCalls()) - - events, err := client.Stream(turnCtx, gm) - if err != nil { - stopTyping() - if errors.Is(err, context.Canceled) || errors.Is(turnCtx.Err(), context.Canceled) { - g.log.InfoContext(ctx, "chat turn stopped", "session", session) - live.abandon(turnCtx) - } else { - g.log.ErrorContext(ctx, "stream failed", "error", err) - live.abandonFailed(turnCtx) - } - return - } - - reply, aborted := g.drainTurnEvents(turnCtx, session, live, stopTyping, events) - if aborted { - return - } - live.finalize(turnCtx, reply) - }) -} - -// drainTurnEvents renders a streamed turn's events and returns the final -// reply. A cancelled turn is abandoned cleanly; a failed one is marked -// failed. aborted means the reply must not be finalized. -func (g *Gateway) drainTurnEvents( - turnCtx context.Context, session string, - live *liveReply, stopTyping func(), events <-chan messaging.ChatEvent, -) (string, bool) { - var reply string - var streamErr error - for ev := range events { - switch ev.Kind { - case "delta": - live.Delta(ev.Text) - case "tool": - live.ToolCall(ev.Tool) - case "media": - live.Media(turnCtx, ev.Media) - case "done": - reply = ev.Text - case "error": - streamErr = errors.New(ev.Text) - } - } - stopTyping() - - if streamErr != nil || turnCtx.Err() != nil { - if errors.Is(turnCtx.Err(), context.Canceled) || (streamErr != nil && errors.Is(streamErr, context.Canceled)) { - g.log.InfoContext(turnCtx, "chat turn stopped", "session", session) - live.abandon(turnCtx) - } else { - g.log.ErrorContext(turnCtx, "stream turn failed", "error", streamErr) - live.abandonFailed(turnCtx) - } - return "", true - } - return reply, false -} - -// fetchTurnMedia downloads the turn's attachment. A failed download is -// reported and the turn does not start. -func (g *Gateway) fetchTurnMedia(ctx context.Context, b *bot.Bot, gm *messaging.Inbound, chatID int64, threadID int) bool { - if len(gm.Media) == 0 || gm.Media[0].Data != nil { - return true - } - // Before the download, so a file whose declared type contradicts itself is - // refused rather than fetched and acted on. - if err := messaging.ValidateInbound(gm.Media[0]); err != nil { - g.log.WarnContext(ctx, "inbound media refused", "media_type", gm.Media[0].Type, "error", err) - g.sendMessage(ctx, b, chatID, threadID, - mediaReplyLabel(gm.Media[0])+"but I can't use that file β€” try sending it again.") - return false - } - data, err := g.downloadMedia(ctx, b, gm.Media[0]) - if err != nil { - g.log.WarnContext(ctx, "inbound media download failed", "media_type", gm.Media[0].Type, "error", err) - g.sendMessage(ctx, b, chatID, threadID, - mediaReplyLabel(gm.Media[0])+"but I couldn't download it β€” try sending it again.") - return false - } - gm.Media[0].Data = data - return true -} - -// ── helpers ────────────────────────────────────────────────────── - -// conversationID addresses the chat a Telegram message arrived in: the -// chat ID, and the topic thread within it for supergroups. -func conversationID(msg *models.Message) messaging.ConversationID { - return messaging.ConversationID{ - ChannelID: fmt.Sprintf("%d", msg.Chat.ID), - ThreadID: threadIDString(msg.MessageThreadID), - } -} - -// threadIDString converts a Telegram message_thread_id to a string suitable -// for messaging.ConversationID.ThreadID and SessionSource.ThreadID. A zero -// value (no topic thread, or the General topic) maps to empty string so that -// flat-chat routing continues to work without changes. -func threadIDString(id int) string { - if id == 0 { - return "" - } - return fmt.Sprintf("%d", id) -} - -func (g *Gateway) authorizedMessage(ctx context.Context, b *bot.Bot, update *models.Update) (*models.Message, bool) { - if update.Message == nil || update.Message.From == nil { - return nil, false - } - if g.isSenderAllowed(update.Message.From.ID) { - return update.Message, true - } - g.log.WarnContext(ctx, - "message from unauthorized sender", - "user_id", update.Message.From.ID, - "username", update.Message.From.Username, - "chat_id", update.Message.Chat.ID, - ) - // Reply so an authorised user who is simply missing from the list can - // tell the bot is alive and misconfigured, rather than dead. - g.sendMessage(ctx, b, update.Message.Chat.ID, update.Message.MessageThreadID, - "β›” You are not authorised to use this bot.") - return nil, false -} - -// typingRefresh is how often the typing action is re-sent. Telegram clears -// the indicator after ~5s, so it must be refreshed to stay visible for the -// length of an LLM turn. -const typingRefresh = 4 * time.Second - -// startTyping shows the "typing…" indicator and keeps it alive until the -// returned stop function is called. Errors are logged at debug level only: -// a missing typing indicator must never block or fail the actual reply. -func (g *Gateway) startTyping(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int) (stop func()) { - send := func() { - params := &bot.SendChatActionParams{ - ChatID: chatID, - Action: models.ChatActionTyping, - } - if messageThreadID != 0 { - params.MessageThreadID = messageThreadID - } - if _, err := b.SendChatAction(ctx, params); err != nil { - g.log.DebugContext(ctx, "send chat action failed", "error", err) - } - } - - typingCtx, cancel := context.WithCancel(ctx) - send() - go func() { - ticker := time.NewTicker(typingRefresh) - defer ticker.Stop() - for { - select { - case <-typingCtx.Done(): - return - case <-ticker.C: - send() - } - } - }() - return cancel -} - -// isSenderAllowed reports whether a message's sender may use the bot. -// An empty allowlist denies everyone (see Gateway.AllowedUserIDs). -func (g *Gateway) isSenderAllowed(userID int64) bool { - return slices.Contains(g.AllowedUserIDs, userID) -} - -// messageMaxLen keeps a single message under Telegram's 4096 character -// limit, with room for the continuation marker split adds. -const messageMaxLen = 4000 - -// telegramRenderVersion identifies the renderer applied to outgoing Telegram -// messages. It is included in the per-send log line so an old deployment -// cannot be mistaken for the current code when diagnosing rendering -// differences. -const telegramRenderVersion = "rich-markdown-v2" - -func (g *Gateway) sendMessage(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, text string) { - blocks := markdownToBlocks(text) - if total := blockTextLen(blocks); total <= messageMaxLen { - g.sendBlocks(ctx, b, chatID, messageThreadID, blocks, "send message failed") - return - } - parts := splitBlocks(blocks, messageMaxLen) - for i, part := range parts { - if i < len(parts)-1 { - part = append(part, paragraphBlock("_(continued...)_")) - } - g.sendBlocks(ctx, b, chatID, messageThreadID, part, "send message part failed") - } -} - -// Send delivers text to chatID, split like a reply. It fails if the bot is not -// running or any part is rejected. -func (g *Gateway) Send(ctx context.Context, chatID, text string) error { - b := g.outbound.Load() - if b == nil { - return channels.ErrNotRunning - } - id, err := strconv.ParseInt(chatID, 10, 64) - if err != nil { - return fmt.Errorf("telegram chat id %q: %w", chatID, err) - } - for _, part := range splitBlocks(markdownToBlocks(text), messageMaxLen) { - if g.sendBlocks(ctx, b, id, 0, part, "deliver message failed") == 0 { - return fmt.Errorf("telegram rejected a message to chat %d", id) - } - } - return nil -} - -// sendBlocks sends one rich message and returns its ID, or 0. A rejected rich -// message is resent as plain text. -func (g *Gateway) sendBlocks(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, blocks []models.InputRichBlock, errMsg string) int { - rich := &bot.SendRichMessageParams{ - ChatID: chatID, - RichMessage: models.InputRichMessage{Blocks: blocks}, - } - if messageThreadID != 0 { - rich.MessageThreadID = messageThreadID - } - if msg, err := b.SendRichMessage(ctx, rich); err == nil { - g.log.DebugContext(ctx, "telegram message sent", "renderer", telegramRenderVersion, "mode", "rich") - return msg.ID - } else { - g.log.WarnContext(ctx, "rich send failed, retrying unformatted", "error", err) - } - - plain := &bot.SendMessageParams{ChatID: chatID, Text: strings.Join(blocksToPlainText(blocks), "\n\n")} - if messageThreadID != 0 { - plain.MessageThreadID = messageThreadID - } - if msg, err := b.SendMessage(ctx, plain); err != nil { - g.log.ErrorContext(ctx, errMsg, "error", err) - return 0 - } else { - g.log.WarnContext(ctx, "telegram message sent via plain fallback", "renderer", telegramRenderVersion, "mode", "plain") - return msg.ID - } -} - -// blockTextLen is the rune length of a block slice as rendered plain text. -func blockTextLen(blocks []models.InputRichBlock) int { - return len([]rune(strings.Join(blocksToPlainText(blocks), "\n"))) -} - -// ── 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.ErrorContext(ctx, "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) - } - if threadID := updateThreadID(update); threadID != 0 { - attrs = append(attrs, "thread_id", threadID) - } - g.log.DebugContext(ctx, "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 - } -} - -// updateThreadID extracts the message_thread_id from an update for logging -// and session routing. Returns 0 for flat chats / non-message updates. -func updateThreadID(update *models.Update) int { - if update == nil || update.Message == nil { - return 0 - } - return update.Message.MessageThreadID -} - -// ConfigSchema returns the JSON Schema for the Telegram channel config. -// The bot token is a secret reference object with engine/key. -func (g *Gateway) ConfigSchema() json.RawMessage { - return json.RawMessage(`{ - "type": "object", - "required": ["token"], - "properties": { - "token": { - "type": "object", - "description": "Secret reference for the Telegram bot token from @BotFather, resolved through the configured secret engine.", - "properties": { - "engine": { "type": "string" }, - "key": { "type": "string" } - } - }, - "allowed_user_ids": { - "type": "array", - "items": { "type": "integer" }, - "description": "Restrict bot access to specific Telegram user ids" - } - } -}`) -} - -// ValidateConfig checks the Telegram channel configuration. A token -// secret reference is required. -func (g *Gateway) ValidateConfig(cfg map[string]any) error { - if cfg == nil { - return fmt.Errorf("telegram config is required") - } - if _, ok := cfg["token"]; !ok { - return fmt.Errorf("telegram.token is required") - } - return nil -} - -// Compile-time guard. -var _ channels.Channel = (*Gateway)(nil) - -// dropPendingUpdates discards queued updates before long polling starts, -// via deleteWebhook. Best-effort. -func (g *Gateway) dropPendingUpdates(ctx context.Context, b *bot.Bot) { - ctx, cancel := context.WithTimeout(ctx, 10*time.Second) - defer cancel() - if _, err := b.DeleteWebhook(ctx, &bot.DeleteWebhookParams{DropPendingUpdates: true}); err != nil { - g.log.WarnContext(ctx, "could not drop pending telegram updates, backlog may be replayed", "error", err) - } -} diff --git a/internal/channels/telegram/update.go b/internal/channels/telegram/update.go deleted file mode 100644 index 4ba9f37a4..000000000 --- a/internal/channels/telegram/update.go +++ /dev/null @@ -1,380 +0,0 @@ -package telegram - -import ( - "context" - "crypto/rand" - "encoding/hex" - "fmt" - "maps" - "slices" - "strings" - "time" - - "github.com/go-telegram/bot" - "github.com/go-telegram/bot/models" - - "github.com/samcharles93/archie-core/internal/releaseupdate" -) - -const ( - updateCallbackPrefix = "update:" - updateApproveCallback = updateCallbackPrefix + "approve:" - updateDeferCallback = updateCallbackPrefix + "defer:" -) - -type updateAction struct { - recipient int64 - snapshot releaseupdate.Snapshot - expiresAt time.Time -} - -func (g *Gateway) updateHandler() bot.HandlerFunc { - return func(ctx context.Context, b *bot.Bot, update *models.Update) { - msg, ok := g.authorizedMessage(ctx, b, update) - if !ok { - return - } - if g.Updates == nil { - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Updates are not configured for this installation.") - return - } - snapshot, err := g.Updates.Check(ctx, msg.From.ID) - if err != nil { - g.log.WarnContext(ctx, "check updates failed", "error", err) - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "I couldn't check for updates right now.") - return - } - g.sendUpdateMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, msg.From.ID, snapshot) - } -} - -func (g *Gateway) sendUpdateMessage(ctx context.Context, b *bot.Bot, chatID int64, threadID int, recipient int64, snapshot releaseupdate.Snapshot) { - params := &bot.SendMessageParams{ChatID: chatID, Text: updateText(snapshot)} - if len(snapshot.Available()) > 0 { - if g.Updates.CanInstall() { - params.ReplyMarkup = g.updateKeyboard(recipient, snapshot) - } - } - if threadID != 0 { - params.MessageThreadID = threadID - } - if _, err := b.SendMessage(ctx, params); err != nil { - g.log.ErrorContext(ctx, "send update status failed", "error", err) - } -} - -func updateText(snapshot releaseupdate.Snapshot) string { - return releaseupdate.FormatSnapshot(snapshot) -} - -func (g *Gateway) updateKeyboard(recipient int64, snapshot releaseupdate.Snapshot) *models.InlineKeyboardMarkup { - token := makeUpdateToken() - g.updateMu.Lock() - now := time.Now() - for key, action := range g.updateActions { - if !action.expiresAt.After(now) { - delete(g.updateActions, key) - } - } - g.updateActions[token] = updateAction{recipient: recipient, snapshot: snapshot, expiresAt: now.Add(10 * time.Minute)} - g.updateMu.Unlock() - return &models.InlineKeyboardMarkup{InlineKeyboard: [][]models.InlineKeyboardButton{{ - {Text: "Approve update", CallbackData: updateApproveCallback + token}, - {Text: "Defer", CallbackData: updateDeferCallback + token}, - }}} -} - -func makeUpdateToken() string { - bytes := make([]byte, 16) - if _, err := rand.Read(bytes); err != nil { - panic("crypto/rand: " + err.Error()) - } - return hex.EncodeToString(bytes) -} - -func (g *Gateway) handleUpdateCallback(ctx context.Context, b *bot.Bot, update *models.Update) { - query := update.CallbackQuery - if query == nil { - return - } - if !g.isSenderAllowed(query.From.ID) { - g.log.WarnContext(ctx, "update callback from unauthorized sender", "user_id", query.From.ID) - g.answerModelCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true) - return - } - if g.Updates == nil { - g.answerModelCallback(ctx, b, query.ID, "Updates are not configured for this installation.", true) - return - } - approved := strings.TrimPrefix(query.Data, updateApproveCallback) - deferred := strings.TrimPrefix(query.Data, updateDeferCallback) - token := approved - if token == query.Data { - token = deferred - } - g.updateMu.Lock() - action, found := g.updateActions[token] - if found && action.recipient == query.From.ID { - delete(g.updateActions, token) - } - g.updateMu.Unlock() - if !found || action.recipient != query.From.ID || !action.expiresAt.After(time.Now()) { - g.answerModelCallback(ctx, b, query.ID, "That update action is no longer valid.", true) - return - } - g.dispatchUpdateAction(ctx, b, query, action) -} - -// dispatchUpdateAction routes the callback to defer, approve, or reject. -func (g *Gateway) dispatchUpdateAction(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, action updateAction) { - switch { - case strings.HasPrefix(query.Data, updateDeferCallback): - if err := g.Updates.Defer(ctx, query.From.ID, action.snapshot); err != nil { - g.log.WarnContext(ctx, "defer update failed", "error", err) - g.answerModelCallback(ctx, b, query.ID, "Couldn't defer the update.", true) - return - } - g.answerModelCallback(ctx, b, query.ID, "Update deferred.", false) - g.editUpdateMessage(ctx, b, query, "Update deferred. Archie will ask again when a newer release is available.") - case strings.HasPrefix(query.Data, updateApproveCallback): - fresh, err := g.Updates.Check(ctx, query.From.ID) - if err != nil || !sameUpdateSnapshot(fresh, action.snapshot) { - g.answerModelCallback(ctx, b, query.ID, "The available releases changed. Run /update again.", true) - return - } - if !g.beginUpdate() { - g.answerModelCallback(ctx, b, query.ID, "An update is already in progress.", true) - return - } - g.answerModelCallback(ctx, b, query.ID, "Starting update…", false) - g.editUpdateMessage(ctx, b, query, "Update approved. Starting now…") - // Install outside the callback's short-lived context. - go g.installUpdate(ctx, b, query, fresh) - default: - g.answerModelCallback(ctx, b, query.ID, "That update action is no longer valid.", true) - } -} - -func (g *Gateway) beginUpdate() bool { - g.updateMu.Lock() - defer g.updateMu.Unlock() - if g.updateInProgress { - return false - } - g.updateInProgress = true - return true -} - -// installUpdate runs and reports an update's install phase. The restart -// outcome is reported by the next boot via SendPendingReport. -func (g *Gateway) installUpdate(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, snapshot releaseupdate.Snapshot) { - defer func() { - g.updateMu.Lock() - g.updateInProgress = false - g.updateMu.Unlock() - }() - message := query.Message.Message - if message == nil { - return - } - meta := releaseupdate.InstallMeta{ - Channel: "telegram", ChatID: message.Chat.ID, ThreadID: message.MessageThreadID, - ReportPath: g.UpdateReportPath, - } - - var lines []string - progress := func(text string) { - lines = append(lines, text) - if _, err := b.EditMessageText(ctx, &bot.EditMessageTextParams{ - ChatID: message.Chat.ID, MessageID: message.ID, Text: progressText(lines), - }); err != nil { - g.log.WarnContext(ctx, "update progress message failed", "error", err) - } - } - - installCtx := context.WithoutCancel(ctx) - result, err := g.Updates.Install(installCtx, snapshot, meta, progress) - if err != nil { - g.log.ErrorContext(ctx, "approved update failed", "error", err) - lines = append(lines, formatInstallFailure(err)) - g.editUpdateMessage(ctx, b, query, progressText(lines)) - return - } - lines = append(lines, formatInstallSuccess(result)) - g.editUpdateMessage(ctx, b, query, progressText(lines)) -} - -// progressText joins accumulated status lines into one message, keeping the -// most recent lines when the total would exceed Telegram's message length -// limit -- the newest status matters most once history has to be dropped. -func progressText(lines []string) string { - text := strings.Join(lines, "\n") - runes := []rune(text) - if len(runes) <= messageMaxLen { - return text - } - return "…\n" + string(runes[len(runes)-messageMaxLen:]) -} - -// formatInstallSuccess reports the synchronous phase-1 outcome only: build -// and install succeeded, and a restart has been queued. It must not claim -// the update finished -- see installUpdate's doc comment. -func formatInstallSuccess(result releaseupdate.Result) string { - var text strings.Builder - text.WriteString("Build and install succeeded") - if changes := formatVersionChanges(result); changes != "" { - fmt.Fprintf(&text, ": %s", changes) - } - text.WriteString(".") - if result.RestartRequested { - text.WriteString(" Restart queued β€” I'll confirm once the new version is up and healthy.") - } - return text.String() -} - -func formatInstallFailure(err error) string { - return fmt.Sprintf("Update failed during build/install: %s. Nothing was restarted; archie-core is still running the previous version.", err) -} - -func formatVersionChanges(result releaseupdate.Result) string { - ids := slices.Sorted(maps.Keys(result.Installed)) - parts := make([]string, 0, len(ids)) - for _, id := range ids { - installed := result.Installed[id] - previous := result.Previous[id] - if previous == "" || previous == installed { - continue - } - // A placeholder is not a release: rendering "1.0.0 β†’ unknown" reads - // as a downgrade to a version by that name rather than as the - // missing bookkeeping it actually is. - if !releaseupdate.IsRecordedVersion(installed) { - continue - } - parts = append(parts, fmt.Sprintf("%s %s β†’ %s", id, previous, installed)) - } - return strings.Join(parts, ", ") -} - -// formatPendingReport describes an update's outcome: confirmed, version -// drift, unverified, rolled back, or failed with no backup. -func formatPendingReport(report releaseupdate.Report, running map[string]string) string { - if !report.RolledBack && report.HealthCheck == "passed" { - return formatHealthyReport(report, report.Verify(running)) - } - - ids := slices.Sorted(maps.Keys(report.Previous)) - versions := make([]string, 0, len(ids)) - for _, id := range ids { - versions = append(versions, fmt.Sprintf("%s %s", id, report.Previous[id])) - } - previousVersions := strings.Join(versions, ", ") - - if report.RolledBack { - text := fmt.Sprintf("Update failed health check after restarting and was automatically rolled back to the previous version (%s). archie-core is running normally on the previous release.", previousVersions) - if report.RestoredDatabase { - text += " The update had migrated the database, so the pre-update backup was restored: every write made since the update began is gone." - } - return text - } - return fmt.Sprintf("Update failed health check after restarting and could NOT be rolled back automatically (no backup was found). archie-core may still be running the broken version, or may not be running at all β€” manual intervention is required. Previous version was %s.", previousVersions) -} - -// formatHealthyReport words the report once RolledBack is false and the -// health check passed -- the branch where a passed probe alone is tempting -// to read as "the update worked," which is exactly the false-confidence -// this whole verification path exists to prevent. -func formatHealthyReport(report releaseupdate.Report, verification releaseupdate.Verification) string { - if len(verification.Drift) > 0 { - return formatVersionDrift(verification.Drift) - } - changes := formatVersionChanges(releaseupdate.Result{Previous: report.Previous, Installed: report.Installed}) - if len(verification.Confirmed) == 0 { - // No version could be checked. - text := "Update install finished" - if changes != "" { - text += " (" + changes + ")" - } - return text + ", health check passed, but I still can't confirm which version is actually running β€” please check manually before assuming the update worked." - } - text := "Update complete" - if changes != "" { - text += ": " + changes - } - text += ". Health check passed β€” archie-core is healthy on the new version." - if len(verification.Unverified) > 0 { - // Name the components that were not checked. - text += " Not independently checked: " + strings.Join(verification.Unverified, ", ") + "." - } - return text -} - -// formatVersionDrift lists components running a version other than the one -// installed. -func formatVersionDrift(drift []releaseupdate.VersionDrift) string { - parts := make([]string, 0, len(drift)) - for _, d := range drift { - part := fmt.Sprintf("%s reports %s, not the installed %s", - d.ID, strings.TrimSpace(d.Running), strings.TrimSpace(d.Claimed)) - if d.RunningIsPrevious { - part += " (still the version this update meant to replace)" - } - parts = append(parts, part) - } - return "Update did NOT take effect: " + strings.Join(parts, "; ") + ". " + - "The health check passed because something was there to answer it, not because the new version " + - "is in service, so nothing was rolled back. " + - "Investigate before retrying β€” otherwise /update will report success again." -} - -// reportPendingUpdate relays and clears a pending update report on launch. -// An unreadable report is discarded. -func (g *Gateway) reportPendingUpdate(ctx context.Context, b *bot.Bot) { - g.updateReportMu.Lock() - defer g.updateReportMu.Unlock() - if g.UpdateReportPath == "" { - return - } - report, found, err := releaseupdate.ReadPendingReport(g.UpdateReportPath) - if err != nil { - g.log.WarnContext(ctx, "read pending update report failed; discarding it", "error", err) - if clearErr := releaseupdate.ClearPendingReport(g.UpdateReportPath); clearErr != nil { - g.log.WarnContext(ctx, "clear unreadable update report failed", "error", clearErr) - } - return - } - if !found { - return - } - g.SendPendingReport(ctx, b, report) - if err := releaseupdate.ClearPendingReport(g.UpdateReportPath); err != nil { - g.log.WarnContext(ctx, "clear pending update report failed", "error", err) - } -} - -// SendPendingReport relays an update's outcome to the chat that approved it. -func (g *Gateway) SendPendingReport(ctx context.Context, b *bot.Bot, report releaseupdate.Report) { - g.sendMessage(ctx, b, report.ChatID, report.ThreadID, formatPendingReport(report, g.runningVersions())) -} - -// runningVersions returns self-reported component versions, or nil. -func (g *Gateway) runningVersions() map[string]string { - if g.RunningVersions == nil { - return nil - } - return g.RunningVersions() -} - -func sameUpdateSnapshot(left, right releaseupdate.Snapshot) bool { - return releaseupdate.SameAvailable(left, right) -} - -func (g *Gateway) editUpdateMessage(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, text string) { - if query.Message.Message == nil { - return - } - message := query.Message.Message - if _, err := b.EditMessageText(ctx, &bot.EditMessageTextParams{ChatID: message.Chat.ID, MessageID: message.ID, Text: text}); err != nil { - g.log.WarnContext(ctx, "update update message failed", "error", err) - } -} diff --git a/internal/domain/messaging/tool_parameters.go b/internal/domain/messaging/tool_parameters.go new file mode 100644 index 000000000..203e24f43 --- /dev/null +++ b/internal/domain/messaging/tool_parameters.go @@ -0,0 +1,73 @@ +package messaging + +import ( + "encoding/json" + "strings" + + "github.com/samcharles93/archie-core/internal/webhookguard" +) + +const ( + toolParametersMaxRunes = 120 + redactedParameterValue = "[redacted]" +) + +// SummarizeToolParameters returns a bounded JSON shape of tool input. +func SummarizeToolParameters(input string) string { + if strings.TrimSpace(input) == "" { + return "" + } + decoder := json.NewDecoder(strings.NewReader(input)) + decoder.UseNumber() + var value any + if err := decoder.Decode(&value); err != nil { + return "[unavailable]" + } + value = redactToolParameters(value, false) + encoded, err := json.Marshal(value) + if err != nil { + return "[unavailable]" + } + return truncateRunesWithinLimit(string(encoded), toolParametersMaxRunes) +} + +func redactToolParameters(value any, sensitive bool) any { + if sensitive { + return redactedParameterValue + } + switch typed := value.(type) { + case map[string]any: + for key, child := range typed { + typed[key] = redactToolParameters(child, sensitiveParameterKey(key)) + } + return typed + case []any: + for i, child := range typed { + typed[i] = redactToolParameters(child, sensitive) + } + return typed + default: + return value + } +} + +func sensitiveParameterKey(key string) bool { + normalized := strings.NewReplacer("-", "_", " ", "_").Replace(strings.ToLower(key)) + for _, marker := range webhookguard.SensitiveKeyMarkers { + if strings.Contains(normalized, marker) { + return true + } + } + return false +} + +func truncateRunesWithinLimit(s string, limit int) string { + runes := []rune(s) + if len(runes) <= limit { + return s + } + if limit <= 1 { + return "…" + } + return string(runes[:limit-1]) + "…" +} diff --git a/internal/domain/messaging/tool_render.go b/internal/domain/messaging/tool_render.go deleted file mode 100644 index 023cab4ca..000000000 --- a/internal/domain/messaging/tool_render.go +++ /dev/null @@ -1,311 +0,0 @@ -package messaging - -import ( - "encoding/json" - "fmt" - "strconv" - "strings" - - "github.com/samcharles93/archie-core/internal/webhookguard" -) - -const ( - toolParametersMaxRunes = 120 - redactedParameterValue = "[redacted]" -) - -// RenderToolCall returns the channel-neutral compact representation used by -// chat surfaces. Parameters are intentionally omitted: JSON/schema-shaped -// inputs are noisy, often contain secrets, and are not useful progress text. -func RenderToolCall(e ToolCallEvent) string { - if limit, ok := legacyTurnBudgetLimit(e.Err); ok { - return toolProgressBlock("tools", e.Emoji, "stopped", fmt.Sprintf("tool-output limit reached (%s chars); further results suppressed", limit)) - } - if line := cleanToolError(e.Name, e.Err); line != "" { - return toolProgressBlock(e.Name, e.Emoji, "failed", line) - } - // Success carries no status word. Every line would read "done", so it - // distinguishes nothing; a status is printed only when the outcome is - // not the one the preview already implies. - return toolProgressBlock(e.Name, e.Emoji, "", toolPreview(e.Name, e.Output)) -} - -// FailureKey identifies equivalent tool calls for channel adapters that -// collapse repeated activity. -func FailureKey(e ToolCallEvent) string { - if _, ok := legacyTurnBudgetLimit(e.Err); ok { - return "legacy-turn-output-limit" - } - if line := cleanToolError(e.Name, e.Err); line != "" { - return strings.TrimSpace(e.Name) + "\x00" + line - } - return "success\x00" + strings.TrimSpace(e.Name) + "\x00" + toolPreview(e.Name, e.Output) -} - -// ToolPreviewSeparator joins a tool line's header and its one-line preview. -const ToolPreviewSeparator = " Β· " - -func toolProgressBlock(name, emoji, status, preview string) string { - name = strings.TrimSpace(name) - if name == "" { - name = "tool" - } - preview = strings.TrimSpace(preview) - if preview == "" { - preview = "completed" - } - if status != "" { - name += " β€” " + status - } - if emoji = strings.TrimSpace(emoji); emoji != "" { - name = emoji + " " + name - } - return name + ToolPreviewSeparator + truncateRunes(preview, 180) -} - -func toolPreview(name, output string) string { - content, _ := unwrapToolContent(output) - if strings.TrimSpace(content) == "" { - return "completed" - } - if summary, ok := toolNoticeSummary(content); ok { - return summary - } - if isSearchTool(name) { - if summary, ok := searchResultSummary(content); ok { - return summary - } - } - preview := firstInformativeLine(content) - if preview == "" { - return "completed with no printable preview" - } - return preview -} - -var searchToolNames = map[string]bool{ - "grep": true, - "rg": true, - "search": true, - "toolsearch": true, -} - -func isSearchTool(name string) bool { - return searchToolNames[strings.ToLower(strings.TrimSpace(name))] -} - -func toolNoticeSummary(content string) (string, bool) { - for line := range strings.SplitSeq(content, "\n") { - notice, ok := parseTruncationNotice(strings.TrimSpace(line)) - if !ok { - continue - } - if notice.total <= notice.shown { - continue - } - if notice.truncatedHead { - return fmt.Sprintf("%d lines total; showing last %d", notice.total, notice.shown), true - } - return fmt.Sprintf("%d lines total; showing %d", notice.total, notice.shown), true - } - return "", false -} - -type truncationNotice struct { - shown int - total int - truncatedHead bool -} - -func parseTruncationNotice(line string) (truncationNotice, bool) { - _, rest, found := strings.Cut(line, "[truncated: ") - if !found { - return truncationNotice{}, false - } - _, rest, found = strings.Cut(rest, "showing ") - if !found { - return truncationNotice{}, false - } - truncatedHead := false - if after, ok := strings.CutPrefix(rest, "last "); ok { - rest, truncatedHead = after, true - } - counts, _, found := strings.Cut(rest, " lines") - if !found { - return truncationNotice{}, false - } - left, right, found := strings.Cut(counts, "/") - if !found { - return truncationNotice{}, false - } - shown, errShown := strconv.Atoi(strings.TrimSpace(left)) - total, errTotal := strconv.Atoi(strings.TrimSpace(right)) - if errShown != nil || errTotal != nil { - return truncationNotice{}, false - } - return truncationNotice{shown: shown, total: total, truncatedHead: truncatedHead}, true -} - -func searchResultSummary(content string) (string, bool) { - matches := countSearchMatches(content) - if matches == 0 { - return "", false - } - return fmt.Sprintf("%d %s", matches, pluralize(matches, "match", "matches")), true -} - -func countSearchMatches(content string) int { - matches := 0 - for line := range strings.SplitSeq(content, "\n") { - if isSearchMatchLine(strings.TrimSpace(line)) { - matches++ - } - } - return matches -} - -func isSearchMatchLine(line string) bool { - if line == "" || strings.HasPrefix(line, "[") { - return false - } - if strings.Trim(line, "-") == "" { - return false - } - for i := len(line) - 1; i > 0; i-- { - if line[i] != ':' { - continue - } - digits := line[i+1:] - end := 0 - for end < len(digits) && digits[end] >= '0' && digits[end] <= '9' { - end++ - } - if end > 0 && end < len(digits) && digits[end] == ':' { - return true - } - } - return false -} - -func firstInformativeLine(content string) string { - for line := range strings.SplitSeq(content, "\n") { - line = strings.TrimSpace(line) - if line == "" { - continue - } - if strings.Contains(line, "/pkg/mod/") { - continue - } - if _, ok := parseTruncationNotice(line); ok { - continue - } - return truncateRunes(line, 120) - } - return "" -} - -func pluralize(n int, one, many string) string { - if n == 1 { - return one - } - return many -} - -func unwrapToolContent(output string) (string, bool) { - trimmed := strings.TrimSpace(output) - if trimmed == "" { - return "", false - } - var envelope struct { - Content string `json:"content"` - } - if json.Unmarshal([]byte(trimmed), &envelope) == nil && envelope.Content != "" { - return envelope.Content, true - } - var quoted string - if json.Unmarshal([]byte(trimmed), "ed) == nil { - return quoted, true - } - return output, false -} - -func cleanToolError(name, raw string) string { - line := firstNonEmptyLine(raw) - prefix := "tool " + strings.TrimSpace(name) + ": " - line = strings.TrimPrefix(line, prefix) - return truncateRunes(strings.TrimSpace(line), toolSummaryMaxRunes) -} - -func legacyTurnBudgetLimit(raw string) (string, bool) { - const marker = "turn budget exceeded (" - _, after, ok := strings.Cut(raw, marker) - if !ok { - return "", false - } - rest := after - end := strings.Index(rest, " chars)") - if end < 1 { - return "", false - } - return rest[:end], true -} - -// SummarizeToolParameters returns a bounded JSON shape of tool input. -func SummarizeToolParameters(input string) string { - if strings.TrimSpace(input) == "" { - return "" - } - decoder := json.NewDecoder(strings.NewReader(input)) - decoder.UseNumber() - var value any - if err := decoder.Decode(&value); err != nil { - return "[unavailable]" - } - value = redactToolParameters(value, false) - encoded, err := json.Marshal(value) - if err != nil { - return "[unavailable]" - } - return truncateRunesWithinLimit(string(encoded), toolParametersMaxRunes) -} - -func redactToolParameters(value any, sensitive bool) any { - if sensitive { - return redactedParameterValue - } - switch typed := value.(type) { - case map[string]any: - for key, child := range typed { - typed[key] = redactToolParameters(child, sensitiveParameterKey(key)) - } - return typed - case []any: - for i, child := range typed { - typed[i] = redactToolParameters(child, sensitive) - } - return typed - default: - return value - } -} - -func sensitiveParameterKey(key string) bool { - normalized := strings.NewReplacer("-", "_", " ", "_").Replace(strings.ToLower(key)) - for _, marker := range webhookguard.SensitiveKeyMarkers { - if strings.Contains(normalized, marker) { - return true - } - } - return false -} - -func truncateRunesWithinLimit(s string, limit int) string { - runes := []rune(s) - if len(runes) <= limit { - return s - } - if limit <= 1 { - return "…" - } - return string(runes[:limit-1]) + "…" -} diff --git a/internal/webui/api_chat.go b/internal/webui/api_chat.go index cfb010f18..70b2e074f 100644 --- a/internal/webui/api_chat.go +++ b/internal/webui/api_chat.go @@ -580,11 +580,6 @@ func (s *Server) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request) progress := make([]string, 0, 4) meta := releaseupdate.InstallMeta{Channel: "webui", ReportPath: s.UpdateReportPath} - if s.TelegramUpdateReportPath != "" && s.TelegramUpdateChatID != 0 { - meta.Channel = "telegram" - meta.ChatID = s.TelegramUpdateChatID - meta.ReportPath = s.TelegramUpdateReportPath - } result, err := chat.Updates.Install(r.Context(), fresh, meta, func(message string) { progress = append(progress, message) }) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway)