-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
1131 lines (1008 loc) · 32.1 KB
/
Copy pathhandler.go
File metadata and controls
1131 lines (1008 loc) · 32.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package telegram
import (
"context"
"encoding/base64"
"fmt"
"io"
"log/slog"
"math"
"net/http"
"sort"
"strings"
"sync"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"telegram-agent/internal/agent"
"telegram-agent/internal/config"
"telegram-agent/internal/llm"
)
const (
maxMessageLen = 4096
requestTimeout = 5 * time.Minute
forwardTTL = 5 * time.Minute
forwardEmbedTimeout = 10 * time.Second
batchTimeout = 2 * time.Second
maxImagesPerBatch = 5
downloadTimeout = 30 * time.Second
maxInputLen = 50 * 1024 // 50 KB cap on incoming text
forwardFilterMinSize = 3 // only filter by relevance when more than this many forwards are buffered
forwardSelectThresh = 0.25 // min cosine similarity to include a buffered forward
maxConcurrentUpdates = 10 // limit concurrent goroutines processing updates
maxDocumentSize = 20 * 1024 * 1024 // 20 MB cap on document uploads
)
// supportedDocMIME lists MIME types accepted as inline documents for the LLM.
var supportedDocMIME = map[string]bool{
"application/pdf": true,
"text/plain": true,
"text/csv": true,
"text/html": true,
"text/markdown": true,
"application/json": true,
"application/xml": true,
}
func isSupportedDocument(mime string) bool {
return supportedDocMIME[mime]
}
// forwardEntry is a single forwarded message with its pre-computed embedding.
// text already includes the "[Forwarded from ...]" header prefix.
type forwardEntry struct {
text string
emb []float32
}
// forwardedContent holds buffered forwarded messages waiting for a user follow-up question.
type forwardedContent struct {
entries []forwardEntry
parts []llm.ContentPart
expiresAt time.Time
}
// pendingBatch accumulates messages for a single chat during the debounce window.
type pendingBatch struct {
msgs []*tgbotapi.Message
timer *time.Timer
version int // incremented on each new message to detect stale timer callbacks
}
type Handler struct {
bot *tgbotapi.BotAPI
agent *agent.Agent
allowed map[int64]bool
ownerID int64
logger *slog.Logger
forwardMu sync.Mutex
forwardBuf map[int64]*forwardedContent
batchMu sync.Mutex
batches map[int64]*pendingBatch
sem chan struct{} // concurrency limiter for handleUpdate goroutines
}
func NewHandler(cfg config.TelegramConfig, ag *agent.Agent, logger *slog.Logger) (*Handler, error) {
bot, err := tgbotapi.NewBotAPI(cfg.BotToken)
if err != nil {
return nil, fmt.Errorf("telegram init: %w", err)
}
allowed := make(map[int64]bool, len(cfg.AllowedChatIDs))
for _, id := range cfg.AllowedChatIDs {
allowed[id] = true
}
logger.Info("telegram bot authorized", "username", bot.Self.UserName)
if err := registerCommands(bot); err != nil {
logger.Warn("failed to register bot commands", "err", err)
}
return &Handler{
bot: bot,
agent: ag,
allowed: allowed,
ownerID: cfg.OwnerChatID,
logger: logger,
forwardBuf: make(map[int64]*forwardedContent),
batches: make(map[int64]*pendingBatch),
sem: make(chan struct{}, maxConcurrentUpdates),
}, nil
}
func (h *Handler) Start(ctx context.Context) {
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates := h.bot.GetUpdatesChan(u)
for {
select {
case <-ctx.Done():
h.bot.StopReceivingUpdates()
return
case update, ok := <-updates:
if !ok {
return
}
h.sem <- struct{}{} // acquire slot; blocks if maxConcurrentUpdates reached
go func() {
defer func() { <-h.sem }() // release slot
h.handleUpdate(update)
}()
}
}
}
func (h *Handler) handleUpdate(update tgbotapi.Update) {
if update.CallbackQuery != nil {
h.handleCallbackQuery(update.CallbackQuery)
return
}
if update.Message == nil {
return
}
msg := update.Message
if msg.From == nil {
return
}
chatID := msg.Chat.ID
if !h.allowed[chatID] || msg.From.ID != h.ownerID {
h.logger.Warn("unauthorized access attempt",
"chat_id", chatID,
"user_id", msg.From.ID,
"username", msg.From.UserName,
)
h.notifyOwner(msg)
return
}
// Commands bypass batching — they are interactive and must respond immediately.
if msg.IsCommand() {
h.handleCommand(msg)
return
}
h.queueMessage(msg)
}
// queueMessage adds a message to the per-chat debounce batch.
// The batch is flushed after batchTimeout of inactivity.
func (h *Handler) queueMessage(msg *tgbotapi.Message) {
chatID := msg.Chat.ID
h.batchMu.Lock()
b := h.batches[chatID]
if b == nil {
b = &pendingBatch{}
h.batches[chatID] = b
}
b.msgs = append(b.msgs, msg)
b.version++
ver := b.version
if b.timer != nil {
b.timer.Stop()
}
b.timer = time.AfterFunc(batchTimeout, func() {
h.processBatch(chatID, ver)
})
h.batchMu.Unlock()
}
// processBatch is called by the debounce timer. It verifies the version to
// avoid processing a batch that was superseded by a newer message.
func (h *Handler) processBatch(chatID int64, version int) {
h.batchMu.Lock()
b := h.batches[chatID]
if b == nil || b.version != version {
h.batchMu.Unlock()
return
}
delete(h.batches, chatID)
h.batchMu.Unlock()
h.runBatch(chatID, b)
}
// Drain flushes all pending batches synchronously. Call after stopping updates
// to avoid losing messages queued but not yet fired by their timers.
func (h *Handler) Drain() {
h.batchMu.Lock()
pending := h.batches
h.batches = make(map[int64]*pendingBatch)
h.batchMu.Unlock()
for chatID, b := range pending {
if b.timer != nil {
b.timer.Stop()
}
h.runBatch(chatID, b)
}
}
// runBatch merges all accumulated messages and sends them to the LLM as one request.
func (h *Handler) runBatch(chatID int64, b *pendingBatch) {
if b == nil || len(b.msgs) == 0 {
return
}
var forwardTexts []string // forwarded messages in this batch
var questionTexts []string // regular (non-forwarded) messages in this batch
var imageParts []llm.ContentPart
for _, msg := range b.msgs {
isForward := msg.ForwardDate != 0
text := msg.Text
if text == "" {
text = msg.Caption
}
text = appendTextLinks(text, msg.Entities, msg.CaptionEntities)
// Transcribe voice/audio messages to text.
if msg.Voice != nil || msg.Audio != nil {
voiceText := h.transcribeVoice(chatID, msg)
if voiceText != "" {
if text != "" {
text = text + "\n" + voiceText
} else {
text = voiceText
}
}
}
if isForward {
header := buildForwardHeader(msg)
entry := header
if text != "" {
entry = header + "\n" + text
}
forwardTexts = append(forwardTexts, entry)
} else {
// If this message is a reply, prepend the quoted original so the LLM has context.
if msg.ReplyToMessage != nil {
text = buildReplyQuote(msg.ReplyToMessage) + text
}
if text != "" {
questionTexts = append(questionTexts, text)
}
}
// Download photo from any message in the batch (forwarded or not)
if msg.Photo != nil && len(imageParts) < maxImagesPerBatch {
photo := msg.Photo[len(msg.Photo)-1]
data, err := h.downloadFile(photo.FileID)
if err != nil {
h.logger.Error("failed to download photo in batch", "err", err)
continue
}
imageParts = append(imageParts, llm.ContentPart{
Type: "image_url",
ImageURL: &llm.ImageURL{
URL: "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(data),
},
})
}
// Download documents (PDF, etc.) — native Gemini only
if msg.Document != nil && isSupportedDocument(msg.Document.MimeType) {
data, err := h.downloadFile(msg.Document.FileID)
if err != nil {
h.logger.Error("failed to download document", "err", err, "file", msg.Document.FileName)
continue
}
if len(data) > maxDocumentSize {
h.logger.Warn("document too large, skipping", "file", msg.Document.FileName, "size", len(data))
continue
}
h.logger.Info("document attached", "file", msg.Document.FileName, "mime", msg.Document.MimeType, "size", len(data))
imageParts = append(imageParts, llm.ContentPart{
Type: "inline_data",
InlineData: &llm.InlineData{
MIMEType: msg.Document.MimeType,
Data: base64.StdEncoding.EncodeToString(data),
},
})
}
}
// If only forwarded messages arrived (no regular user message), buffer and ack.
if len(questionTexts) == 0 {
h.bufferForwards(chatID, forwardTexts, imageParts)
return
}
// Consume any previously buffered forwards (slow follow-up path).
h.forwardMu.Lock()
fwd := h.forwardBuf[chatID]
if fwd != nil && time.Now().After(fwd.expiresAt) {
fwd = nil
}
delete(h.forwardBuf, chatID)
h.forwardMu.Unlock()
var allTextParts []string
if fwd != nil {
// Embed the user question to select only relevant buffered forwards.
questionText := strings.Join(questionTexts, "\n\n")
embedCtx, cancel := context.WithTimeout(context.Background(), forwardEmbedTimeout)
questionEmb, _ := h.agent.EmbedText(embedCtx, questionText)
cancel()
selected := selectForwards(fwd.entries, questionEmb)
allTextParts = append(allTextParts, selected...)
imageParts = append(fwd.parts, imageParts...)
}
allTextParts = append(allTextParts, forwardTexts...)
allTextParts = append(allTextParts, questionTexts...)
// Build the LLM message.
combined := strings.Join(allTextParts, "\n\n")
if len(combined) > maxInputLen {
combined = combined[:maxInputLen]
}
var userMsg llm.Message
if len(imageParts) > 0 {
if combined == "" {
combined = "What is in this image?"
}
parts := append([]llm.ContentPart{{Type: "text", Text: combined}}, imageParts...)
userMsg = llm.Message{Role: "user", Parts: parts}
} else {
if combined == "" {
return
}
userMsg = llm.Message{Role: "user", Content: combined}
}
h.executeMessage(chatID, userMsg)
}
// bufferForwards embeds each forwarded text and stores them in forwardBuf for
// later relevance-based filtering when the user's follow-up question arrives.
func (h *Handler) bufferForwards(chatID int64, texts []string, parts []llm.ContentPart) {
embedCtx, cancel := context.WithTimeout(context.Background(), forwardEmbedTimeout)
defer cancel()
entries := make([]forwardEntry, 0, len(texts))
for _, t := range texts {
emb, _ := h.agent.EmbedText(embedCtx, t)
entries = append(entries, forwardEntry{text: t, emb: emb})
}
h.forwardMu.Lock()
h.forwardBuf[chatID] = &forwardedContent{
entries: entries,
parts: parts,
expiresAt: time.Now().Add(forwardTTL),
}
h.forwardMu.Unlock()
h.sendPlain(chatID, "✓ Received. Add your question or comment.")
}
// selectForwards returns the texts from entries most relevant to questionEmb.
// Falls back to all entries when embeddings are unavailable or entry count is small.
func selectForwards(entries []forwardEntry, questionEmb []float32) []string {
if len(entries) == 0 {
return nil
}
// With few entries or no question embedding, include everything.
if len(questionEmb) == 0 || !forwardHasEmbs(entries) || len(entries) <= forwardFilterMinSize {
texts := make([]string, len(entries))
for i, e := range entries {
texts[i] = e.text
}
return texts
}
type scored struct {
idx int
score float64
}
scores := make([]scored, len(entries))
for i, e := range entries {
s := 0.0
if len(e.emb) > 0 {
s = forwardCosine(questionEmb, e.emb)
}
scores[i] = scored{idx: i, score: s}
}
// Sort descending by score to find relevant ones; always keep at least 2.
sort.Slice(scores, func(i, j int) bool { return scores[i].score > scores[j].score })
var selected []int
for i, s := range scores {
if s.score >= forwardSelectThresh || i < 2 {
selected = append(selected, s.idx)
}
}
// Restore original order.
sort.Ints(selected)
texts := make([]string, 0, len(selected))
for _, idx := range selected {
texts = append(texts, entries[idx].text)
}
return texts
}
func forwardHasEmbs(entries []forwardEntry) bool {
for _, e := range entries {
if len(e.emb) > 0 {
return true
}
}
return false
}
func forwardCosine(a, b []float32) float64 {
if len(a) != len(b) || len(a) == 0 {
return 0
}
var dot, normA, normB float64
for i := range a {
dot += float64(a[i]) * float64(b[i])
normA += float64(a[i]) * float64(a[i])
normB += float64(b[i]) * float64(b[i])
}
denom := math.Sqrt(normA) * math.Sqrt(normB)
if denom == 0 {
return 0
}
return dot / denom
}
const transcribeTimeout = 30 * time.Second
// transcribeVoice downloads a voice/audio message and transcribes it to text via the LLM.
func (h *Handler) transcribeVoice(chatID int64, msg *tgbotapi.Message) string {
var fileID string
if msg.Voice != nil {
fileID = msg.Voice.FileID
} else if msg.Audio != nil {
fileID = msg.Audio.FileID
}
if fileID == "" {
return ""
}
data, err := h.downloadFile(fileID)
if err != nil {
h.logger.Error("failed to download voice", "chat_id", chatID, "err", err)
return ""
}
ctx, cancel := context.WithTimeout(context.Background(), transcribeTimeout)
defer cancel()
text, err := h.agent.TranscribeAudio(ctx, data, "audio/ogg")
if err != nil {
h.logger.Error("transcription failed", "chat_id", chatID, "err", err)
return ""
}
h.logger.Info("voice transcribed", "chat_id", chatID, "text_len", len(text))
return text
}
// executeMessage sends a prepared LLM message and streams the response back to Telegram.
func (h *Handler) executeMessage(chatID int64, userMsg llm.Message) {
typingCtx, stopTyping := context.WithCancel(context.Background())
defer stopTyping()
go h.sendTypingLoop(chatID, typingCtx)
h.logger.Info("processing message", "chat_id", chatID, "has_parts", len(userMsg.Parts) > 0)
var toolsUsed []string
var statusMsgID int
onToolCall := func(toolName string) {
toolsUsed = append(toolsUsed, toolName)
text := "⚙️ " + strings.Join(toolsUsed, " → ")
if statusMsgID == 0 {
m, err := h.bot.Send(tgbotapi.NewMessage(chatID, text))
if err == nil {
statusMsgID = m.MessageID
}
} else {
edit := tgbotapi.NewEditMessageText(chatID, statusMsgID, text)
h.bot.Send(edit) //nolint:errcheck
}
}
reqCtx, cancelReq := context.WithTimeout(context.Background(), requestTimeout)
defer cancelReq()
response, err := h.agent.Process(reqCtx, chatID, userMsg, onToolCall)
stopTyping()
if statusMsgID != 0 {
h.bot.Request(tgbotapi.NewDeleteMessage(chatID, statusMsgID)) //nolint:errcheck
}
if err != nil {
h.logger.Error("agent error", "err", err)
h.sendPlain(chatID, "Error: "+err.Error())
return
}
if len(toolsUsed) > 0 {
response += "\n\n`⚙️ " + strings.Join(toolsUsed, " · ") + "`"
}
h.sendResponse(chatID, response)
}
// appendTextLinks appends hidden URLs from text_link entities to the message text.
// Plain URLs are already visible in the text and need no special handling.
func appendTextLinks(text string, entitySets ...[]tgbotapi.MessageEntity) string {
var links []string
seen := make(map[string]bool)
for _, entities := range entitySets {
for _, e := range entities {
if e.Type == "text_link" && e.URL != "" && !seen[e.URL] {
seen[e.URL] = true
links = append(links, e.URL)
}
}
}
if len(links) == 0 {
return text
}
return text + "\n" + strings.Join(links, "\n")
}
// buildReplyQuote formats the replied-to message as a quoted prefix so the LLM
// understands what the user is responding to.
func buildReplyQuote(reply *tgbotapi.Message) string {
text := reply.Text
if text == "" {
text = reply.Caption
}
if text == "" {
// replied to a photo/sticker/etc with no text
text = "[media]"
}
const maxQuoteLen = 300
if len([]rune(text)) > maxQuoteLen {
runes := []rune(text)
text = string(runes[:maxQuoteLen]) + "…"
}
sender := "bot"
if reply.From != nil && !reply.From.IsBot {
sender = "you"
}
return fmt.Sprintf("[Replying to %s: \"%s\"]\n", sender, text)
}
// buildForwardHeader builds a "[Forwarded from ...]" label from a forwarded message.
func buildForwardHeader(msg *tgbotapi.Message) string {
switch {
case msg.ForwardFrom != nil:
if msg.ForwardFrom.UserName != "" {
return fmt.Sprintf("[Forwarded from @%s]", msg.ForwardFrom.UserName)
}
return fmt.Sprintf("[Forwarded from %s %s]", msg.ForwardFrom.FirstName, msg.ForwardFrom.LastName)
case msg.ForwardFromChat != nil:
if msg.ForwardFromChat.UserName != "" {
return fmt.Sprintf("[Forwarded from @%s]", msg.ForwardFromChat.UserName)
}
return fmt.Sprintf("[Forwarded from %s]", msg.ForwardFromChat.Title)
default:
return "[Forwarded]"
}
}
func (h *Handler) handleCommand(msg *tgbotapi.Message) {
chatID := msg.Chat.ID
switch msg.Command() {
case "start":
h.send(chatID, fmt.Sprintf(
"Hi\\! I'm your personal AI assistant\\.\n\n"+
"Model: `%s`\n\n"+
"/clear — reset context\n"+
"/compact — compress history\n"+
"/model list — available models\n"+
"/tools — available tools\n"+
"/help — help",
h.agent.ModelName(),
))
case "help":
h.send(chatID, fmt.Sprintf(
"*Commands:*\n\n"+
"/clear — reset conversation context\n"+
"/compact — compress history \\(summarise\\)\n"+
"/stats — history size, model, last compact\n"+
"/model — show current model\n"+
"/model list — available models\n"+
"/model <name> — switch model\n"+
"/model reset — back to auto\\-routing\n"+
"/tools — list MCP tools\n"+
"/mcp update — reload MCP servers\n"+
"/help — this help\n\n"+
"*Model:* `%s`\n"+
"Responses longer than 4096 chars are sent as a `.md` file\\.",
h.agent.ModelName(),
))
case "clear":
h.agent.ClearHistory(chatID)
h.send(chatID, "Context cleared\\.")
case "compact":
h.sendPlain(chatID, "Compressing history...")
if err := h.agent.Compact(context.Background(), chatID); err != nil {
h.sendPlain(chatID, "Error: "+err.Error())
} else {
h.send(chatID, "History compressed\\.")
}
case "model":
arg := strings.TrimSpace(msg.CommandArguments())
switch arg {
case "":
override := h.agent.ModelOverride()
mode := override
if mode == "" {
mode = "auto"
}
h.send(chatID, fmt.Sprintf("Model: `%s` \\(override: %s\\)\n\n/model list — available models", h.agent.ModelName(), escapeMarkdown(mode)))
case "list":
names := h.agent.ListModels()
var sb strings.Builder
sb.WriteString("*Available models:*\n")
for _, n := range names {
sb.WriteString(" `" + escapeMarkdown(n) + "`\n")
}
sb.WriteString("\nUse `/model <name>` to switch\\.")
h.send(chatID, sb.String())
case "default", "reset":
h.agent.SetModel("") //nolint:errcheck
h.send(chatID, fmt.Sprintf("Model: `%s` \\(auto\\)", h.agent.ModelName()))
default:
if err := h.agent.SetModel(arg); err != nil {
names := h.agent.ListModels()
escaped := make([]string, len(names))
for i, n := range names {
escaped[i] = "`" + escapeMarkdown(n) + "`"
}
h.send(chatID, "Unknown model\\. Available: "+strings.Join(escaped, ", "))
} else {
h.send(chatID, fmt.Sprintf("Model: `%s`", escapeMarkdown(h.agent.ModelName())))
}
}
case "routing":
cfg := h.agent.GetRouting()
msg := tgbotapi.NewMessage(chatID, routingMenuText(cfg))
msg.ParseMode = tgbotapi.ModeMarkdownV2
msg.ReplyMarkup = routingMenuKeyboard(cfg)
h.bot.Send(msg) //nolint:errcheck
case "tools":
h.handleToolsCommand(chatID)
case "mcp":
h.handleMCPCommand(chatID, msg.CommandArguments())
case "stats":
h.handleStatsCommand(chatID)
default:
h.send(chatID, "Unknown command\\. /help for help\\.")
}
}
var downloadHTTPClient = &http.Client{Timeout: downloadTimeout}
func (h *Handler) downloadFile(fileID string) ([]byte, error) {
file, err := h.bot.GetFile(tgbotapi.FileConfig{FileID: fileID})
if err != nil {
return nil, err
}
url := file.Link(h.bot.Token)
resp, err := downloadHTTPClient.Get(url) //nolint:gosec
if err != nil {
return nil, err
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}
func (h *Handler) sendResponse(chatID int64, text string) {
if len(text) >= maxMessageLen {
h.sendAsFile(chatID, text)
return
}
htmlText := markdownToTelegramHTML(text)
msg := tgbotapi.NewMessage(chatID, htmlText)
msg.ParseMode = tgbotapi.ModeHTML
if _, err := h.bot.Send(msg); err != nil {
h.logger.Warn("html send failed, retrying as plain text", "err", err)
msg.ParseMode = ""
msg.Text = text
if _, err := h.bot.Send(msg); err != nil {
h.logger.Error("failed to send response", "chat_id", chatID, "err", err)
}
}
}
func (h *Handler) sendAsFile(chatID int64, text string) {
caption := text
if len(caption) > 200 {
caption = caption[:200] + "..."
}
doc := tgbotapi.NewDocument(chatID, tgbotapi.FileBytes{
Name: "response.md",
Bytes: []byte(text),
})
doc.Caption = caption
if _, err := h.bot.Send(doc); err != nil {
h.logger.Error("failed to send document", "err", err)
h.sendPlain(chatID, text[:maxMessageLen-50]+"...\n\n_(response truncated)_")
}
}
// send sends a bot-generated message with MarkdownV2 (text must be pre-escaped).
func (h *Handler) send(chatID int64, text string) {
msg := tgbotapi.NewMessage(chatID, text)
msg.ParseMode = tgbotapi.ModeMarkdownV2
if _, err := h.bot.Send(msg); err != nil {
h.logger.Error("failed to send message", "chat_id", chatID, "err", err)
}
}
// sendPlain sends a message without any markdown parsing.
func (h *Handler) sendPlain(chatID int64, text string) {
msg := tgbotapi.NewMessage(chatID, text)
if _, err := h.bot.Send(msg); err != nil {
h.logger.Error("failed to send plain message", "chat_id", chatID, "err", err)
}
}
func (h *Handler) sendTypingLoop(chatID int64, ctx context.Context) {
h.bot.Send(tgbotapi.NewChatAction(chatID, tgbotapi.ChatTyping)) //nolint:errcheck
ticker := time.NewTicker(4 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
h.bot.Send(tgbotapi.NewChatAction(chatID, tgbotapi.ChatTyping)) //nolint:errcheck
}
}
}
// --- Routing inline keyboard ---
func routingMenuText(cfg llm.RouterConfig) string {
classifierStatus := "off"
if cfg.ClassifierMinLen > 0 {
classifierStatus = fmt.Sprintf("min %d chars", cfg.ClassifierMinLen)
}
return fmt.Sprintf(
"⚙️ *Routing Configuration*\n\n"+
"Primary: `%s`\n"+
"Fallback: `%s`\n"+
"Reasoner: `%s`\n"+
"Classifier: `%s` \\(%s\\)\n"+
"Multimodal: `%s`",
escapeMarkdown(cfg.Primary),
escapeMarkdown(cfg.Fallback),
escapeMarkdown(cfg.Reasoner),
escapeMarkdown(cfg.Classifier),
classifierStatus,
escapeMarkdown(cfg.Multimodal),
)
}
func routingMenuKeyboard(cfg llm.RouterConfig) tgbotapi.InlineKeyboardMarkup {
return tgbotapi.NewInlineKeyboardMarkup(
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("✏️ Primary: "+cfg.Primary, "rt:role:primary"),
tgbotapi.NewInlineKeyboardButtonData("✏️ Fallback: "+cfg.Fallback, "rt:role:fallback"),
),
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("✏️ Reasoner: "+cfg.Reasoner, "rt:role:reasoner"),
tgbotapi.NewInlineKeyboardButtonData("✏️ Classifier: "+cfg.Classifier, "rt:role:classifier"),
),
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("✏️ Multimodal: "+cfg.Multimodal, "rt:role:multimodal"),
tgbotapi.NewInlineKeyboardButtonData("✏️ Classifier threshold", "rt:min"),
),
)
}
func roleMenuKeyboard(role, current string, models []string) tgbotapi.InlineKeyboardMarkup {
var rows [][]tgbotapi.InlineKeyboardButton
var row []tgbotapi.InlineKeyboardButton
for i, m := range models {
label := m
if m == current {
label = "✓ " + m
}
row = append(row, tgbotapi.NewInlineKeyboardButtonData(label, "rt:set:"+role+":"+m))
if len(row) == 2 || i == len(models)-1 {
rows = append(rows, row)
row = nil
}
}
rows = append(rows, tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("← Back", "rt:menu"),
))
return tgbotapi.NewInlineKeyboardMarkup(rows...)
}
func minLenMenuKeyboard(current int) tgbotapi.InlineKeyboardMarkup {
options := []int{0, 50, 100, 200, 500}
labels := []string{"Off (0)", "50", "100", "200", "500"}
var row []tgbotapi.InlineKeyboardButton
for i, v := range options {
label := labels[i]
if v == current {
label = "✓ " + label
}
row = append(row, tgbotapi.NewInlineKeyboardButtonData(label, fmt.Sprintf("rt:min:%d", v)))
}
return tgbotapi.NewInlineKeyboardMarkup(
row,
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("← Back", "rt:menu"),
),
)
}
func (h *Handler) handleCallbackQuery(q *tgbotapi.CallbackQuery) {
// Only owner can interact
if q.From == nil || q.From.ID != h.ownerID {
h.bot.Request(tgbotapi.NewCallback(q.ID, "Unauthorized")) //nolint:errcheck
return
}
h.bot.Request(tgbotapi.NewCallback(q.ID, "")) //nolint:errcheck
data := q.Data
chatID := q.Message.Chat.ID
msgID := q.Message.MessageID
editText := func(text string, kb tgbotapi.InlineKeyboardMarkup) {
edit := tgbotapi.NewEditMessageText(chatID, msgID, text)
edit.ParseMode = tgbotapi.ModeMarkdownV2
edit.ReplyMarkup = &kb
h.bot.Send(edit) //nolint:errcheck
}
switch {
case data == "rt:menu":
cfg := h.agent.GetRouting()
editText(routingMenuText(cfg), routingMenuKeyboard(cfg))
case strings.HasPrefix(data, "rt:role:"):
role := strings.TrimPrefix(data, "rt:role:")
cfg := h.agent.GetRouting()
current := roleValue(cfg, role)
models := h.agent.ListModels()
kb := roleMenuKeyboard(role, current, models)
edit := tgbotapi.NewEditMessageText(chatID, msgID,
fmt.Sprintf("⚙️ *Select model for* `%s`\\:", escapeMarkdown(role)))
edit.ParseMode = tgbotapi.ModeMarkdownV2
edit.ReplyMarkup = &kb
h.bot.Send(edit) //nolint:errcheck
case strings.HasPrefix(data, "rt:set:"):
// rt:set:<role>:<model>
rest := strings.TrimPrefix(data, "rt:set:")
idx := strings.Index(rest, ":")
if idx < 0 {
return
}
role, model := rest[:idx], rest[idx+1:]
h.logger.Info("routing change requested", "role", role, "model", model)
if err := h.agent.SetRoutingRole(role, model); err != nil {
h.logger.Warn("routing change failed", "role", role, "model", model, "err", err)
h.bot.Request(tgbotapi.NewCallback(q.ID, "Error: "+err.Error())) //nolint:errcheck
return
}
h.logger.Info("routing change applied", "role", role, "model", model)
cfg := h.agent.GetRouting()
editText(routingMenuText(cfg), routingMenuKeyboard(cfg))
case data == "rt:min":
cfg := h.agent.GetRouting()
edit := tgbotapi.NewEditMessageText(chatID, msgID,
"⚙️ *Classifier threshold*\n\nMinimum message length to run classifier \\(0 \\= disabled\\)\\:")
edit.ParseMode = tgbotapi.ModeMarkdownV2
kb := minLenMenuKeyboard(cfg.ClassifierMinLen)
edit.ReplyMarkup = &kb
h.bot.Send(edit) //nolint:errcheck
case strings.HasPrefix(data, "rt:min:"):
var n int
fmt.Sscanf(strings.TrimPrefix(data, "rt:min:"), "%d", &n)
h.agent.SetClassifierMinLen(n)
cfg := h.agent.GetRouting()
editText(routingMenuText(cfg), routingMenuKeyboard(cfg))
}
}
// NotifyMissingRouting sends a Telegram message to the owner for each routing role
// that references a provider not present in the providers map.
func (h *Handler) NotifyMissingRouting() {
if h.ownerID == 0 {
return
}
cfg := h.agent.GetRouting()
available := make(map[string]bool)
for _, m := range h.agent.ListModels() {
available[m] = true
}
roles := []struct{ name, model string }{
{"fallback", cfg.Fallback},
{"reasoner", cfg.Reasoner},
{"classifier", cfg.Classifier},
{"multimodal", cfg.Multimodal},
}
for _, r := range roles {
if r.model != "" && !available[r.model] {
text := fmt.Sprintf(
"⚠️ *Routing*: role `%s` — model `%s` is not available\\.\n\nSelect a replacement:",
escapeMarkdown(r.name), escapeMarkdown(r.model),
)
msg := tgbotapi.NewMessage(h.ownerID, text)
msg.ParseMode = tgbotapi.ModeMarkdownV2
kb := roleMenuKeyboard(r.name, "", h.agent.ListModels())
msg.ReplyMarkup = kb
h.bot.Send(msg) //nolint:errcheck
}
}
}
// roleValue returns the current model name for a given routing role.
func roleValue(cfg llm.RouterConfig, role string) string {
switch role {
case "primary":
return cfg.Primary
case "fallback":
return cfg.Fallback
case "reasoner":
return cfg.Reasoner
case "classifier":
return cfg.Classifier
case "multimodal":
return cfg.Multimodal
}
return ""
}
func registerCommands(bot *tgbotapi.BotAPI) error {
commands := []tgbotapi.BotCommand{
{Command: "clear", Description: "Reset conversation context"},
{Command: "compact", Description: "Compress history (summarise)"},
{Command: "model", Description: "Show / switch model"},
{Command: "routing", Description: "Configure routing (inline UI)"},
{Command: "tools", Description: "List connected MCP tools"},
{Command: "mcp", Description: "MCP management (update/reload)"},
{Command: "stats", Description: "Show history size, model, last compact"},
{Command: "help", Description: "Help"},
}