Files
archie/internal/channels/telegram/telegram.go
T
sam e0b6aa6105 feat(workflow): post line-anchored review comments with suggested fixes (#891)
* feat(workflow): post line-anchored review comments with suggested fixes

Bead archie-core-q9au (docs/prds/inline-review.md). A review's findings reached
the operator only as a flat list in the PR body, so the author had to map every
finding back to its line by hand and apply mechanical fixes by hand. Now the
line-anchored findings are also posted as inline review comments, carrying a
one-click suggestion when the reviewer could state the fix.

Domain (internal/domain/workflow):
- ReviewFinding gains Suggestion; Validate rejects one on anything but a
  confirmed finding, so the agent's record_finding call is refused with
  something it can act on. Validate splits into validateAnchor /
  validateClassification / validateDisposition, which also brings it back under
  the cyclop limit the gate enforces.
- StagePostReviewComments runs after StageOpenPR in the implement workflow. It
  posts only line-anchored findings (Line > 0); a whole-file finding has no line
  to attach to and stays in the body list, which remains the complete record.
  It is best-effort: the PR is open and the body already lists every finding, so
  a failed comment is logged, never a park -- the same reasoning as OpenPR's
  existing best-effort LinkBranch call.
- The suggestion fence is gated on Verdict == confirmed where the fence is
  written, because it is a one-click apply: a wrong suggestion breaks the code
  and the author has to notice.

Forge (internal/forge): ReviewCommentWriter + GitHub/Gitea implementations,
type-asserted like PullRequestReader so a forge that cannot is skipped rather
than faked (NoopForge is pinned as not satisfying it). GitHub loops one
CreateComment per comment and joins the failures, so one refused anchor cannot
drop the rest; Gitea carries them on a single COMMENT-state review.

Two deliberate departures from the PRD's sketch, both recorded in it:
- The interface is batch (CreateReviewComments), not one call per comment:
  Gitea's only inline shape is one submitted review, and the set then crosses
  NATS once instead of once per finding.
- The head SHA is resolved inside each forge implementation rather than by the
  caller. The stage runs in archie-agent, which holds no forge credentials and
  has no PullRequestReader; the daemon-side forgerpc handler is the only place
  that does.

Transport (internal/forgerpc): workflow.Forger gains the method, so the agent
reaches the daemon over the new create_review_comments subject; the server
type-asserts the writer and answers an incapable forge with an error the stage
logs. This is the one proxied method whose absence on an image skew does not
park a task.

The reviewer prompt and record_finding schema ask for a suggestion on a
confirmed, mechanically fixable defect only.

Regenerating the wfextract symbol table -- the documented way a new exported
workflow symbol reaches interpreted stage plugins -- also picked up symbols that
were missing from the committed table (the Status* and Source* constants,
ReviewCheck, Store, Task, and the _Store wrapper). Nil-guards were re-applied to
every wrapper afterwards, as that file's header requires.

Evidence: task check exit 0 (incl. 229 UI tests). Three mutations of the new
stage logic each fail a test that names the behaviour -- dropping the
confirmed-only gate, dropping the Line > 0 filter, and letting a posting failure
escape -- so the tests discriminate rather than passing vacuously.

* fix(build): drop the Dockerfile pin assertion

The guard fetched golangci-lint's go.mod at image build time to fail the build
when GOLANGCI_LINT_VERSION and GOFUMPT_VERSION disagreed. It only ever tripped
on self-inflicted pin drift, but it added a network fetch and a new failure
mode to the release build, which is not where that belongs.

The pins stay correct (golangci-lint 2.13.2, whose vendored gofumpt v0.11.0
equals GOFUMPT_VERSION) and the comment above them still states the invariant,
so the reasoning survives without the build-time machinery. The pin change
itself reaches the agent image through the normal release path: CI rebuilds
and pushes archie-agent on an archie/vX.Y.Z release, and a gateway-only
release deliberately does not.

* feat(workflow): add the remediate workflow for PR review remediation

Implements step 5 of docs/prds/pr-review-remediation.md: a remediate
workflow that resumes the task's existing worktree onto its PR branch
(worktree.Manager.Resume, not Prepare's refresh), runs a builder agent
against the review's actionable comments, commits and pushes to the
same branch, and replies via the forge's ReplyToReview. Task.RetryCount
doubles as the remediation round counter, capped by the repo's
max_retries; the round-cap stage parks the task and posts one comment
when it's hit.

Task gains a ReviewPayload field (JSON-encoded review unit) with full
store/proto/staterpc plumbing. workflow.Forger gains Comment and
ReplyToReview, proxied to archie-agent via a new forgerpc RPC. Resume
and its Dir lookup are added as an unexported optional Trees capability
rather than widening the exported interface, which is already at
golangci-lint's interfacebloat cap and is projected into wfextract's
Yaegi symbol table for repository-authored stage plugins.

The daemon-side reaction consumer that dispatches into this workflow
(subscribing ARCHIE_REACTIONS, grouping comments by review, enforcing
per-task serialization) is tracked separately in archie-core-8li9.4.

* feat(messaging): extract standalone messaging service binary and process composition

* feat(messaging): adapt channel frontends to consume Gateway ChatContract

* feat(messaging): remove in-process channels and Router from daemon bootstrap

Telegram, email and webhook now run only in the Messaging Service, which
reaches this process through the Gateway's ChatContract. The daemon builds
no channel and no gateway.Router, so the wiring that existed only to serve
them goes with it: setupGateways, setupEmailGateway, setupWebhookGateway,
setupTelegramGateway, buildTelegramRouter, makeTelegramReload and the
release-announcement path helper.

The seams those paths owned move to where they can still be honoured:

- Channel ValidateConfig runs in archiemessaging.compose, which now returns
  an error, so a configured-but-invalid front-end fails the service rather
  than being dropped silently.
- The inbound rate limiter moves to the Gateway process, which owns the only
  Router and therefore the only place a per-sender budget applies to every
  channel's turns.
- The daemon's gateway readiness probe becomes a ContractProbe against the
  Gateway. It cannot observe a channel lifecycle it no longer runs, and a
  channel-count probe would have reported every daemon degraded.
- telegramSetup is now chatSetup (in chat_setup.go), trimmed to the fields a
  chat turn runner actually reads.

Telegram operator features that were wired only in the daemon (/update,
release announcements, version reporting, SIGHUP reload) are not yet wired
in the Messaging Service: archie-core-8cda.6.6. Channel lifecycle reporting:
archie-core-8cda.6.8. The Gateway process builds no worktree manager, so
review_pr is unadvertised on every channel: archie-core-8cda.6.7.

* feat(messaging): re-wire the Telegram operator surface in the Messaging Service

setupTelegramGateway satisfied eight telegram.Gateway seams from the daemon's
own process. Each is resolved by where the fact it needs is owned, not by
where it used to be built; the decision table is in
docs/architecture/migration-decisions.md.

Wired here: /update (built from this service's own [chat.telegram] check and
install commands), the update-report relay (same sha256(bot_user)[:8] path the
daemon wrote, so a pending report is found rather than written afresh),
show_tool_calls, and /restart's config reload, which re-resolves the token and
allowlist from this service's own file and refuses a reload that resolves to
an empty token.

/version is sourced from the Gateway: ChatSnapshot gains a Version field
carrying the Gateway's rendered build block, read per call and bounded by the
dependency timeout. cmd/archie-messaging deliberately takes no version
ldflags, so it cannot report a partial upgrade as a matched one.

RunningVersions and ReleaseAnnouncements stay nil. Both need a component's
real running version, and the only versions this process can obtain are a
different binary's stamps -- reporting them would manufacture exactly the
false success the update check exists to catch, and the announcer without
parseable versions is a no-op that reads as configured. archie-core-8cda.6.9
carries the contract that unblocks them. Dangerous stays nil: no composition
has ever supplied a command authority.

Enrich is dropped from the update service: componentInstallTypeEnricher read
[nats], which this service must not decode, so the check command's own
reported install type stands.

* fix(workflow): guard inline review comments against head drift

Two findings from the review of q9au.

A comment's line numbers describe exactly one revision of the branch, but the
forge resolved the pull request's head at posting time -- after the review had
already read the worktree. A push in that window (a collaborator, a retry) meant
the findings were anchored to whatever now occupied those lines, mislabelling
instead of failing. The revision the review measured now travels with the
comment set: OpenPR records it from the same worktree read it already performs
(TaskContext.ReviewedHeadSHA), StagePostReviewComments threads it through
Forger to forgerpc, and the forge refuses the whole set once the head it reads
has moved off it -- which the best-effort stage logs, the PR body remaining the
record. An unmeasured revision posts unverified rather than dropping every
finding, so a worktree that cannot report one degrades instead of regressing.

Suggestion was documented single-line only, because GitHub applies a suggestion
fence up to its first line and a multi-line replacement would silently corrupt
the file. Only the verdict was validated, so a multi-line suggestion reached the
renderer and posted as that truncated fence. Validate now rejects an embedded
newline, which makes record_finding refuse it with feedback the model can act on
instead of the reviewer discovering the corruption later.
2026-09-19 23:37:23 +10:00

930 lines
34 KiB
Go

// 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"
"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 Telegram user IDs allowed to use the bot,
// matched against the sender rather than the chat so the bot cannot be
// reached by adding it to a group. Empty denies everyone: a bot handle
// is public, and chat tools run with the daemon's authority, so failing
// open would expose those tools to any stranger who finds the bot.
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
// UpdateReportPath is where the update watchdog (see
// scripts/archie-update-watchdog) leaves the phase-2 outcome of an
// update -- whether the restarted daemon came up healthy or was rolled
// back. Checked and relayed on every gateway launch (process boot and
// /restart alike), same as ReleaseAnnouncements. Empty disables it.
UpdateReportPath string
// RunningVersions reports, per component ID (see
// releaseupdate.ComponentDaemon), the version that component reports for
// itself rather than the version an installer claimed to install. It is
// what turns a pending update report from a self-reported claim into a
// checked one: the daemon's own compiled-in build version cannot be
// talked out of being what is actually running. Only components that can
// genuinely self-report belong here -- a guess would re-introduce
// exactly the false success this check exists to catch. Nil leaves every
// claim unverified.
RunningVersions func() map[string]string
// Dangerous is the sandbox/process authority for /rollback and /stop.
// When nil, those commands return "not configured". The composition
// root supplies this; Telegram only renders approval UX.
Dangerous DangerousCommandAuthority
// 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
// dangerous command approval state
dangerousMu sync.Mutex
dangerousActions map[string]dangerousAction
permanentApprovals []permanentApproval
// tool approval state (gateway.ApprovalRequester). Kept separate from
// the dangerous-command state above: tool approvals deliver the human's
// decision on a channel to the blocked RequestApproval call rather than
// executing through an onApprove callback.
approvalMu sync.Mutex
pendingApprovals map[string]*pendingApproval
// 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 every liveReply currently mid-turn. Cancelling
// turnCtx (a /restart, a daemon shutdown) does not guarantee the
// goroutine that owns a liveReply ever runs again to notice and clean
// up after itself -- a full process exit gives it no chance at all --
// so Stop drains this registry directly rather than waiting on that
// goroutine. See abandonAllLive. The map itself survives a /restart
// (only turns above is rebuilt per launch); liveStopped is what scopes
// draining to one launch's lifecycle.
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 the instant abandonAllLive claims the registry, so
// a newLiveReply that arrives in the narrow window between that claim
// and its caller actually registering is abandoned immediately instead
// of being added to a registry nothing will ever drain again. Reset to
// false at the start of the next launch.
liveStopped bool
log *slog.Logger
bot *bot.Bot
running bool
// 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
}
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 {
return &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),
dangerousActions: make(map[string]dangerousAction),
permanentApprovals: nil,
pendingApprovals: make(map[string]*pendingApproval),
log: log.With("component", "gateway-telegram"),
}
}
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 supervises the bot: it launches an instance and relaunches it
// whenever a restart is requested, blocking until ctx is cancelled.
//
// Restarts are scoped to this gateway. The daemon keeps running, so
// in-flight agent tasks are untouched -- the whole point of the escape
// hatch is to recover chat without disturbing work in progress.
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.Info("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 to whoever asked, now that the new instance can send.
if req := g.pendingRestart; req != nil && req.chatID != 0 {
g.sendMessage(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.Info("restarting telegram gateway", "requested_by", req.chatID)
cancel()
if err := g.Stop(context.WithoutCancel(ctx)); err != nil {
g.log.Warn("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.Error("config reload failed, restarting with previous settings", "error", err)
}
}
g.pendingRestart = &req
}
}
}
func (g *Gateway) registerCommandHandlers(b *bot.Bot, client messaging.ChatContract) {
b.RegisterHandler(bot.HandlerTypeMessageText, "/status", bot.MatchTypeExact, g.statusHandler(client))
b.RegisterHandler(bot.HandlerTypeMessageText, "/whoami", bot.MatchTypeExact, g.whoamiHandler(client))
b.RegisterHandler(bot.HandlerTypeMessageText, "/profile", bot.MatchTypeExact, g.profileHandler(client))
b.RegisterHandler(bot.HandlerTypeMessageText, "/sessions", bot.MatchTypeExact, g.sessionsHandler(client))
b.RegisterHandler(bot.HandlerTypeMessageText, "/resume", bot.MatchTypeExact, g.resumeHandler(client))
b.RegisterHandler(bot.HandlerTypeMessageText, "/agents", bot.MatchTypeExact, g.agentsHandler(client))
b.RegisterHandler(bot.HandlerTypeMessageText, "/version", bot.MatchTypeExact, g.versionHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/update", bot.MatchTypeExact, g.updateHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/start", bot.MatchTypeExact, g.startHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/help", bot.MatchTypeExact, g.helpHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/restart", bot.MatchTypeExact, g.restartHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/rollback", bot.MatchTypePrefix, g.rollbackHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/stop", bot.MatchTypePrefix, g.stopHandler(client))
b.RegisterHandler(bot.HandlerTypeMessageText, "/approve", bot.MatchTypeExact, g.approveHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/deny", bot.MatchTypeExact, g.denyHandler())
}
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.Debug("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.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.Warn("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.Info("stopping telegram gateway")
g.running = false
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{Message: messaging.Message{
ConversationID: conversationID(msg),
Sender: msg.From.Username,
Role: messaging.RoleUser,
Text: msg.Text,
}})
if err != nil {
g.log.Error("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{Message: messaging.Message{
ConversationID: conversationID(msg),
Sender: msg.From.Username,
Role: messaging.RoleUser,
Text: cmd,
}})
if err != nil {
g.log.Error("command handler failed", "command", cmd, "error", err)
return
}
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply.Text)
}
}
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 (non-command text → 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 || 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
}
if isPersonalityRequest(msg.Text) {
g.handlePersonalityCommand(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, dangerousCmdPrefix):
g.handleDangerousCallback(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, personalityCallbackPrefix):
g.handlePersonalityCallback(ctx, b, update, client)
case strings.HasPrefix(update.CallbackQuery.Data, updateCallbackPrefix):
g.handleUpdateCallback(ctx, b, update)
}
}
// submitTurn hands the message to its session's turn lane and returns at
// once, leaving the bot's single update worker free.
//
// The turn must not run on the caller's goroutine. go-telegram/bot serves
// updates from one worker that invokes handlers synchronously, so a turn
// running here would block delivery of every later update -- including the
// /stop meant to cancel it, which would sit unread until the turn it was
// aimed at had already finished.
func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Message, client messaging.ChatContract) {
gm := messaging.Inbound{Message: messaging.Message{
// Telegram's message ID makes persistence idempotent: the store
// derives a canonical ID from it, so a redelivered update is a
// no-op rather than appending a duplicate or overwriting the
// stored record, which must stay immutable. Date is the sender's
// clock reading and is what history should be ordered by.
SourceID: fmt.Sprintf("%d", msg.ID),
ConversationID: conversationID(msg),
Sender: msg.From.Username,
SenderID: fmt.Sprintf("%d", msg.From.ID),
Role: messaging.RoleUser,
Text: msg.Text,
At: time.Unix(int64(msg.Date), 0).UTC(),
}}
// 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 the turn invokes a tool that requires human 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)
// 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.Info("chat turn stopped", "session", session)
live.abandon(turnCtx)
} else {
g.log.Error("stream failed", "error", err)
live.abandonFailed(turnCtx)
}
return
}
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()
// A cancelled turn is a /stop, not a fault. The stop handler has
// already acknowledged it, and turnCtx is dead, so there is
// nothing useful left to send from here -- but whatever was
// already streamed stays, minus the cursor that would otherwise
// claim the answer is still being written. abandon strips turnCtx's
// own cancellation before it edits, so the cursor-drop is not itself
// aborted by the /stop that triggered it.
//
// errors.Is(err, context.Canceled) reliably separates a /stop from a
// fault; either way turnCtx is dead by the time we get here. A
// genuine fault is marked as failed rather than left as a clean
// partial: /stop is an acknowledged interruption, a provider error
// is not, and an unmarked partial reads as a finished answer either
// way.
if streamErr != nil || turnCtx.Err() != nil {
if errors.Is(turnCtx.Err(), context.Canceled) || (streamErr != nil && errors.Is(streamErr, context.Canceled)) {
g.log.Info("chat turn stopped", "session", session)
live.abandon(turnCtx)
} else {
g.log.Error("stream turn failed", "error", streamErr)
live.abandonFailed(turnCtx)
}
return
}
live.finalize(turnCtx, reply)
})
}
// ── 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.Warn(
"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.Debug("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")
}
}
// sendBlocks delivers one message as a Telegram rich message built from
// structured blocks.
//
// Rich messages are a recent Bot API addition, so a rejection here is treated
// as "unsupported" rather than fatal: fall back to sending the blocks as plain
// text so the user still receives the reply, unformatted, instead of silence.
func (g *Gateway) sendBlocks(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, blocks []models.InputRichBlock, errMsg string) {
rich := &bot.SendRichMessageParams{
ChatID: chatID,
RichMessage: models.InputRichMessage{Blocks: blocks},
}
if messageThreadID != 0 {
rich.MessageThreadID = messageThreadID
}
if _, err := b.SendRichMessage(ctx, rich); err == nil {
g.log.Debug("telegram message sent", "renderer", telegramRenderVersion, "mode", "rich")
return
} else {
g.log.Warn("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 _, err := b.SendMessage(ctx, plain); err != nil {
g.log.Error(errMsg, "error", err)
} else {
g.log.Warn("telegram message sent via plain fallback", "renderer", telegramRenderVersion, "mode", "plain")
}
}
// 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.Error("panic in telegram middleware", attrs...)
}
}()
next(ctx, b, update)
}
}
}
func (g *Gateway) updateLoggingMiddleware() bot.Middleware {
return func(next bot.HandlerFunc) bot.HandlerFunc {
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
kind, chatID, hasChat := updateMetadata(update)
attrs := []any{"update_kind", kind, "update_id", update.ID}
if hasChat {
attrs = append(attrs, "chat_id", chatID)
}
if threadID := updateThreadID(update); threadID != 0 {
attrs = append(attrs, "thread_id", threadID)
}
g.log.Debug("telegram update", attrs...)
next(ctx, b, update)
}
}
}
func updateMetadata(update *models.Update) (kind string, chatID int64, hasChat bool) {
switch {
case update == nil:
return "unknown", 0, false
case update.Message != nil:
return "message", update.Message.Chat.ID, true
case update.CallbackQuery != nil:
if update.CallbackQuery.Message.Message != nil {
return "callback_query", update.CallbackQuery.Message.Message.Chat.ID, true
}
return "callback_query", 0, false
default:
return "other", 0, false
}
}
// 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 may be supplied either directly as token_env (an
// environment variable name) or as token (a secret reference object with
// engine/key); token takes precedence when both are set, matching
// resolveTelegramToken's own precedence.
func (g *Gateway) ConfigSchema() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"anyOf": [
{ "required": ["token_env"] },
{ "required": ["token"] }
],
"properties": {
"token_env": {
"type": "string",
"description": "Environment variable holding the Telegram bot token from @BotFather"
},
"token": {
"type": "object",
"description": "Secret reference for the bot token, resolved through the configured secret engine. Takes precedence over token_env.",
"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 is
// required, supplied either as token (a secret reference) or token_env
// (an environment variable name) -- either credential source is valid,
// matching resolveTelegramToken's precedence in the daemon's boot path.
func (g *Gateway) ValidateConfig(cfg map[string]any) error {
if cfg == nil {
return fmt.Errorf("telegram config is required")
}
tokenEnv, _ := cfg["token_env"].(string)
_, hasTokenRef := cfg["token"]
if tokenEnv == "" && !hasTokenRef {
return fmt.Errorf("telegram.token or telegram.token_env is required")
}
return nil
}
// Compile-time guard.
var _ channels.Channel = (*Gateway)(nil)
// dropPendingUpdates clears Telegram's queue of undelivered updates before
// long polling starts.
//
// Telegram holds updates for 24h and replays them on the first getUpdates,
// so without this a daemon that was down overnight boots and answers every
// message sent while it was gone -- one LLM turn each, in a burst. The
// webhook path already passes DropPendingUpdates when it registers; polling
// has no equivalent, so it has to be asked for explicitly. deleteWebhook is
// the call that carries the flag, and it doubles as a guard against a stale
// webhook registration, which would make getUpdates fail with 409.
//
// This also runs on /restart, so a message sent during the restart window is
// discarded rather than answered late. That matches the webhook branch, which
// passes the same flag on every launch.
//
// Best-effort: a failure here is logged, not fatal. Chat availability matters
// more than a clean queue, and the deadline keeps an unreachable Telegram
// from holding up gateway startup.
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.Warn("could not drop pending telegram updates, backlog may be replayed", "error", err)
}
}