]> git.giacomolli.uk - onechat/blob - telegram.go
Give each subagent its own prompt cache key
[onechat] / telegram.go
1 package main
2
3 import (
4         "bytes"
5         "context"
6         "encoding/json"
7         "errors"
8         "fmt"
9         "io"
10         "log"
11         "net/http"
12         "os"
13         "path/filepath"
14         "strings"
15         "sync"
16         "time"
17         "unicode/utf8"
18 )
19
20 const (
21         // telegramAPIURL is the Telegram Bot API service.
22         telegramAPIURL = "https://api.telegram.org"
23
24         // telegramConfigFileName is the bot config in the data directory. The
25         // daemon runs the bot only when the file exists.
26         telegramConfigFileName = "telegram.json"
27
28         // telegramOffsetFileName is the update offset of the bot in the agent
29         // directory.
30         telegramOffsetFileName = "telegram-offset.json"
31
32         // telegramSource is the source of the user messages from Telegram.
33         telegramSource = "telegram"
34
35         // telegramMessageUnits is the most UTF-16 code units of one Telegram
36         // message.
37         telegramMessageUnits = 4096
38
39         // telegramRichBytes is the most bytes of the Markdown of one rich
40         // message. The Bot API allows 32768 characters of rendered text, and
41         // the Markdown of a text has at least as many bytes as the text has
42         // characters.
43         telegramRichBytes = 32768
44
45         // telegramTypingInterval is how often the bot shows the typing action
46         // while a turn runs. Telegram shows the action for about five seconds.
47         telegramTypingInterval = 4 * time.Second
48
49         // telegramTextOnly is the answer to a message that is not text.
50         telegramTextOnly = "Only text messages are supported."
51 )
52
53 // loadTelegramConfig reads telegram.json in dir. It returns false when the file
54 // does not exist. An error never holds the token.
55 func loadTelegramConfig(dir string) (TelegramConfig, bool, error) {
56         path := filepath.Join(dir, telegramConfigFileName)
57         info, err := os.Stat(path)
58         if errors.Is(err, os.ErrNotExist) {
59                 return TelegramConfig{}, false, nil
60         }
61
62         if err != nil {
63                 return TelegramConfig{}, false, fmt.Errorf("read bot config: %w", err)
64         }
65
66         if info.Mode().Perm()&0o077 != 0 {
67                 return TelegramConfig{}, false, fmt.Errorf("%s holds the bot token, so its mode must be 0600", telegramConfigFileName)
68         }
69
70         data, err := os.ReadFile(path)
71         if err != nil {
72                 return TelegramConfig{}, false, fmt.Errorf("read bot config: %w", err)
73         }
74
75         var config TelegramConfig
76         decoder := json.NewDecoder(bytes.NewReader(data))
77         decoder.DisallowUnknownFields()
78         err = decoder.Decode(&config)
79         if err == nil && !errors.Is(decoder.Decode(&struct{}{}), io.EOF) {
80                 err = errors.New("data after the JSON object")
81         }
82
83         if err != nil {
84                 return TelegramConfig{}, false, fmt.Errorf("%s is not valid JSON with the fields token and owner", telegramConfigFileName)
85         }
86
87         err = config.validate()
88         if err != nil {
89                 return TelegramConfig{}, false, fmt.Errorf("%s: %w", telegramConfigFileName, err)
90         }
91
92         return config, true, nil
93 }
94
95 // newTelegramBot returns the bot of owner on api. The offset file is at
96 // offsetPath, and logger gets the failures. No log line holds the text of a
97 // message.
98 func newTelegramBot(api *TelegramAPI, owner int64, offsetPath string, logger *log.Logger) *TelegramBot {
99         return &TelegramBot{
100                 api:        api,
101                 owner:      owner,
102                 offsetPath: offsetPath,
103                 logger:     logger,
104                 minWait:    time.Second,
105                 maxWait:    time.Minute,
106                 ready:      make(chan struct{}, 1),
107         }
108 }
109
110 // TelegramConfig holds the settings of telegram.json: the bot token and the
111 // user ID of the owner. The token is a secret, so the file must have mode 0600.
112 type TelegramConfig struct {
113         Token string `json:"token"`
114         Owner int64  `json:"owner"`
115 }
116
117 // validate makes sure that the token has the form of a bot token and that the
118 // owner is a user ID. The token goes into a URL path, so it can only hold the
119 // characters of a bot token.
120 func (c TelegramConfig) validate() error {
121         id, secret, found := strings.Cut(c.Token, ":")
122         if !found || id == "" || secret == "" || strings.Trim(id, "0123456789") != "" || strings.Trim(secret, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-") != "" {
123                 return errors.New("token does not have the form of a bot token from BotFather")
124         }
125
126         if c.Owner <= 0 {
127                 return errors.New("owner must be the numeric Telegram user ID of the owner")
128         }
129
130         return nil
131 }
132
133 // TelegramBot connects the private chat of the owner with the agent. It polls
134 // the Bot API for new messages and sends each text message of the owner to the
135 // agent. It ignores every other update. Its sender sends the replies, the
136 // errors, the notices of the bot, and the user messages of the other clients to
137 // the chat, and shows the typing action while a turn runs. Only the replies
138 // have a format: their Markdown goes as rich messages, which Telegram renders
139 // itself, and as message entities only when Telegram refuses a rich message.
140 // The rest is plain text. Tool calls do not go to the chat.
141 //
142 // The offset file holds the ID of the next update. It moves past an update
143 // only after the message of the update is durable in the log, so a restart
144 // does not lose a message. A crash between the flush and the offset write
145 // makes Telegram send the update again, and the message repeats once.
146 //
147 // A failed Bot API call waits and tries again, from minWait up to maxWait, or
148 // as long as the Bot API asks. It never stops the agent.
149 type TelegramBot struct {
150         api        *TelegramAPI
151         owner      int64
152         offsetPath string
153         logger     *log.Logger
154         minWait    time.Duration
155         maxWait    time.Duration
156
157         mutex sync.Mutex
158         queue []Event
159         ready chan struct{}
160 }
161
162 // Notify queues event for the chat. It never blocks, so a slow network does not
163 // stop the agent.
164 func (b *TelegramBot) Notify(event Event) {
165         switch event.Kind {
166         case "busy", "idle", "reply", "error", "notice", "subagent", "work":
167         case "user":
168                 if event.Source == telegramSource {
169                         return
170                 }
171         default:
172                 return
173         }
174
175         b.mutex.Lock()
176         b.queue = append(b.queue, event)
177         b.mutex.Unlock()
178
179         select {
180         case b.ready <- struct{}{}:
181         default:
182         }
183 }
184
185 // Run polls for the messages of the owner and sends the queued events to the
186 // chat until ctx ends. It returns an error only when a message or the offset
187 // cannot be written, because then the bot would lose or repeat messages.
188 func (b *TelegramBot) Run(ctx context.Context, l *TurnLoop) error {
189         ctx, cancel := context.WithCancel(ctx)
190         defer cancel()
191
192         var sender sync.WaitGroup
193         sender.Add(1)
194         go func() {
195                 defer sender.Done()
196
197                 b.send(ctx)
198         }()
199
200         err := b.poll(ctx, l)
201         cancel()
202         sender.Wait()
203
204         return err
205 }
206
207 // send sends each queued event to the chat in order until ctx ends. While a
208 // turn runs, it shows the typing action every telegramTypingInterval and after
209 // each message, because a message ends the action.
210 func (b *TelegramBot) send(ctx context.Context) {
211         ticker := time.NewTicker(telegramTypingInterval)
212         defer ticker.Stop()
213
214         busy := false
215         for ctx.Err() == nil {
216                 event, found := b.next()
217                 if !found {
218                         select {
219                         case <-b.ready:
220                         case <-ticker.C:
221                                 if busy {
222                                         b.typing(ctx)
223                                 }
224                         case <-ctx.Done():
225                         }
226
227                         continue
228                 }
229
230                 switch event.Kind {
231                 case "busy":
232                         busy = true
233                         b.typing(ctx)
234                         ticker.Reset(telegramTypingInterval)
235                 case "idle":
236                         busy = false
237                 default:
238                         b.post(ctx, event)
239
240                         if busy {
241                                 b.typing(ctx)
242                         }
243                 }
244         }
245 }
246
247 // poll gets the updates from the stored offset on and handles each one, until
248 // ctx ends. Each update is handled to its end also when ctx ends during it, so
249 // a stop does not repeat its message.
250 func (b *TelegramBot) poll(ctx context.Context, l *TurnLoop) error {
251         offset, err := telegramLoadOffset(b.offsetPath)
252         if err != nil {
253                 return err
254         }
255
256         wait := b.minWait
257         for ctx.Err() == nil {
258                 updates, err := b.api.GetUpdates(ctx, offset)
259                 if ctx.Err() != nil {
260                         return nil
261                 }
262
263                 if err != nil {
264                         _, asked := telegramRetryable(err)
265                         wait = b.pause(ctx, err, wait, asked)
266
267                         continue
268                 }
269
270                 wait = b.minWait
271                 for _, update := range updates {
272                         if ctx.Err() != nil {
273                                 return nil
274                         }
275
276                         err = b.handle(context.WithoutCancel(ctx), l, update)
277                         if err != nil {
278                                 return err
279                         }
280
281                         offset = update.UpdateID + 1
282                         err = telegramSaveOffset(b.offsetPath, offset)
283                         if err != nil {
284                                 return err
285                         }
286                 }
287         }
288
289         return nil
290 }
291
292 // next removes the first queued event and returns it.
293 func (b *TelegramBot) next() (Event, bool) {
294         b.mutex.Lock()
295         defer b.mutex.Unlock()
296
297         if len(b.queue) == 0 {
298                 return Event{}, false
299         }
300
301         event := b.queue[0]
302         b.queue = b.queue[1:]
303
304         return event, true
305 }
306
307 // typing shows the typing action once. A failure is not logged, because the
308 // next message or poll logs the state of the network.
309 func (b *TelegramBot) typing(ctx context.Context) {
310         _ = b.api.SendTyping(ctx, b.owner)
311 }
312
313 // post sends event to the chat. A reply goes as rich messages of its Markdown,
314 // with each < and & outside code escaped by telegramEscapeTags and then split
315 // with telegramSplitRich, so that the length limit counts the escaped text.
316 // Every other event goes as plain text, split with telegramSplitMessage.
317 func (b *TelegramBot) post(ctx context.Context, event Event) {
318         if event.Kind != "reply" {
319                 for _, text := range telegramSplitMessage(telegramText(event), telegramMessageUnits) {
320                         b.deliver(ctx, TelegramPart{
321                                 text: text,
322                         })
323                 }
324
325                 return
326         }
327
328         for _, markdown := range telegramSplitRich(telegramEscapeTags(event.Text), telegramRichBytes) {
329                 b.deliverRich(ctx, markdown)
330         }
331 }
332
333 // pause logs err and waits the longer of wait and asked, or until ctx ends. It
334 // returns the wait of the next failure: twice wait, up to maxWait.
335 func (b *TelegramBot) pause(ctx context.Context, err error, wait, asked time.Duration) time.Duration {
336         delay := max(wait, asked)
337         b.logger.Printf("%v (next try in %s)", err, delay)
338
339         timer := time.NewTimer(delay)
340         defer timer.Stop()
341
342         select {
343         case <-timer.C:
344         case <-ctx.Done():
345         }
346
347         return min(2*wait, b.maxWait)
348 }
349
350 // handle runs one update. A text message of the owner in the private chat goes
351 // to the agent, and handle returns when it is durable in the log. The line
352 // /stop interrupts the turn, and the line /stop NAME stops the subagent NAME.
353 // Any other message of the owner gets the answer that only text is supported.
354 // Every other update is ignored, and its content is not logged.
355 func (b *TelegramBot) handle(ctx context.Context, l *TurnLoop, update TelegramUpdate) error {
356         message := update.Message
357         if message == nil || message.Chat.Type != "private" || message.Chat.ID != b.owner || message.From == nil || message.From.ID != b.owner {
358                 b.logger.Print("update ignored: not a message of the owner in the private chat")
359                 return nil
360         }
361
362         name, stop := stopSubagentName(message.Text)
363         switch {
364         case message.Text == "":
365                 b.notice(telegramTextOnly)
366         case strings.TrimSpace(message.Text) == stopCommand:
367                 if !l.Interrupt() {
368                         b.notice("No turn runs.")
369                 }
370         case stop:
371                 found, err := l.StopSubagent(name)
372                 if err != nil {
373                         return fmt.Errorf("stop subagent %s: %w", name, err)
374                 }
375
376                 if !found {
377                         b.notice("No subagent " + name + " runs.")
378                 }
379         default:
380                 _, err := l.Submit(telegramSource, message.Text)
381                 if err != nil {
382                         return err
383                 }
384
385                 err = l.Flush(ctx)
386                 if err != nil {
387                         return fmt.Errorf("flush the message from Telegram: %w", err)
388                 }
389         }
390
391         return nil
392 }
393
394 // deliver sends part to the chat. When Telegram refuses a part with entities
395 // (HTTP 400), it sends the text of the part again once with no entities, so a
396 // reply is not lost to a bad entity. It tries again after each failure that a
397 // later try can fix, until ctx ends. It drops the part after any other failure.
398 func (b *TelegramBot) deliver(ctx context.Context, part TelegramPart) {
399         wait := b.minWait
400         for {
401                 err := b.api.SendMessage(ctx, b.owner, part.text, part.entities)
402                 if err == nil || ctx.Err() != nil {
403                         return
404                 }
405
406                 var answer *TelegramError
407                 if len(part.entities) > 0 && errors.As(err, &answer) && answer.Status == http.StatusBadRequest {
408                         b.logger.Printf("entities refused, the message goes again as plain text: %v", err)
409                         part.entities = nil
410
411                         continue
412                 }
413
414                 retry, asked := telegramRetryable(err)
415                 if !retry {
416                         b.logger.Printf("message dropped: %v", err)
417                         return
418                 }
419
420                 wait = b.pause(ctx, err, wait, asked)
421         }
422 }
423
424 // deliverRich sends markdown, escaped with telegramEscapeTags, to the chat as a
425 // rich message. When the Bot API refuses it with HTTP 400 or 404, the message
426 // was not sent, so deliverRich sends the text of the part once with message
427 // entities, and the reply is not lost and does not repeat. Message entities
428 // read no HTML, so the fallback gets the Markdown of telegramUnescapeTags, as
429 // the model wrote it. It tries again after each failure that a later try can
430 // fix, until ctx ends. It drops the message after any other failure.
431 func (b *TelegramBot) deliverRich(ctx context.Context, markdown string) {
432         wait := b.minWait
433         for {
434                 err := b.api.SendRichMessage(ctx, b.owner, markdown)
435                 if err == nil || ctx.Err() != nil {
436                         return
437                 }
438
439                 if telegramRejected(err) {
440                         b.logger.Printf("rich message refused, the reply goes with entities: %v", err)
441                         for _, part := range telegramReplyParts(telegramUnescapeTags(markdown)) {
442                                 b.deliver(ctx, part)
443                         }
444
445                         return
446                 }
447
448                 retry, asked := telegramRetryable(err)
449                 if !retry {
450                         b.logger.Printf("message dropped: %v", err)
451                         return
452                 }
453
454                 wait = b.pause(ctx, err, wait, asked)
455         }
456 }
457
458 // notice queues a short answer of the bot for the chat.
459 func (b *TelegramBot) notice(text string) {
460         b.Notify(Event{
461                 Kind: "notice",
462                 Text: text,
463         })
464 }
465
466 // TelegramPart is the text of one message to the chat, at most
467 // telegramMessageUnits long, and its entities.
468 type TelegramPart struct {
469         text     string
470         entities []TelegramEntity
471 }
472
473 // TelegramOffsetFile is the content of the offset file.
474 type TelegramOffsetFile struct {
475         Offset int64 `json:"offset"`
476 }
477
478 // telegramLoadOffset reads the update offset at path. A missing file gives 0,
479 // which asks for every update that Telegram keeps.
480 func telegramLoadOffset(path string) (int64, error) {
481         data, err := os.ReadFile(path)
482         if errors.Is(err, os.ErrNotExist) {
483                 return 0, nil
484         }
485
486         if err != nil {
487                 return 0, fmt.Errorf("read update offset: %w", err)
488         }
489
490         var file TelegramOffsetFile
491         err = json.Unmarshal(data, &file)
492         if err != nil {
493                 return 0, fmt.Errorf("%s: %w", path, err)
494         }
495
496         return file.Offset, nil
497 }
498
499 // telegramSaveOffset replaces the update offset at path.
500 func telegramSaveOffset(path string, offset int64) error {
501         data, err := json.Marshal(TelegramOffsetFile{
502                 Offset: offset,
503         })
504         if err != nil {
505                 return fmt.Errorf("encode update offset: %w", err)
506         }
507
508         err = writeFileAtomic(path, append(data, '\n'))
509         if err != nil {
510                 return fmt.Errorf("write update offset: %w", err)
511         }
512
513         return nil
514 }
515
516 // telegramSplitMessage cuts text into parts of at most limit UTF-16 code units,
517 // the unit of the Telegram message limit. It cuts after the last line break or
518 // space of a part when one is in its second half, and else at the limit. It
519 // never cuts a character.
520 func telegramSplitMessage(text string, limit int) []string {
521         var parts []string
522         for {
523                 end := telegramPrefixEnd(text, limit)
524                 if end == len(text) {
525                         return append(parts, text)
526                 }
527
528                 cut := strings.LastIndexByte(text[:end], '\n') + 1
529                 if cut <= end/2 {
530                         cut = strings.LastIndexByte(text[:end], ' ') + 1
531                 }
532
533                 if cut <= end/2 {
534                         cut = end
535                 }
536
537                 parts = append(parts, text[:cut])
538                 text = text[cut:]
539         }
540 }
541
542 // telegramText returns the text of event for the chat. A user message of
543 // another client has its source as a mark. A subagent shows only its start and
544 // how its run ended, because the reply of the agent carries the content of the
545 // report.
546 func telegramText(event Event) string {
547         switch event.Kind {
548         case "user":
549                 return "[" + event.Source + "] " + event.Text
550         case "subagent":
551                 return "[" + event.Text + "] started"
552         case "work":
553                 return "[" + event.Source + "] " + event.Status
554         case "error":
555                 return "Error: " + event.Text
556         default:
557                 return event.Text
558         }
559 }
560
561 // telegramSplitRich cuts the Markdown of a reply into parts of at most limit
562 // bytes. It cuts after a blank line outside a code block, so a table, a code
563 // block, or a paragraph stays whole. When no such cut fits in a part, it cuts
564 // after the last line break outside a code block, then after the last line
565 // break in a code block, which it closes at the end of the part and opens again
566 // in the next part with the same fence line. A line longer than limit is cut at
567 // the limit, or before an & in the four bytes before the limit, so that it does
568 // not cut an entity of telegramEscapeTags. It never cuts a character.
569 func telegramSplitRich(markdown string, limit int) []string {
570         var parts []string
571         for len(markdown) > limit {
572                 cut, fence, opening := telegramRichCut(markdown, limit)
573                 if fence == "" {
574                         parts = append(parts, markdown[:cut])
575                         markdown = markdown[cut:]
576
577                         continue
578                 }
579
580                 parts = append(parts, markdown[:cut]+fence+"\n")
581                 markdown = opening + "\n" + markdown[cut:]
582         }
583
584         return append(parts, markdown)
585 }
586
587 // telegramReplyParts returns the messages of the Markdown of a reply with
588 // message entities. A reply that has no text left after the conversion, such as
589 // an empty code block, goes as its Markdown.
590 func telegramReplyParts(markdown string) []TelegramPart {
591         text, entities := telegramMarkdownEntities(markdown)
592         if strings.TrimSpace(text) == "" {
593                 text, entities = markdown, nil
594         }
595
596         return telegramSplitEntities(text, entities, telegramMessageUnits)
597 }
598
599 // telegramPrefixEnd returns the byte length of the longest prefix of text with
600 // at most limit UTF-16 code units.
601 func telegramPrefixEnd(text string, limit int) int {
602         units := 0
603         for index, char := range text {
604                 size := 1
605                 if char > 0xFFFF {
606                         size = 2
607                 }
608
609                 if units+size > limit {
610                         return index
611                 }
612
613                 units += size
614         }
615
616         return len(text)
617 }
618
619 // telegramRichCut returns where telegramSplitRich cuts markdown, which is
620 // longer than limit. For a cut in a code block, it also returns the fence that
621 // closes the block and the line that opens it. Each part before a cut holds
622 // text other than space, and a cut in a code block leaves room for the fence,
623 // so each cut makes the rest shorter.
624 func telegramRichCut(markdown string, limit int) (int, string, string) {
625         blank, line, code := 0, 0, 0
626         var fence, opening, inFence, inOpening string
627         for start := 0; start < limit; {
628                 end := strings.IndexByte(markdown[start:], '\n')
629                 if end < 0 || start+end+1 > limit {
630                         break
631                 }
632
633                 end += start + 1
634                 text := strings.TrimRight(markdown[start:end], "\r\n")
635                 _, opens := telegramCodeFence(text)
636                 switch {
637                 case fence != "":
638                         if telegramClosesFence(text, fence) {
639                                 fence = ""
640                         } else if end > len(opening)+1 && end+len(fence)+1 <= limit {
641                                 code, inFence, inOpening = end, fence, opening
642                         }
643                 case opens != "":
644                         fence, opening = opens, text
645                 case strings.TrimSpace(markdown[:end]) == "":
646                 case strings.TrimSpace(text) == "":
647                         blank = end
648                 }
649
650                 if fence == "" && strings.TrimSpace(markdown[:end]) != "" {
651                         line = end
652                 }
653
654                 start = end
655         }
656
657         switch {
658         case blank > 0:
659                 return blank, "", ""
660         case line > 0:
661                 return line, "", ""
662         case code > 0:
663                 return code, inFence, inOpening
664         }
665
666         cut := limit
667         for !utf8.RuneStart(markdown[cut]) {
668                 cut--
669         }
670
671         start := max(cut-len("&amp;")+1, 0)
672         entity := strings.LastIndexByte(markdown[start:cut], '&')
673         if entity >= 0 && start+entity > 0 {
674                 cut = start + entity
675         }
676
677         return cut, "", ""
678 }
679
680 // telegramSplitEntities cuts text into parts with telegramSplitMessage, and
681 // gives each part the entities in it, with offsets from the start of the part.
682 // An entity that crosses a cut becomes one entity in each part.
683 func telegramSplitEntities(text string, entities []TelegramEntity, limit int) []TelegramPart {
684         var parts []TelegramPart
685         start := 0
686         for _, part := range telegramSplitMessage(text, limit) {
687                 end := start + telegramUTF16Units(part)
688                 var kept []TelegramEntity
689                 for _, entity := range entities {
690                         from := max(entity.Offset, start)
691                         to := min(entity.Offset+entity.Length, end)
692                         if to <= from {
693                                 continue
694                         }
695
696                         entity.Offset = from - start
697                         entity.Length = to - from
698                         kept = append(kept, entity)
699                 }
700
701                 parts = append(parts, TelegramPart{
702                         text:     part,
703                         entities: kept,
704                 })
705
706                 start = end
707         }
708
709         return parts
710 }