21 // telegramRetryDelay is the wait before the first retry of a failed
23 telegramRetryDelay = time.Second
25 // telegramRetryLimit is the longest wait between retries of a failed
27 telegramRetryLimit = time.Minute
29 // telegramAPIURL is the Telegram Bot API service.
30 telegramAPIURL = "https://api.telegram.org"
32 // telegramConfigFileName is the bot config in the data directory. The
33 // daemon runs the bot only when the file exists.
34 telegramConfigFileName = "telegram.json"
36 // telegramOffsetFileName is the update offset of the bot in the agent
38 telegramOffsetFileName = "telegram-offset.json"
40 // telegramSource is the source of the user messages from Telegram.
41 telegramSource = "telegram"
43 // telegramMessageUnits is the most UTF-16 code units of one Telegram
45 telegramMessageUnits = 4096
47 // telegramRichBytes is the most bytes of the Markdown of one rich
48 // message. The Bot API allows 32768 characters of rendered text, and
49 // the Markdown of a text has at least as many bytes as the text has
51 telegramRichBytes = 32768
53 // telegramTypingInterval is how often the bot shows the typing action
54 // while a turn runs. Telegram shows the action for about five seconds.
55 telegramTypingInterval = 4 * time.Second
57 // telegramTextOnly is the answer to a message that is not text.
58 telegramTextOnly = "Only text messages are supported."
61 // TelegramConfig holds the settings of telegram.json: the bot token and the
62 // user ID of the owner. The token is a secret, so the file must have mode 0600.
63 type TelegramConfig struct {
64 Token string `json:"token"`
65 Owner int64 `json:"owner"`
68 // TelegramBot connects the private chat of the owner with the agent. It polls
69 // the Bot API for new messages and sends owner text, images, and voice notes to
70 // the agent. It ignores every other update. Its sender sends the replies, the
71 // errors, the notices of the bot, and the user messages of the other clients to
72 // the chat, and shows the typing action while a turn runs. Only the replies
73 // have a format: their Markdown goes as rich messages, which Telegram renders
74 // itself, and as message entities only when Telegram refuses a rich message.
75 // The rest is plain text. Tool calls do not go to the chat.
77 // The offset file holds the ID of the next update. It moves past an update only
78 // after the message of the update is durable in the log, so a restart does not
79 // lose a message. A crash between the flush and the offset write makes Telegram
80 // send the update again, and the message repeats once.
82 // A failed Bot API call waits and tries again, from telegramRetryDelay up to
83 // telegramRetryLimit, or as long as the Bot API asks. It never stops the agent.
84 // A TelegramOutage logs the first failure and the end of each run of failures,
85 // and the retries between them log nothing.
86 type TelegramBot struct {
88 voice *VoiceTranscriber
98 // TelegramOutage is one run of failures of a kind of Bot API call. The first
99 // failure logs loss, its cause, and the wait of the next try. The retries log
100 // nothing. The next answer of Telegram logs back and the length of the outage.
101 // loss and back say what the user loses and gets again.
102 type TelegramOutage struct {
109 // TelegramPart is the text of one message to the chat, at most
110 // telegramMessageUnits long, and its entities.
111 type TelegramPart struct {
113 entities []TelegramEntity
116 // TelegramOffsetFile is the content of the offset file.
117 type TelegramOffsetFile struct {
118 Offset int64 `json:"offset"`
121 // loadTelegramConfig reads telegram.json in dir. It returns false when the file
122 // does not exist. An error never holds the token.
123 func loadTelegramConfig(dir string) (TelegramConfig, bool, error) {
124 path := filepath.Join(dir, telegramConfigFileName)
125 info, err := os.Stat(path)
126 if errors.Is(err, os.ErrNotExist) {
127 return TelegramConfig{}, false, nil
131 return TelegramConfig{}, false, fmt.Errorf("read bot config: %w", err)
134 if info.Mode().Perm()&0o077 != 0 {
135 return TelegramConfig{}, false, fmt.Errorf("%s holds the bot token, so its mode must be 0600", telegramConfigFileName)
138 data, err := os.ReadFile(path)
140 return TelegramConfig{}, false, fmt.Errorf("read bot config: %w", err)
143 var config TelegramConfig
145 decoder := json.NewDecoder(bytes.NewReader(data))
146 decoder.DisallowUnknownFields()
148 err = decoder.Decode(&config)
149 if err == nil && !errors.Is(decoder.Decode(&struct{}{}), io.EOF) {
150 err = errors.New("data after the JSON object")
154 return TelegramConfig{}, false, fmt.Errorf("%s is not valid JSON with the fields token and owner", telegramConfigFileName)
157 err = config.validate()
159 return TelegramConfig{}, false, fmt.Errorf("%s: %w", telegramConfigFileName, err)
162 return config, true, nil
165 // newTelegramBot returns the bot of owner on api. The offset file is at
166 // offsetPath, and logger gets the failures. No log line holds the text of a
168 func newTelegramBot(api *TelegramAPI, owner int64, offsetPath string, logger *slog.Logger) *TelegramBot {
171 voice: &VoiceTranscriber{},
173 offsetPath: offsetPath,
175 ready: make(chan struct{}, 1),
179 // validate makes sure that the token has the form of a bot token and that the
180 // owner is a user ID. The token goes into a URL path, so it can only hold the
181 // characters of a bot token.
182 func (c TelegramConfig) validate() error {
183 id, secret, found := strings.Cut(c.Token, ":")
184 if !found || id == "" || secret == "" || strings.Trim(id, "0123456789") != "" || strings.Trim(secret, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-") != "" {
185 return errors.New("token does not have the form of a bot token from BotFather")
189 return errors.New("owner must be the numeric Telegram user ID of the owner")
195 // Run polls for the messages of the owner and sends the queued events to the
196 // chat until ctx ends. It returns an error only when a message or the offset or
197 // image cannot be written, because then the bot would lose or repeat messages.
198 func (b *TelegramBot) Run(ctx context.Context, l *TurnLoop, whatsapp *WhatsApp) error {
199 ctx, cancel := context.WithCancel(ctx)
202 var sender sync.WaitGroup
212 err := b.poll(ctx, l, whatsapp)
220 // send sends each queued event to the chat in order until ctx ends. While a
221 // turn runs, it shows the typing action every telegramTypingInterval and after
222 // each message, because a message ends the action.
223 func (b *TelegramBot) send(ctx context.Context) {
224 ticker := time.NewTicker(telegramTypingInterval)
228 for ctx.Err() == nil {
229 event, found := b.next()
248 ticker.Reset(telegramTypingInterval)
261 // poll gets updates from the stored offset and handles them until ctx ends. A
262 // failed image download retries from the same offset. A submitted message is
263 // flushed even if ctx ends, and only then can the offset advance.
264 func (b *TelegramBot) poll(ctx context.Context, l *TurnLoop, whatsapp *WhatsApp) error {
265 offset, err := telegramLoadOffset(b.offsetPath)
267 return fmt.Errorf("load Telegram offset: %w", err)
270 outage := &TelegramOutage{
272 loss: "receive failed",
273 back: "receive back",
276 imageOutage := &TelegramOutage{
278 loss: "image receive failed",
279 back: "image receive back",
282 imageWait := telegramRetryDelay
283 wait := telegramRetryDelay
286 for ctx.Err() == nil {
287 updates, err := b.api.GetUpdates(ctx, offset)
288 if ctx.Err() != nil {
293 _, asked := telegramRetryable(err)
294 wait = b.pause(ctx, outage, err, wait, asked)
301 wait = telegramRetryDelay
303 for _, update := range updates {
304 if ctx.Err() != nil {
308 err = b.handle(ctx, l, whatsapp, update)
310 retry, asked := telegramRetryable(err)
312 imageWait = b.pause(ctx, imageOutage, err, imageWait, asked)
317 return fmt.Errorf("handle Telegram update: %w", err)
325 imageWait = telegramRetryDelay
327 offset = update.UpdateID + 1
328 err = telegramSaveOffset(b.offsetPath, offset)
330 return fmt.Errorf("save Telegram offset: %w", err)
338 // next removes the first queued event and returns it.
339 func (b *TelegramBot) next() (Event, bool) {
341 defer b.mutex.Unlock()
343 if len(b.queue) == 0 {
344 return Event{}, false
348 b.queue = b.queue[1:]
353 // typing shows the typing action once. A failure is not logged, because the
354 // next message or poll logs the state of the network.
355 func (b *TelegramBot) typing(ctx context.Context) {
356 // The next message or poll reports a network failure.
357 b.api.SendTyping(ctx, b.owner) // nolint: errcheck
360 // post sends event to the chat. A reply goes as rich messages of its Markdown,
361 // with each < and & outside code escaped by telegramEscapeTags and then split
362 // with telegramSplitRich, so that the length limit counts the escaped text.
363 // Every other event goes as plain text, split with telegramSplitMessage.
364 func (b *TelegramBot) post(ctx context.Context, event Event) {
365 if event.Kind != "reply" {
366 for _, text := range telegramSplitMessage(telegramText(event), telegramMessageUnits) {
367 b.deliver(ctx, TelegramPart{
375 for _, markdown := range telegramSplitRich(telegramEscapeTags(event.Text), telegramRichBytes) {
376 b.deliverRich(ctx, markdown)
380 // pause gives err to outage and waits the longer of wait and asked, or until
381 // ctx ends. It returns the wait of the next failure: twice wait, up to
382 // telegramRetryLimit.
383 func (b *TelegramBot) pause(ctx context.Context, outage *TelegramOutage, err error, wait, asked time.Duration) time.Duration {
384 delay := max(wait, asked)
385 outage.Fail(err, delay)
387 timer := time.NewTimer(delay)
395 return min(2*wait, telegramRetryLimit)
398 // handle runs one update. A text message of the owner in the private chat goes
399 // to the agent, and handle returns when it is durable in the log. The line
400 // /stop interrupts the turn, the line /stop NAME stops the subagent NAME, and a
401 // line that starts with /whatsapp runs a WhatsApp command on whatsapp, whose
402 // answers go to the chat only. Photos and image documents enter the shared
403 // image store with their caption. Voice notes keep their audio and local
404 // transcript. Other media keep the text-only answer. Every other update is
405 // ignored, and its content is not logged.
406 func (b *TelegramBot) handle(ctx context.Context, l *TurnLoop, whatsapp *WhatsApp, update TelegramUpdate) error {
407 message := update.Message
408 if message == nil || message.Chat.Type != "private" || message.Chat.ID != b.owner || message.From == nil || message.From.ID != b.owner {
409 b.logger.Info("message ignored: not from the owner")
414 name, stop := stopSubagentName(message.Text)
415 args, isWhatsApp := whatsappCommandArgs(message.Text)
417 case message.Voice != nil:
418 text := telegramVoiceText(ctx, b.api, l.agent.Voices(), b.voice, message)
419 _, err := l.Submit(telegramSource, text)
421 return fmt.Errorf("submit Telegram voice: %w", err)
424 err = l.Flush(context.WithoutCancel(ctx))
426 return fmt.Errorf("flush Telegram voice: %w", err)
428 case len(message.Photo) > 0 || message.Document != nil:
429 text, err := telegramImageText(ctx, b.api, l.agent.Images(), message)
431 retry, _ := telegramRetryable(err)
433 return fmt.Errorf("receive image: %w", err)
437 case errors.Is(err, errTelegramOtherMedia):
438 b.notice(telegramTextOnly)
439 case errors.Is(err, errImageSize), errors.Is(err, errImageFormat), errors.Is(err, errTelegramPhotoSize):
440 b.notice(err.Error())
442 var answer *TelegramError
444 if !errors.As(err, &answer) {
445 return fmt.Errorf("receive Telegram image: %w", err)
448 b.notice("Cannot download image.")
454 _, err = l.Submit(telegramSource, text)
456 return fmt.Errorf("submit Telegram image: %w", err)
459 err = l.Flush(context.WithoutCancel(ctx))
461 return fmt.Errorf("flush Telegram image: %w", err)
463 case message.Text == "":
464 b.notice(telegramTextOnly)
465 case strings.TrimSpace(message.Text) == stopCommand:
467 b.notice("No turn runs.")
470 found, err := l.StopSubagent(name)
472 return fmt.Errorf("stop subagent %s: %w", name, err)
476 b.notice("No subagent " + name + " runs.")
479 whatsapp.Command(args, b.notice)
481 _, err := l.Submit(telegramSource, message.Text)
483 return fmt.Errorf("submit Telegram text: %w", err)
486 err = l.Flush(context.WithoutCancel(ctx))
488 return fmt.Errorf("flush the message from Telegram: %w", err)
495 // deliver sends part to the chat. When Telegram refuses a part with entities
496 // (HTTP 400), it sends the text of the part again once with no entities, so a
497 // reply is not lost to a bad entity. It tries again after each failure that a
498 // later try can fix, until ctx ends. It drops the part after any other failure.
499 func (b *TelegramBot) deliver(ctx context.Context, part TelegramPart) {
500 outage := b.sendOutage()
501 wait := telegramRetryDelay
503 err := b.api.SendMessage(ctx, b.owner, part.text, part.entities)
504 retry, asked := telegramRetryable(err)
509 if err == nil || ctx.Err() != nil {
513 var answer *TelegramError
515 if len(part.entities) > 0 && errors.As(err, &answer) && answer.Status == http.StatusBadRequest {
516 b.logger.Warn("reply sent as plain text", "err", err)
524 b.logger.Error("reply lost", "err", err)
529 wait = b.pause(ctx, outage, err, wait, asked)
533 // deliverRich sends markdown, escaped with telegramEscapeTags, to the chat as a
534 // rich message. When the Bot API refuses it with HTTP 400 or 404, the message
535 // was not sent, so deliverRich sends the text of the part once with message
536 // entities, and the reply is not lost and does not repeat. Message entities
537 // read no HTML, so the fallback gets the Markdown of telegramUnescapeTags, as
538 // the model wrote it. It tries again after each failure that a later try can
539 // fix, until ctx ends. It drops the message after any other failure.
540 func (b *TelegramBot) deliverRich(ctx context.Context, markdown string) {
541 outage := b.sendOutage()
542 wait := telegramRetryDelay
544 err := b.api.SendRichMessage(ctx, b.owner, markdown)
545 retry, asked := telegramRetryable(err)
550 if err == nil || ctx.Err() != nil {
554 if telegramRejected(err) {
555 b.logger.Warn("reply sent with simple formatting", "err", err)
557 for _, part := range telegramReplyParts(telegramUnescapeTags(markdown)) {
565 b.logger.Error("reply lost", "err", err)
570 wait = b.pause(ctx, outage, err, wait, asked)
574 // notice queues a short answer of the bot for the chat.
575 func (b *TelegramBot) notice(text string) {
582 // sendOutage returns a new outage of the messages to the chat.
583 func (b *TelegramBot) sendOutage() *TelegramOutage {
584 return &TelegramOutage{
591 // Notify queues event for the chat. It never blocks, so a slow network does not
592 // stop the agent. The WhatsApp batches and the runs of the schedules do not go
593 // to the chat: the reply of the agent tells the user what needs the user.
594 func (b *TelegramBot) Notify(event Event) {
596 case "busy", "idle", "reply", "error", "notice", "subagent":
598 if event.Source == whatsappSource || event.Source == scheduleSource {
602 if event.Source == telegramSource {
611 b.queue = append(b.queue, event)
615 case b.ready <- struct{}{}:
620 // End logs the end of the outage that runs, with its length.
621 func (o *TelegramOutage) End() {
622 if o.start.IsZero() {
626 o.logger.Info(o.back, "after", time.Since(o.start))
628 o.start = time.Time{}
631 // Fail logs the start of an outage with err and delay, unless an outage runs.
632 func (o *TelegramOutage) Fail(err error, delay time.Duration) {
633 if !o.start.IsZero() {
638 o.logger.Warn(o.loss, "err", err, "retry", delay)
641 // telegramLoadOffset reads the update offset at path. A missing file gives 0,
642 // which asks for every update that Telegram keeps.
643 func telegramLoadOffset(path string) (int64, error) {
644 data, err := os.ReadFile(path)
645 if errors.Is(err, os.ErrNotExist) {
650 return 0, fmt.Errorf("read update offset: %w", err)
653 var file TelegramOffsetFile
655 err = json.Unmarshal(data, &file)
657 return 0, fmt.Errorf("%s: %w", path, err)
660 return file.Offset, nil
663 // telegramSaveOffset replaces the update offset at path.
664 func telegramSaveOffset(path string, offset int64) error {
665 data, err := json.Marshal(TelegramOffsetFile{
669 return fmt.Errorf("encode update offset: %w", err)
672 err = writeFileAtomic(path, append(data, '\n'))
674 return fmt.Errorf("write update offset: %w", err)
680 // telegramSplitMessage cuts text into parts of at most limit UTF-16 code units,
681 // the unit of the Telegram message limit. It cuts after the last line break or
682 // space of a part when one is in its second half, and else at the limit. It
683 // never cuts a character.
684 func telegramSplitMessage(text string, limit int) []string {
688 end := telegramPrefixEnd(text, limit)
689 if end == len(text) {
690 return append(parts, text)
693 cut := strings.LastIndexByte(text[:end], '\n') + 1
695 cut = strings.LastIndexByte(text[:end], ' ') + 1
702 parts = append(parts, text[:cut])
707 // telegramText returns the text of event for the chat. A user message of
708 // another client has its source as a mark. A subagent shows only its start and
709 // how its run ended, because the reply of the agent carries the content of the
711 func telegramText(event Event) string {
714 return "[" + event.Source + "] " + event.Text
716 return "[" + event.Text + "] started"
718 return "[" + event.Source + "] " + event.Status
720 return "Error: " + event.Text
726 // telegramSplitRich cuts the Markdown of a reply into parts of at most limit
727 // bytes. It cuts after a blank line outside a code block, so a table, a code
728 // block, or a paragraph stays whole. When no such cut fits in a part, it cuts
729 // after the last line break outside a code block, then after the last line
730 // break in a code block, which it closes at the end of the part and opens again
731 // in the next part with the same fence line. A line longer than limit is cut at
732 // the limit, or before an & in the four bytes before the limit, so that it does
733 // not cut an entity of telegramEscapeTags. It never cuts a character.
734 func telegramSplitRich(markdown string, limit int) []string {
737 for len(markdown) > limit {
738 cut, fence, opening := telegramRichCut(markdown, limit)
740 parts = append(parts, markdown[:cut])
741 markdown = markdown[cut:]
746 parts = append(parts, markdown[:cut]+fence+"\n")
747 markdown = opening + "\n" + markdown[cut:]
750 return append(parts, markdown)
753 // telegramReplyParts returns the messages of the Markdown of a reply with
754 // message entities. A reply that has no text left after the conversion, such as
755 // an empty code block, goes as its Markdown.
756 func telegramReplyParts(markdown string) []TelegramPart {
757 text, entities := telegramMarkdownEntities(markdown)
758 if strings.TrimSpace(text) == "" {
759 text, entities = markdown, nil
762 return telegramSplitEntities(text, entities, telegramMessageUnits)
765 // telegramPrefixEnd returns the byte length of the longest prefix of text with
766 // at most limit UTF-16 code units.
767 func telegramPrefixEnd(text string, limit int) int {
769 for index, char := range text {
775 if units+size > limit {
785 // telegramRichCut returns where telegramSplitRich cuts markdown, which is
786 // longer than limit. For a cut in a code block, it also returns the fence that
787 // closes the block and the line that opens it. Each part before a cut holds
788 // text other than space, and a cut in a code block leaves room for the fence,
789 // so each cut makes the rest shorter.
790 func telegramRichCut(markdown string, limit int) (int, string, string) {
791 blank, line, code := 0, 0, 0
793 var fence, opening, inFence, inOpening string
795 for start := 0; start < limit; {
796 end := strings.IndexByte(markdown[start:], '\n')
797 if end < 0 || start+end+1 > limit {
802 text := strings.TrimRight(markdown[start:end], "\r\n")
803 _, opens := markdownCodeFence(text)
806 if markdownClosesFence(text, fence) {
808 } else if end > len(opening)+1 && end+len(fence)+1 <= limit {
809 code, inFence, inOpening = end, fence, opening
812 fence, opening = opens, text
813 case strings.TrimSpace(markdown[:end]) == "":
814 case strings.TrimSpace(text) == "":
818 if fence == "" && strings.TrimSpace(markdown[:end]) != "" {
831 return code, inFence, inOpening
835 for !utf8.RuneStart(markdown[cut]) {
839 start := max(cut-len("&")+1, 0)
840 entity := strings.LastIndexByte(markdown[start:cut], '&')
841 if entity >= 0 && start+entity > 0 {
848 // telegramSplitEntities cuts text into parts with telegramSplitMessage, and
849 // gives each part the entities in it, with offsets from the start of the part.
850 // An entity that crosses a cut becomes one entity in each part.
851 func telegramSplitEntities(text string, entities []TelegramEntity, limit int) []TelegramPart {
852 var parts []TelegramPart
855 for _, part := range telegramSplitMessage(text, limit) {
856 end := start + telegramUTF16Units(part)
858 var kept []TelegramEntity
860 for _, entity := range entities {
861 from := max(entity.Offset, start)
862 to := min(entity.Offset+entity.Length, end)
867 entity.Offset = from - start
868 entity.Length = to - from
869 kept = append(kept, entity)
872 parts = append(parts, TelegramPart{