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.
This commit is contained in:
sam committed 2026-10-31 15:30:27 +11:00
1 parent d03062cad8
commit 86501fa1d4
10 files changed
+2115 -276

No files matched your search

+492
View File
@@ -0,0 +1,492 @@
// Command telegram is the Telegram chat channel. It long-polls the Bot API,
// routes messages from allowed user ids through the gateway ChatService, and
// replies in the chat. Settings: token_ref ("engine:key" naming the bot token
// from @BotFather), allowed_user_ids (comma-separated Telegram user ids; empty
// denies everyone) and show_tool_calls ("true"/"false", default false).
package main
import (
"context"
"errors"
"fmt"
"log/slog"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/samcharles93/archipelago/sdk/channel"
gatewayv1 "github.com/samcharles93/archipelago/sdk/gateway/v1"
)
const platform = "telegram"
type settings struct {
token string
allowed []int64
showTools bool
}
func main() { channel.Serve(run) }
func run(ctx context.Context, cfg channel.Config, chat gatewayv1.ChatServiceClient, lifecycle channel.Lifecycle) error {
lifecycle.Starting()
s, err := parseSettings(cfg)
if err != nil {
return err
}
log := slog.Default().With("component", "telegram")
g := &gateway{
settings: s,
chat: chat,
log: log,
pending: map[pendingKey]*pendingAsk{},
}
b, err := bot.New(s.token,
bot.WithDefaultHandler(g.defaultHandler),
bot.WithErrorsHandler(func(err error) { log.WarnContext(ctx, "telegram error", "error", err) }),
bot.WithMiddlewares(g.panicRecovery()),
)
if err != nil {
return fmt.Errorf("telegram: create bot: %w", err)
}
g.bot = b
g.registerCommands(b)
if _, err := b.DeleteWebhook(ctx, &bot.DeleteWebhookParams{DropPendingUpdates: true}); err != nil {
log.WarnContext(ctx, "could not drop pending updates, backlog may be replayed", "error", err)
}
if _, err := b.SetMyCommands(ctx, &bot.SetMyCommandsParams{Commands: botCommands()}); err != nil {
log.WarnContext(ctx, "could not publish the command menu", "error", err)
}
lifecycle.Running()
log.InfoContext(ctx, "telegram channel polling", "allowed_user_ids", len(s.allowed))
b.Start(ctx)
return nil
}
// parseSettings reads the operator's settings. token comes from token_ref,
// which the host resolved into secrets under "token".
func parseSettings(cfg channel.Config) (settings, error) {
s := settings{
token: cfg.Secrets["token"],
showTools: cfg.Settings["show_tool_calls"] == "true",
}
for part := range strings.SplitSeq(cfg.Settings["allowed_user_ids"], ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
id, err := strconv.ParseInt(part, 10, 64)
if err != nil || id <= 0 {
return s, fmt.Errorf("telegram: allowed_user_ids %q is not a positive Telegram user id", part)
}
s.allowed = append(s.allowed, id)
}
if s.token == "" {
return s, errors.New("telegram: token_ref is required")
}
if len(s.allowed) == 0 {
return s, errors.New("telegram: allowed_user_ids is required; the bot answers nobody without it")
}
return s, nil
}
// gateway is one running channel: the bot, the chat service and the asks
// waiting on a user decision.
type gateway struct {
settings settings
chat gatewayv1.ChatServiceClient
log *slog.Logger
bot *bot.Bot
mu sync.Mutex
pending map[pendingKey]*pendingAsk
}
// pendingKey identifies the chat an ask was posed to, so only that chat's
// next text or button answers it.
type pendingKey struct {
chatID int64
threadID int
}
// pendingAsk is one question the turn blocks on until Answer names its id.
type pendingAsk struct {
id string
kind string
}
func (g *gateway) allowedUser(userID int64) bool {
return slices.Contains(g.settings.allowed, userID)
}
// authorized returns the message when its sender is allowed, and tells the
// chat otherwise so a misconfigured allowlist is visible rather than silent.
func (g *gateway) authorized(ctx context.Context, update *models.Update) *models.Message {
msg := update.Message
if msg == nil || msg.From == nil {
return nil
}
if g.allowedUser(msg.From.ID) {
return msg
}
g.log.WarnContext(ctx, "message from unauthorized sender",
"user_id", msg.From.ID, "username", msg.From.Username, "chat_id", msg.Chat.ID)
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID,
"⛔ You are not authorised to use this bot.")
return nil
}
// conversationKey is the session a chat addresses: the chat id, and the topic
// thread within it for supergroups. It matches the host's session key for
// the conversation, so /stop reaches the turn the sender is watching.
func conversationKey(msg *models.Message) string {
if msg.MessageThreadID == 0 {
return strconv.FormatInt(msg.Chat.ID, 10)
}
return strconv.FormatInt(msg.Chat.ID, 10) + "/" + strconv.Itoa(msg.MessageThreadID)
}
// inboundMessage renders a Telegram message as the gateway's wire message.
func inboundMessage(msg *models.Message, text string, media []*gatewayv1.Media) *gatewayv1.Message {
m := &gatewayv1.Message{
MessageId: strconv.Itoa(msg.ID),
SourceId: strconv.Itoa(msg.ID), // redelivery is idempotent on this
ChannelId: strconv.FormatInt(msg.Chat.ID, 10),
From: msg.From.Username,
SenderId: strconv.FormatInt(msg.From.ID, 10),
Text: text,
At: timestampOf(msg.Date),
Platform: platform,
Media: media,
}
if msg.MessageThreadID != 0 {
m.ThreadId = strconv.Itoa(msg.MessageThreadID)
}
return m
}
func timestampOf(unix int) *timestamppb.Timestamp {
if unix == 0 {
return nil
}
return timestamppb.New(time.Unix(int64(unix), 0).UTC())
}
// defaultHandler routes every update that is not a registered command: an
// answer to a pending question first, then media and text as a new turn.
func (g *gateway) defaultHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
if update.CallbackQuery != nil {
g.handleCallback(ctx, update.CallbackQuery)
return
}
msg := g.authorized(ctx, update)
if msg == nil {
return
}
if g.consumePendingAnswer(ctx, msg) {
return
}
text, media := msg.Text, []*gatewayv1.Media(nil)
if attachment, ok := inboundAttachment(msg); ok {
if data, err := g.download(ctx, attachment.fileID); err != nil {
g.log.WarnContext(ctx, "attachment download failed", "file_id", attachment.fileID, "error", err)
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID, "I couldn't download that file — try sending it again.")
return
} else {
media = []*gatewayv1.Media{{
Type: attachment.kind, FileId: attachment.fileID,
MimeType: attachment.mime, FileName: attachment.name, Data: data,
}}
text = strings.TrimSpace(attachment.note + " " + text)
}
}
if text == "" && len(media) == 0 {
return
}
g.submitTurn(ctx, msg, text, media)
}
// handleCallback answers a pending approval button.
func (g *gateway) handleCallback(ctx context.Context, q *models.CallbackQuery) {
data := q.Data
const prefix = "ask:"
if !strings.HasPrefix(data, prefix) {
_, _ = g.bot.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{CallbackQueryID: q.ID})
return
}
rest := strings.TrimPrefix(data, prefix)
askID, answer, ok := strings.Cut(rest, ":")
if !ok {
return
}
key := pendingKey{}
if msg := q.Message.Message; msg != nil {
key = pendingKey{chatID: msg.Chat.ID, threadID: msg.MessageThreadID}
}
g.mu.Lock()
_, pending := g.pending[key]
delete(g.pending, key)
g.mu.Unlock()
_, _ = g.bot.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{CallbackQueryID: q.ID})
if !pending {
return
}
if _, err := g.chat.Answer(ctx, &gatewayv1.AnswerRequest{AskId: askID, Answer: answer}); err != nil {
g.log.WarnContext(ctx, "answer failed", "ask_id", askID, "error", err)
return
}
if msg := q.Message.Message; msg != nil {
g.editText(ctx, msg.Chat.ID, msg.ID, "✅ Answered: "+answer)
}
}
// consumePendingAnswer routes a text message that answers a blocked clarify,
// picker or questionnaire instead of starting a new turn.
func (g *gateway) consumePendingAnswer(ctx context.Context, msg *models.Message) bool {
key := pendingKey{chatID: msg.Chat.ID, threadID: msg.MessageThreadID}
g.mu.Lock()
ask, ok := g.pending[key]
if ok {
delete(g.pending, key)
}
g.mu.Unlock()
if !ok || msg.Text == "" {
return false
}
if _, err := g.chat.Answer(ctx, &gatewayv1.AnswerRequest{AskId: ask.id, Answer: msg.Text}); err != nil {
g.log.WarnContext(ctx, "answer failed", "ask_id", ask.id, "error", err)
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID, "I couldn't deliver that answer; the question may have expired.")
}
return true
}
func (g *gateway) registerCommands(b *bot.Bot) {
for _, cmd := range []struct {
name string
handler bot.HandlerFunc
}{
{"/start", g.startHandler},
{"/help", g.helpHandler},
{"/version", g.versionHandler},
{"/stop", g.stopHandler},
} {
b.RegisterHandler(bot.HandlerTypeMessageText, cmd.name, bot.MatchTypeExact, cmd.handler)
}
b.RegisterHandler(bot.HandlerTypeCallbackQueryData, "ask:", bot.MatchTypePrefix, g.callbackHandler)
}
func (g *gateway) callbackHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
g.handleCallback(ctx, update.CallbackQuery)
}
func (g *gateway) startHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
msg := g.authorized(ctx, update)
if msg == nil {
return
}
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID,
"Archie is running. Send a message to chat, or type /help for available commands.")
}
func (g *gateway) helpHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
msg := g.authorized(ctx, update)
if msg == nil {
return
}
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID, helpText())
}
// versionHandler reports the gateway's build, fetched per call.
func (g *gateway) versionHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
msg := g.authorized(ctx, update)
if msg == nil {
return
}
snapshot, err := g.chat.Snapshot(ctx, &gatewayv1.SnapshotRequest{})
if err != nil || snapshot.GetVersion() == "" {
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID, "Version information is unavailable.")
return
}
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID, snapshot.GetVersion())
}
// stopHandler serves /stop: bare /stop cancels the conversation's running
// reply, else stops the tasks this conversation created; /stop <id> stops one
// task.
func (g *gateway) stopHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
msg := g.authorized(ctx, update)
if msg == nil {
return
}
rest := strings.TrimSpace(strings.TrimPrefix(msg.Text, "/stop"))
if rest == "" {
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID, g.stopConversation(ctx, msg))
return
}
id, err := strconv.ParseInt(strings.TrimPrefix(rest, "#"), 10, 64)
if err != nil || id <= 0 {
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID, "Usage: /stop, or /stop <task-id>")
return
}
g.sendText(ctx, msg.Chat.ID, msg.MessageThreadID, g.stopTasks(ctx, originOf(msg), id))
}
// stopConversation cancels the chat's most recently active session; with none
// running it stops the conversation's tasks instead.
func (g *gateway) stopConversation(ctx context.Context, msg *models.Message) string {
sessions, err := g.chat.GetSessionsByChannel(ctx, &gatewayv1.GetSessionsByChannelRequest{
Platform: platform, ChannelId: strconv.FormatInt(msg.Chat.ID, 10),
})
if err == nil {
thread := ""
if msg.MessageThreadID != 0 {
thread = strconv.Itoa(msg.MessageThreadID)
}
var latest *gatewayv1.Session
for _, s := range sessions.GetSessions() {
if s.GetThreadId() != thread {
continue
}
if latest == nil || s.GetLastActiveAt().AsTime().After(latest.GetLastActiveAt().AsTime()) {
latest = s
}
}
if latest != nil {
if res, err := g.chat.Cancel(ctx, &gatewayv1.CancelRequest{SessionId: latest.GetSessionId()}); err == nil && (res.GetCancelled() || res.GetDropped() > 0) {
return stopReport(res.GetCancelled(), int(res.GetDropped()), nil)
}
}
}
return g.stopTasks(ctx, originOf(msg), 0)
}
func (g *gateway) stopTasks(ctx context.Context, origin string, id int64) string {
res, err := g.chat.StopTasks(ctx, &gatewayv1.StopTasksRequest{Origin: origin, TaskId: id})
if err != nil {
return "Could not stop: " + err.Error()
}
stopped := make([]int64, 0, len(res.GetStopped()))
stopped = append(stopped, res.GetStopped()...)
report := stopReport(false, 0, stopped)
if res.GetError() != "" {
report += "\n\n" + res.GetError()
}
return report
}
func originOf(msg *models.Message) string {
return platform + ":" + conversationKey(msg)
}
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] = "#" + strconv.FormatInt(id, 10)
}
parts = append(parts, "task(s) "+strings.Join(ids, ", "))
}
if len(parts) == 0 {
return "Nothing is running."
}
return "🛑 Stopped " + joinWithAnd(parts) + "."
}
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]
}
}
// botCommands is the published command menu; the handlers it names are the
// ones this channel answers locally. Everything else routes through the
// gateway like any other message.
func botCommands() []models.BotCommand {
return []models.BotCommand{
{Command: "start", Description: "Confirm that Archie is running"},
{Command: "help", Description: "See what Archie can do"},
{Command: "version", Description: "Show installed Archie versions"},
{Command: "stop", Description: "Stop the running reply or this chat's tasks"},
}
}
func helpText() string {
return "Send a message to chat. Commands: /start, /help, /version, /stop — every other slash command is answered by Archie itself."
}
// sendText sends one message, split under Telegram's 4096-character limit.
func (g *gateway) sendText(ctx context.Context, chatID int64, threadID int, text string) {
for _, part := range splitText(text, messageMaxLen) {
params := &bot.SendMessageParams{ChatID: chatID, Text: part}
if threadID != 0 {
params.MessageThreadID = threadID
}
if _, err := g.bot.SendMessage(ctx, params); err != nil {
g.log.WarnContext(ctx, "send message failed", "chat_id", chatID, "error", err)
}
}
}
func (g *gateway) editText(ctx context.Context, chatID int64, messageID int, text string) {
parts := splitText(text, messageMaxLen)
if _, err := g.bot.EditMessageText(ctx, &bot.EditMessageTextParams{ChatID: chatID, MessageID: messageID, Text: parts[0]}); err != nil {
g.log.DebugContext(ctx, "edit message failed", "chat_id", chatID, "error", err)
}
}
// messageMaxLen keeps one message under Telegram's 4096-character limit.
const messageMaxLen = 4000
// splitText splits on paragraph boundaries, then hard-wraps long lines.
func splitText(text string, max int) []string {
if len([]rune(text)) <= max {
return []string{text}
}
var parts []string
for _, para := range strings.Split(text, "\n\n") {
for len([]rune(para)) > max {
cut := max
if i := strings.LastIndex(para[:min(cut, len(para))], "\n"); i > 0 {
cut = i
}
parts = append(parts, para[:cut])
para = strings.TrimLeft(para[cut:], "\n")
}
if para != "" {
parts = append(parts, para)
}
}
return parts
}
func (g *gateway) panicRecovery() 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 {
g.log.ErrorContext(ctx, "panic in telegram handler", "panic", r)
}
}()
next(ctx, b, update)
}
}
}
+131
View File
@@ -0,0 +1,131 @@
package main
import (
"strings"
"testing"
"github.com/go-telegram/bot/models"
"github.com/samcharles93/archipelago/sdk/channel"
)
func TestParseSettings(t *testing.T) {
for _, tc := range []struct {
name string
cfg channel.Config
wantErr string
check func(t *testing.T, s settings)
}{
{
name: "token and allowlist",
cfg: channel.Config{
Settings: map[string]string{"allowed_user_ids": " 111, 222 ,,333 "},
Secrets: map[string]string{"token": "123:ABC"},
},
check: func(t *testing.T, s settings) {
if s.token != "123:ABC" {
t.Errorf("token = %q", s.token)
}
if len(s.allowed) != 3 || s.allowed[0] != 111 || s.allowed[2] != 333 {
t.Errorf("allowed = %v", s.allowed)
}
if s.showTools {
t.Error("showTools defaulted true")
}
},
},
{
name: "show_tool_calls on",
cfg: channel.Config{
Settings: map[string]string{"allowed_user_ids": "1", "show_tool_calls": "true"},
Secrets: map[string]string{"token": "t"},
},
check: func(t *testing.T, s settings) {
if !s.showTools {
t.Error("showTools = false, want true")
}
},
},
{name: "missing token", cfg: channel.Config{Settings: map[string]string{"allowed_user_ids": "1"}}, wantErr: "token_ref"},
{name: "missing allowlist", cfg: channel.Config{Secrets: map[string]string{"token": "t"}}, wantErr: "allowed_user_ids"},
{name: "empty allowlist", cfg: channel.Config{Secrets: map[string]string{"token": "t"}, Settings: map[string]string{"allowed_user_ids": " ,"}}, wantErr: "allowed_user_ids"},
{name: "bad user id", cfg: channel.Config{Secrets: map[string]string{"token": "t"}, Settings: map[string]string{"allowed_user_ids": "abc"}}, wantErr: "not a positive"},
{name: "negative user id", cfg: channel.Config{Secrets: map[string]string{"token": "t"}, Settings: map[string]string{"allowed_user_ids": "-5"}}, wantErr: "not a positive"},
} {
t.Run(tc.name, func(t *testing.T) {
s, err := parseSettings(tc.cfg)
if tc.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
t.Fatalf("err = %v, want it to mention %q", err, tc.wantErr)
}
return
}
if err != nil {
t.Fatalf("parseSettings: %v", err)
}
if tc.check != nil {
tc.check(t, s)
}
})
}
}
func TestSplitText(t *testing.T) {
long := strings.Repeat("a", 9000)
parts := splitText(long, messageMaxLen)
if len(parts) != 3 {
t.Fatalf("splitText gave %d parts, want 3", len(parts))
}
for _, p := range parts {
if len([]rune(p)) > messageMaxLen {
t.Errorf("part is %d runes, over the limit", len([]rune(p)))
}
}
if got := splitText("short", messageMaxLen); len(got) != 1 || got[0] != "short" {
t.Errorf("splitText(short) = %v", got)
}
paras := splitText("one\n\n"+long, messageMaxLen)
if paras[0] != "one" {
t.Errorf("first part = %q, want %q", paras[0], "one")
}
}
func TestConversationKey(t *testing.T) {
for _, tc := range []struct {
chatID, thread int64
want string
}{
{123, 0, "123"},
{123, 7, "123/7"},
{-100, 42, "-100/42"},
} {
msg := &models.Message{Chat: models.Chat{ID: tc.chatID}, MessageThreadID: int(tc.thread)}
if got := conversationKey(msg); got != tc.want {
t.Errorf("conversationKey(%d, %d) = %q, want %q", tc.chatID, tc.thread, got, tc.want)
}
}
}
func TestInboundMessage(t *testing.T) {
msg := &models.Message{
ID: 42,
Chat: models.Chat{ID: -100},
MessageThreadID: 7,
From: &models.User{ID: 111, Username: "sam"},
Text: "hello",
Date: 1700000000,
}
m := inboundMessage(msg, "hello", nil)
if m.GetMessageId() != "42" || m.GetSourceId() != "42" {
t.Errorf("ids = %q/%q, want both 42", m.GetMessageId(), m.GetSourceId())
}
if m.GetChannelId() != "-100" || m.GetThreadId() != "7" {
t.Errorf("channel/thread = %q/%q", m.GetChannelId(), m.GetThreadId())
}
if m.GetFrom() != "sam" || m.GetSenderId() != "111" || m.GetPlatform() != "telegram" {
t.Errorf("from/sender/platform = %q/%q/%q", m.GetFrom(), m.GetSenderId(), m.GetPlatform())
}
if m.GetAt() == nil || m.GetAt().GetSeconds() != 1700000000 {
t.Errorf("at = %v", m.GetAt())
}
}
+149
View File
@@ -0,0 +1,149 @@
package main
import (
"context"
"fmt"
"io"
"net/http"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
gatewayv1 "github.com/samcharles93/archipelago/sdk/gateway/v1"
)
// attachment is one inbound file Telegram carries.
type attachment struct {
fileID, kind, mime, name, note string
}
// inboundAttachment maps a Telegram message's file onto an attachment. A
// message carries at most one file; a photo collapses to its largest size.
func inboundAttachment(msg *models.Message) (attachment, bool) {
switch {
case len(msg.Photo) > 0:
largest := msg.Photo[len(msg.Photo)-1]
for _, size := range msg.Photo {
if size.FileSize >= largest.FileSize {
largest = size
}
}
return attachment{fileID: largest.FileID, kind: "image", mime: "image/jpeg", note: "[photo]"}, true
case msg.Document != nil:
return attachment{
fileID: msg.Document.FileID, kind: "document", mime: msg.Document.MimeType,
name: msg.Document.FileName, note: "[document: " + msg.Document.FileName + "]",
}, true
case msg.Video != nil:
return attachment{fileID: msg.Video.FileID, kind: "video", mime: msg.Video.MimeType, note: "[video]"}, true
case msg.VideoNote != nil:
return attachment{fileID: msg.VideoNote.FileID, kind: "video", mime: "video/mp4", note: "[video message]"}, true
case msg.Voice != nil:
return attachment{fileID: msg.Voice.FileID, kind: "audio", mime: msg.Voice.MimeType, note: "[voice message]"}, true
case msg.Audio != nil:
return attachment{
fileID: msg.Audio.FileID, kind: "audio", mime: msg.Audio.MimeType,
name: msg.Audio.FileName, note: "[audio: " + msg.Audio.FileName + "]",
}, true
}
return attachment{}, false
}
// download fetches an attachment's bytes through the Bot API file link. The
// gateway process never holds the bot token, so the bytes ride on the inbound
// message.
func (g *gateway) download(ctx context.Context, fileID string) ([]byte, error) {
file, err := g.bot.GetFile(ctx, &bot.GetFileParams{FileID: fileID})
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, g.bot.FileDownloadLink(file), nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("telegram: download %s: %s", fileID, resp.Status)
}
return io.ReadAll(io.LimitReader(resp.Body, maxAttachmentBytes))
}
// maxAttachmentBytes bounds one inbound attachment.
const maxAttachmentBytes = 20 << 20
// sendMedia delivers an outbound media event: photos and documents by file id
// or url, anything else as a link.
func (g *gateway) sendMedia(ctx context.Context, chatID int64, threadID int, media *gatewayv1.Media) {
if media == nil {
return
}
var file any
switch {
case media.GetFileId() != "":
file = models.InputFileString{Data: media.GetFileId()}
case media.GetUrl() != "":
file = models.InputFileString{Data: media.GetUrl()}
}
send := func(err error) {
if err != nil {
g.log.WarnContext(ctx, "send media failed", "type", media.GetType(), "error", err)
}
}
switch media.GetType() {
case "image":
if file == nil {
g.sendText(ctx, chatID, threadID, media.GetUrl())
return
}
params := &bot.SendPhotoParams{ChatID: chatID, Photo: file.(models.InputFile)}
if threadID != 0 {
params.MessageThreadID = threadID
}
if media.GetFileName() != "" {
params.Caption = media.GetFileName()
}
_, err := g.bot.SendPhoto(ctx, params)
send(err)
case "video":
if file == nil {
g.sendText(ctx, chatID, threadID, media.GetUrl())
return
}
params := &bot.SendVideoParams{ChatID: chatID, Video: file.(models.InputFile)}
if threadID != 0 {
params.MessageThreadID = threadID
}
_, err := g.bot.SendVideo(ctx, params)
send(err)
case "audio":
if file == nil {
g.sendText(ctx, chatID, threadID, media.GetUrl())
return
}
params := &bot.SendAudioParams{ChatID: chatID, Audio: file.(models.InputFile)}
if threadID != 0 {
params.MessageThreadID = threadID
}
_, err := g.bot.SendAudio(ctx, params)
send(err)
default:
if file == nil {
if media.GetUrl() != "" {
g.sendText(ctx, chatID, threadID, media.GetUrl())
} else if media.GetPath() != "" {
g.sendText(ctx, chatID, threadID, media.GetPath())
}
return
}
params := &bot.SendDocumentParams{ChatID: chatID, Document: file.(models.InputFile)}
if threadID != 0 {
params.MessageThreadID = threadID
}
_, err := g.bot.SendDocument(ctx, params)
send(err)
}
}
+11
View File
@@ -0,0 +1,11 @@
apiVersion: dev.archie.package.v1
displayName: Telegram
description: "Telegram chat channel: long-polls the Bot API, routes messages from allowed user ids through the gateway, and replies in the chat. The bot token is a secret reference (token_ref) resolved by the host."
version: 1.0.0
contributes:
extensions:
- surface: channel
path: bin/telegram
files:
- path: bin/telegram
mode: 493
+257
View File
@@ -0,0 +1,257 @@
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]) + "…"
}
+1
View File
@@ -10,6 +10,7 @@ require (
github.com/emersion/go-msgauth v0.7.0
github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6
github.com/emersion/go-smtp v0.25.0
github.com/go-telegram/bot v1.27.0
github.com/gofri/go-github-ratelimit/v2 v2.0.2
github.com/google/go-github/v78 v78.0.0
github.com/hashicorp/go-plugin v1.8.0
+2
View File
@@ -36,6 +36,8 @@ github.com/go-fed/httpsig v1.1.0 h1:9M+hb0jkEICD8/cAiNqEB66R87tTINszBRTjwjQzWcI=
github.com/go-fed/httpsig v1.1.0/go.mod h1:RCMrTZvN1bJYtofsG4rd5NaO5obxQ5xBkdiS7xsT7bM=
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-telegram/bot v1.27.0 h1:PG9yBDzM8O26oUerE9SZwWlHon4RpH8WcNslZ7CEZmE=
github.com/go-telegram/bot v1.27.0/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM=
github.com/go-test/deep v1.1.1 h1:0r/53hagsehfO4bzD2Pgr/+RgHqhmf+k1Bpse2cTu1U=
github.com/go-test/deep v1.1.1/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
github.com/gofri/go-github-ratelimit/v2 v2.0.2 h1:gS8wAS1jTmlWGdTjAM7KIpsLjwY1S0S/gKK5hthfSXM=
+487 -276
View File
File diff suppressed because it is too large. Load diff
+382
View File
@@ -0,0 +1,382 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
// protoc (unknown)
// source: gateway/v1/task_tools.proto
package gatewayv1
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type ListTaskToolsRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
RunCredential string `protobuf:"bytes,1,opt,name=run_credential,json=runCredential,proto3" json:"run_credential,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ListTaskToolsRequest) Reset() {
*x = ListTaskToolsRequest{}
mi := &file_gateway_v1_task_tools_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ListTaskToolsRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ListTaskToolsRequest) ProtoMessage() {}
func (x *ListTaskToolsRequest) ProtoReflect() protoreflect.Message {
mi := &file_gateway_v1_task_tools_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ListTaskToolsRequest.ProtoReflect.Descriptor instead.
func (*ListTaskToolsRequest) Descriptor() ([]byte, []int) {
return file_gateway_v1_task_tools_proto_rawDescGZIP(), []int{0}
}
func (x *ListTaskToolsRequest) GetRunCredential() string {
if x != nil {
return x.RunCredential
}
return ""
}
type ListTaskToolsResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
ToolsJson []byte `protobuf:"bytes,1,opt,name=tools_json,json=toolsJson,proto3" json:"tools_json,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ListTaskToolsResponse) Reset() {
*x = ListTaskToolsResponse{}
mi := &file_gateway_v1_task_tools_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ListTaskToolsResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ListTaskToolsResponse) ProtoMessage() {}
func (x *ListTaskToolsResponse) ProtoReflect() protoreflect.Message {
mi := &file_gateway_v1_task_tools_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ListTaskToolsResponse.ProtoReflect.Descriptor instead.
func (*ListTaskToolsResponse) Descriptor() ([]byte, []int) {
return file_gateway_v1_task_tools_proto_rawDescGZIP(), []int{1}
}
func (x *ListTaskToolsResponse) GetToolsJson() []byte {
if x != nil {
return x.ToolsJson
}
return nil
}
type CallTaskToolRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
RunCredential string `protobuf:"bytes,1,opt,name=run_credential,json=runCredential,proto3" json:"run_credential,omitempty"`
Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
ArgumentsJson []byte `protobuf:"bytes,3,opt,name=arguments_json,json=argumentsJson,proto3" json:"arguments_json,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *CallTaskToolRequest) Reset() {
*x = CallTaskToolRequest{}
mi := &file_gateway_v1_task_tools_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *CallTaskToolRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CallTaskToolRequest) ProtoMessage() {}
func (x *CallTaskToolRequest) ProtoReflect() protoreflect.Message {
mi := &file_gateway_v1_task_tools_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CallTaskToolRequest.ProtoReflect.Descriptor instead.
func (*CallTaskToolRequest) Descriptor() ([]byte, []int) {
return file_gateway_v1_task_tools_proto_rawDescGZIP(), []int{2}
}
func (x *CallTaskToolRequest) GetRunCredential() string {
if x != nil {
return x.RunCredential
}
return ""
}
func (x *CallTaskToolRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *CallTaskToolRequest) GetArgumentsJson() []byte {
if x != nil {
return x.ArgumentsJson
}
return nil
}
type CallTaskToolResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
ResultJson []byte `protobuf:"bytes,1,opt,name=result_json,json=resultJson,proto3" json:"result_json,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *CallTaskToolResponse) Reset() {
*x = CallTaskToolResponse{}
mi := &file_gateway_v1_task_tools_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *CallTaskToolResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CallTaskToolResponse) ProtoMessage() {}
func (x *CallTaskToolResponse) ProtoReflect() protoreflect.Message {
mi := &file_gateway_v1_task_tools_proto_msgTypes[3]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CallTaskToolResponse.ProtoReflect.Descriptor instead.
func (*CallTaskToolResponse) Descriptor() ([]byte, []int) {
return file_gateway_v1_task_tools_proto_rawDescGZIP(), []int{3}
}
func (x *CallTaskToolResponse) GetResultJson() []byte {
if x != nil {
return x.ResultJson
}
return nil
}
type CloseTaskToolsRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
RunCredential string `protobuf:"bytes,1,opt,name=run_credential,json=runCredential,proto3" json:"run_credential,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *CloseTaskToolsRequest) Reset() {
*x = CloseTaskToolsRequest{}
mi := &file_gateway_v1_task_tools_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *CloseTaskToolsRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CloseTaskToolsRequest) ProtoMessage() {}
func (x *CloseTaskToolsRequest) ProtoReflect() protoreflect.Message {
mi := &file_gateway_v1_task_tools_proto_msgTypes[4]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CloseTaskToolsRequest.ProtoReflect.Descriptor instead.
func (*CloseTaskToolsRequest) Descriptor() ([]byte, []int) {
return file_gateway_v1_task_tools_proto_rawDescGZIP(), []int{4}
}
func (x *CloseTaskToolsRequest) GetRunCredential() string {
if x != nil {
return x.RunCredential
}
return ""
}
type CloseTaskToolsResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *CloseTaskToolsResponse) Reset() {
*x = CloseTaskToolsResponse{}
mi := &file_gateway_v1_task_tools_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *CloseTaskToolsResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CloseTaskToolsResponse) ProtoMessage() {}
func (x *CloseTaskToolsResponse) ProtoReflect() protoreflect.Message {
mi := &file_gateway_v1_task_tools_proto_msgTypes[5]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CloseTaskToolsResponse.ProtoReflect.Descriptor instead.
func (*CloseTaskToolsResponse) Descriptor() ([]byte, []int) {
return file_gateway_v1_task_tools_proto_rawDescGZIP(), []int{5}
}
var File_gateway_v1_task_tools_proto protoreflect.FileDescriptor
const file_gateway_v1_task_tools_proto_rawDesc = "" +
"\n" +
"\x1bgateway/v1/task_tools.proto\x12\n" +
"gateway.v1\"=\n" +
"\x14ListTaskToolsRequest\x12%\n" +
"\x0erun_credential\x18\x01 \x01(\tR\rrunCredential\"6\n" +
"\x15ListTaskToolsResponse\x12\x1d\n" +
"\n" +
"tools_json\x18\x01 \x01(\fR\ttoolsJson\"w\n" +
"\x13CallTaskToolRequest\x12%\n" +
"\x0erun_credential\x18\x01 \x01(\tR\rrunCredential\x12\x12\n" +
"\x04name\x18\x02 \x01(\tR\x04name\x12%\n" +
"\x0earguments_json\x18\x03 \x01(\fR\rargumentsJson\"7\n" +
"\x14CallTaskToolResponse\x12\x1f\n" +
"\vresult_json\x18\x01 \x01(\fR\n" +
"resultJson\">\n" +
"\x15CloseTaskToolsRequest\x12%\n" +
"\x0erun_credential\x18\x01 \x01(\tR\rrunCredential\"\x18\n" +
"\x16CloseTaskToolsResponse2\x94\x02\n" +
"\x10TaskToolsService\x12T\n" +
"\rListTaskTools\x12 .gateway.v1.ListTaskToolsRequest\x1a!.gateway.v1.ListTaskToolsResponse\x12Q\n" +
"\fCallTaskTool\x12\x1f.gateway.v1.CallTaskToolRequest\x1a .gateway.v1.CallTaskToolResponse\x12W\n" +
"\x0eCloseTaskTools\x12!.gateway.v1.CloseTaskToolsRequest\x1a\".gateway.v1.CloseTaskToolsResponseB\xa7\x01\n" +
"\x0ecom.gateway.v1B\x0eTaskToolsProtoP\x01Z<github.com/samcharles93/archipelago/sdk/gateway/v1;gatewayv1\xa2\x02\x03GXX\xaa\x02\n" +
"Gateway.V1\xca\x02\n" +
"Gateway\\V1\xe2\x02\x16Gateway\\V1\\GPBMetadata\xea\x02\vGateway::V1b\x06proto3"
var (
file_gateway_v1_task_tools_proto_rawDescOnce sync.Once
file_gateway_v1_task_tools_proto_rawDescData []byte
)
func file_gateway_v1_task_tools_proto_rawDescGZIP() []byte {
file_gateway_v1_task_tools_proto_rawDescOnce.Do(func() {
file_gateway_v1_task_tools_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_gateway_v1_task_tools_proto_rawDesc), len(file_gateway_v1_task_tools_proto_rawDesc)))
})
return file_gateway_v1_task_tools_proto_rawDescData
}
var file_gateway_v1_task_tools_proto_msgTypes = make([]protoimpl.MessageInfo, 6)
var file_gateway_v1_task_tools_proto_goTypes = []any{
(*ListTaskToolsRequest)(nil), // 0: gateway.v1.ListTaskToolsRequest
(*ListTaskToolsResponse)(nil), // 1: gateway.v1.ListTaskToolsResponse
(*CallTaskToolRequest)(nil), // 2: gateway.v1.CallTaskToolRequest
(*CallTaskToolResponse)(nil), // 3: gateway.v1.CallTaskToolResponse
(*CloseTaskToolsRequest)(nil), // 4: gateway.v1.CloseTaskToolsRequest
(*CloseTaskToolsResponse)(nil), // 5: gateway.v1.CloseTaskToolsResponse
}
var file_gateway_v1_task_tools_proto_depIdxs = []int32{
0, // 0: gateway.v1.TaskToolsService.ListTaskTools:input_type -> gateway.v1.ListTaskToolsRequest
2, // 1: gateway.v1.TaskToolsService.CallTaskTool:input_type -> gateway.v1.CallTaskToolRequest
4, // 2: gateway.v1.TaskToolsService.CloseTaskTools:input_type -> gateway.v1.CloseTaskToolsRequest
1, // 3: gateway.v1.TaskToolsService.ListTaskTools:output_type -> gateway.v1.ListTaskToolsResponse
3, // 4: gateway.v1.TaskToolsService.CallTaskTool:output_type -> gateway.v1.CallTaskToolResponse
5, // 5: gateway.v1.TaskToolsService.CloseTaskTools:output_type -> gateway.v1.CloseTaskToolsResponse
3, // [3:6] is the sub-list for method output_type
0, // [0:3] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_gateway_v1_task_tools_proto_init() }
func file_gateway_v1_task_tools_proto_init() {
if File_gateway_v1_task_tools_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_gateway_v1_task_tools_proto_rawDesc), len(file_gateway_v1_task_tools_proto_rawDesc)),
NumEnums: 0,
NumMessages: 6,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_gateway_v1_task_tools_proto_goTypes,
DependencyIndexes: file_gateway_v1_task_tools_proto_depIdxs,
MessageInfos: file_gateway_v1_task_tools_proto_msgTypes,
}.Build()
File_gateway_v1_task_tools_proto = out.File
file_gateway_v1_task_tools_proto_goTypes = nil
file_gateway_v1_task_tools_proto_depIdxs = nil
}
+203
View File
@@ -0,0 +1,203 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.2
// - protoc (unknown)
// source: gateway/v1/task_tools.proto
package gatewayv1
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
TaskToolsService_ListTaskTools_FullMethodName = "/gateway.v1.TaskToolsService/ListTaskTools"
TaskToolsService_CallTaskTool_FullMethodName = "/gateway.v1.TaskToolsService/CallTaskTool"
TaskToolsService_CloseTaskTools_FullMethodName = "/gateway.v1.TaskToolsService/CloseTaskTools"
)
// TaskToolsServiceClient is the client API for TaskToolsService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
//
// TaskToolsService executes central tools for a live task grant. Only the
// daemon calls it; identities, orgs and permissions are resolved by the server.
type TaskToolsServiceClient interface {
ListTaskTools(ctx context.Context, in *ListTaskToolsRequest, opts ...grpc.CallOption) (*ListTaskToolsResponse, error)
CallTaskTool(ctx context.Context, in *CallTaskToolRequest, opts ...grpc.CallOption) (*CallTaskToolResponse, error)
CloseTaskTools(ctx context.Context, in *CloseTaskToolsRequest, opts ...grpc.CallOption) (*CloseTaskToolsResponse, error)
}
type taskToolsServiceClient struct {
cc grpc.ClientConnInterface
}
func NewTaskToolsServiceClient(cc grpc.ClientConnInterface) TaskToolsServiceClient {
return &taskToolsServiceClient{cc}
}
func (c *taskToolsServiceClient) ListTaskTools(ctx context.Context, in *ListTaskToolsRequest, opts ...grpc.CallOption) (*ListTaskToolsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ListTaskToolsResponse)
err := c.cc.Invoke(ctx, TaskToolsService_ListTaskTools_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *taskToolsServiceClient) CallTaskTool(ctx context.Context, in *CallTaskToolRequest, opts ...grpc.CallOption) (*CallTaskToolResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CallTaskToolResponse)
err := c.cc.Invoke(ctx, TaskToolsService_CallTaskTool_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *taskToolsServiceClient) CloseTaskTools(ctx context.Context, in *CloseTaskToolsRequest, opts ...grpc.CallOption) (*CloseTaskToolsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CloseTaskToolsResponse)
err := c.cc.Invoke(ctx, TaskToolsService_CloseTaskTools_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// TaskToolsServiceServer is the server API for TaskToolsService service.
// All implementations must embed UnimplementedTaskToolsServiceServer
// for forward compatibility.
//
// TaskToolsService executes central tools for a live task grant. Only the
// daemon calls it; identities, orgs and permissions are resolved by the server.
type TaskToolsServiceServer interface {
ListTaskTools(context.Context, *ListTaskToolsRequest) (*ListTaskToolsResponse, error)
CallTaskTool(context.Context, *CallTaskToolRequest) (*CallTaskToolResponse, error)
CloseTaskTools(context.Context, *CloseTaskToolsRequest) (*CloseTaskToolsResponse, error)
mustEmbedUnimplementedTaskToolsServiceServer()
}
// UnimplementedTaskToolsServiceServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedTaskToolsServiceServer struct{}
func (UnimplementedTaskToolsServiceServer) ListTaskTools(context.Context, *ListTaskToolsRequest) (*ListTaskToolsResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ListTaskTools not implemented")
}
func (UnimplementedTaskToolsServiceServer) CallTaskTool(context.Context, *CallTaskToolRequest) (*CallTaskToolResponse, error) {
return nil, status.Error(codes.Unimplemented, "method CallTaskTool not implemented")
}
func (UnimplementedTaskToolsServiceServer) CloseTaskTools(context.Context, *CloseTaskToolsRequest) (*CloseTaskToolsResponse, error) {
return nil, status.Error(codes.Unimplemented, "method CloseTaskTools not implemented")
}
func (UnimplementedTaskToolsServiceServer) mustEmbedUnimplementedTaskToolsServiceServer() {}
func (UnimplementedTaskToolsServiceServer) testEmbeddedByValue() {}
// UnsafeTaskToolsServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to TaskToolsServiceServer will
// result in compilation errors.
type UnsafeTaskToolsServiceServer interface {
mustEmbedUnimplementedTaskToolsServiceServer()
}
func RegisterTaskToolsServiceServer(s grpc.ServiceRegistrar, srv TaskToolsServiceServer) {
// If the following call panics, it indicates UnimplementedTaskToolsServiceServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&TaskToolsService_ServiceDesc, srv)
}
func _TaskToolsService_ListTaskTools_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListTaskToolsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(TaskToolsServiceServer).ListTaskTools(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: TaskToolsService_ListTaskTools_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(TaskToolsServiceServer).ListTaskTools(ctx, req.(*ListTaskToolsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _TaskToolsService_CallTaskTool_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CallTaskToolRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(TaskToolsServiceServer).CallTaskTool(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: TaskToolsService_CallTaskTool_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(TaskToolsServiceServer).CallTaskTool(ctx, req.(*CallTaskToolRequest))
}
return interceptor(ctx, in, info, handler)
}
func _TaskToolsService_CloseTaskTools_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CloseTaskToolsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(TaskToolsServiceServer).CloseTaskTools(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: TaskToolsService_CloseTaskTools_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(TaskToolsServiceServer).CloseTaskTools(ctx, req.(*CloseTaskToolsRequest))
}
return interceptor(ctx, in, info, handler)
}
// TaskToolsService_ServiceDesc is the grpc.ServiceDesc for TaskToolsService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var TaskToolsService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "gateway.v1.TaskToolsService",
HandlerType: (*TaskToolsServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "ListTaskTools",
Handler: _TaskToolsService_ListTaskTools_Handler,
},
{
MethodName: "CallTaskTool",
Handler: _TaskToolsService_CallTaskTool_Handler,
},
{
MethodName: "CloseTaskTools",
Handler: _TaskToolsService_CloseTaskTools_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "gateway/v1/task_tools.proto",
}