Files
sam 86501fa1d4 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.
2026-10-31 15:30:27 +11:00

258 lines
7.1 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
gatewayv1 "github.com/samcharles93/archipelago/sdk/gateway/v1"
)
// typingRefresh is how often the typing indicator is re-sent; Telegram clears
// it after ~5s.
const typingRefresh = 4 * time.Second
// liveEditInterval bounds how often a streaming reply is edited in place.
const liveEditInterval = 2 * time.Second
// submitTurn routes one inbound message as a streamed chat turn and renders
// the reply live: deltas edit one message, tools and media post alongside, and
// the done text replaces what was streamed.
func (g *gateway) submitTurn(ctx context.Context, msg *models.Message, text string, media []*gatewayv1.Media) {
chatID, threadID := msg.Chat.ID, msg.MessageThreadID
in := inboundMessage(msg, text, media)
stopTyping := g.startTyping(ctx, chatID, threadID)
defer stopTyping()
stream, err := g.chat.Stream(ctx, &gatewayv1.StreamRequest{
Message: in,
CanApprove: true,
CanClarify: true,
CanPick: true,
CanQuestion: true,
})
switch status.Code(err) {
case codes.OK:
case codes.InvalidArgument, codes.PermissionDenied:
g.sendText(ctx, chatID, threadID, "Archie refused that message: "+status.Convert(err).Message())
return
default:
if err != nil {
g.log.ErrorContext(ctx, "stream failed", "error", err)
g.sendText(ctx, chatID, threadID, "Something went wrong on my side — try again in a moment.")
return
}
}
live := &liveReply{g: g, chatID: chatID, threadID: threadID}
var reply string
var streamErr error
lastEdit := time.Time{}
for {
ev, err := stream.Recv()
if errors.Is(err, context.Canceled) || ctx.Err() != nil {
return
}
if err != nil {
if status.Code(err) != codes.Canceled {
streamErr = err
}
break
}
switch ev.GetKind() {
case "delta":
live.buf.WriteString(ev.GetText())
if time.Since(lastEdit) >= liveEditInterval {
live.edit(ctx, false)
lastEdit = time.Now()
}
case "tool":
live.toolCall(ctx, ev.GetTool())
case "media":
g.sendMedia(ctx, chatID, threadID, ev.GetMedia())
case "ask":
g.presentAsk(ctx, chatID, threadID, ev.GetAsk())
case "done":
reply = ev.GetText()
case "error":
streamErr = errors.New(ev.GetText())
}
}
stopTyping()
switch {
case streamErr != nil:
g.log.ErrorContext(ctx, "stream turn failed", "error", streamErr)
live.editText(ctx, "⚠️ "+streamErr.Error(), true)
case reply != "":
live.editText(ctx, reply, true)
default:
live.finish(ctx)
}
}
// liveReply is one streamed reply: the deltas accumulate in buf and are edited
// into a single Telegram message.
type liveReply struct {
g *gateway
chatID int64
threadID int
buf strings.Builder
messageID int
}
func (l *liveReply) edit(ctx context.Context, final bool) {
text := l.buf.String()
if l.messageID == 0 {
params := &bot.SendMessageParams{ChatID: l.chatID, Text: clip(text, messageMaxLen)}
if l.threadID != 0 {
params.MessageThreadID = l.threadID
}
if sent, err := l.g.bot.SendMessage(ctx, params); err == nil {
l.messageID = sent.ID
}
return
}
l.g.editText(ctx, l.chatID, l.messageID, clip(text, messageMaxLen))
}
func (l *liveReply) editText(ctx context.Context, text string, final bool) {
if l.messageID == 0 {
l.buf.Reset()
l.buf.WriteString(text)
l.edit(ctx, final)
return
}
l.g.editText(ctx, l.chatID, l.messageID, text)
}
func (l *liveReply) finish(ctx context.Context) {
if l.messageID != 0 {
l.g.editText(ctx, l.chatID, l.messageID, clip(l.buf.String(), messageMaxLen))
}
}
// toolCall posts a completed tool call as its own short message when the
// operator turned show_tool_calls on.
func (l *liveReply) toolCall(ctx context.Context, tool *gatewayv1.ToolCall) {
if !l.g.settings.showTools || tool == nil {
return
}
name := tool.GetName()
if tool.GetError() != "" {
l.g.sendText(ctx, l.chatID, l.threadID, "🔧 "+name+" failed: "+tool.GetError())
return
}
l.g.sendText(ctx, l.chatID, l.threadID, "🔧 "+name)
}
// presentAsk poses a blocking question to the chat. Approvals get inline
// buttons; clarify, picker and questionnaire questions are posed as text and
// the chat's next message is consumed as the answer.
func (g *gateway) presentAsk(ctx context.Context, chatID int64, threadID int, ask *gatewayv1.Ask) {
if ask == nil {
return
}
key := pendingKey{chatID: chatID, threadID: threadID}
g.mu.Lock()
g.pending[key] = &pendingAsk{id: ask.GetId(), kind: ask.GetKind()}
g.mu.Unlock()
switch ask.GetKind() {
case "approval":
prompt := ask.GetPrompt()
if ask.GetDetail() != "" {
prompt += "\n\n" + ask.GetDetail()
}
g.sendApproval(ctx, chatID, threadID, ask.GetId(), prompt)
default:
g.sendText(ctx, chatID, threadID, askPrompt(ask))
}
}
func askPrompt(ask *gatewayv1.Ask) string {
var b strings.Builder
b.WriteString(ask.GetPrompt())
if len(ask.GetChoices()) > 0 {
b.WriteString("\n")
for i, c := range ask.GetChoices() {
fmt.Fprintf(&b, "%d. %s\n", i+1, c.GetLabel())
}
b.WriteString("Reply with a number or the text.")
}
if len(ask.GetQuestions()) > 0 {
for _, q := range ask.GetQuestions() {
fmt.Fprintf(&b, "\n• %s", q.GetTitle())
if q.GetDescription() != "" {
fmt.Fprintf(&b, " — %s", q.GetDescription())
}
}
}
return b.String()
}
// sendApproval posts the approval question with Approve / Always / Deny
// buttons whose callback carries the ask id and the answer.
func (g *gateway) sendApproval(ctx context.Context, chatID int64, threadID int, askID, prompt string) {
row := [][]models.InlineKeyboardButton{{
{Text: "Approve", CallbackData: "ask:" + askID + ":approve"},
{Text: "Always", CallbackData: "ask:" + askID + ":always"},
{Text: "Deny", CallbackData: "ask:" + askID + ":deny"},
}}
params := &bot.SendMessageParams{
ChatID: chatID,
Text: "🛑 Approval needed\n\n" + prompt,
ReplyMarkup: &models.InlineKeyboardMarkup{InlineKeyboard: row},
}
if threadID != 0 {
params.MessageThreadID = threadID
}
if _, err := g.bot.SendMessage(ctx, params); err != nil {
g.log.WarnContext(ctx, "send approval failed", "error", err)
}
}
// startTyping shows the typing indicator until the returned stop is called.
func (g *gateway) startTyping(ctx context.Context, chatID int64, threadID int) func() {
send := func(c context.Context) {
params := &bot.SendChatActionParams{ChatID: chatID, Action: models.ChatActionTyping}
if threadID != 0 {
params.MessageThreadID = threadID
}
if _, err := g.bot.SendChatAction(c, params); err != nil {
g.log.DebugContext(c, "send chat action failed", "error", err)
}
}
typingCtx, cancel := context.WithCancel(ctx)
send(typingCtx)
go func() {
ticker := time.NewTicker(typingRefresh)
defer ticker.Stop()
for {
select {
case <-typingCtx.Done():
return
case <-ticker.C:
send(typingCtx)
}
}
}()
return cancel
}
// clip truncates text to max runes.
func clip(text string, max int) string {
runes := []rune(text)
if len(runes) <= max {
return text
}
return string(runes[:max]) + "…"
}