21 // telegramAPIURL is the Telegram Bot API service.
22 telegramAPIURL = "https://api.telegram.org"
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"
28 // telegramOffsetFileName is the update offset of the bot in the agent
30 telegramOffsetFileName = "telegram-offset.json"
32 // telegramSource is the source of the user messages from Telegram.
33 telegramSource = "telegram"
35 // telegramMessageUnits is the most UTF-16 code units of one Telegram
37 telegramMessageUnits = 4096
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
43 telegramRichBytes = 32768
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
49 // telegramTextOnly is the answer to a message that is not text.
50 telegramTextOnly = "Only text messages are supported."
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
63 return TelegramConfig{}, false, fmt.Errorf("read bot config: %w", err)
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)
70 data, err := os.ReadFile(path)
72 return TelegramConfig{}, false, fmt.Errorf("read bot config: %w", err)
75 var config TelegramConfig
77 decoder := json.NewDecoder(bytes.NewReader(data))
78 decoder.DisallowUnknownFields()
80 err = decoder.Decode(&config)
81 if err == nil && !errors.Is(decoder.Decode(&struct{}{}), io.EOF) {
82 err = errors.New("data after the JSON object")
86 return TelegramConfig{}, false, fmt.Errorf("%s is not valid JSON with the fields token and owner", telegramConfigFileName)
89 err = config.validate()
91 return TelegramConfig{}, false, fmt.Errorf("%s: %w", telegramConfigFileName, err)
94 return config, true, nil
97 // newTelegramBot returns the bot of owner on api. The offset file is at
98 // offsetPath, and logger gets the failures. No log line holds the text of a
100 func newTelegramBot(api *TelegramAPI, owner int64, offsetPath string, logger *slog.Logger) *TelegramBot {
104 offsetPath: offsetPath,
106 minWait: time.Second,
107 maxWait: time.Minute,
108 ready: make(chan struct{}, 1),
112 // TelegramConfig holds the settings of telegram.json: the bot token and the
113 // user ID of the owner. The token is a secret, so the file must have mode 0600.
114 type TelegramConfig struct {
115 Token string `json:"token"`
116 Owner int64 `json:"owner"`
119 // validate makes sure that the token has the form of a bot token and that the
120 // owner is a user ID. The token goes into a URL path, so it can only hold the
121 // characters of a bot token.
122 func (c TelegramConfig) validate() error {
123 id, secret, found := strings.Cut(c.Token, ":")
124 if !found || id == "" || secret == "" || strings.Trim(id, "0123456789") != "" || strings.Trim(secret, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-") != "" {
125 return errors.New("token does not have the form of a bot token from BotFather")
129 return errors.New("owner must be the numeric Telegram user ID of the owner")
135 // TelegramBot connects the private chat of the owner with the agent. It polls
136 // the Bot API for new messages and sends owner text and images to the agent. It
137 // ignores every other update. Its sender sends the replies, the errors, the
138 // notices of the bot, and the user messages of the other clients to the chat,
139 // and shows the typing action while a turn runs. Only the replies have a
140 // format: their Markdown goes as rich messages, which Telegram renders itself,
141 // and as message entities only when Telegram refuses a rich message. The rest
142 // is plain text. Tool calls do not go to the chat.
144 // The offset file holds the ID of the next update. It moves past an update
145 // only after the message of the update is durable in the log, so a restart
146 // does not lose a message. A crash between the flush and the offset write
147 // makes Telegram send the update again, and the message repeats once.
149 // A failed Bot API call waits and tries again, from minWait up to maxWait, or
150 // as long as the Bot API asks. It never stops the agent. A TelegramOutage logs
151 // the first failure and the end of each run of failures, and the retries
152 // between them log nothing.
153 type TelegramBot struct {
158 minWait time.Duration
159 maxWait time.Duration
166 // Notify queues event for the chat. It never blocks, so a slow network does not
167 // stop the agent. The WhatsApp batches and the runs of the schedules do not go
168 // to the chat: the reply of the agent tells the user what needs the user.
169 func (b *TelegramBot) Notify(event Event) {
171 case "busy", "idle", "reply", "error", "notice", "subagent":
173 if event.Source == whatsappSource || event.Source == scheduleSource {
177 if event.Source == telegramSource {
186 b.queue = append(b.queue, event)
190 case b.ready <- struct{}{}:
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)
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 := b.minWait
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)
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)
321 imageWait = b.minWait
323 offset = update.UpdateID + 1
324 err = telegramSaveOffset(b.offsetPath, offset)
334 // next removes the first queued event and returns it.
335 func (b *TelegramBot) next() (Event, bool) {
337 defer b.mutex.Unlock()
339 if len(b.queue) == 0 {
340 return Event{}, false
344 b.queue = b.queue[1:]
349 // typing shows the typing action once. A failure is not logged, because the
350 // next message or poll logs the state of the network.
351 func (b *TelegramBot) typing(ctx context.Context) {
352 _ = b.api.SendTyping(ctx, b.owner)
355 // post sends event to the chat. A reply goes as rich messages of its Markdown,
356 // with each < and & outside code escaped by telegramEscapeTags and then split
357 // with telegramSplitRich, so that the length limit counts the escaped text.
358 // Every other event goes as plain text, split with telegramSplitMessage.
359 func (b *TelegramBot) post(ctx context.Context, event Event) {
360 if event.Kind != "reply" {
361 for _, text := range telegramSplitMessage(telegramText(event), telegramMessageUnits) {
362 b.deliver(ctx, TelegramPart{
370 for _, markdown := range telegramSplitRich(telegramEscapeTags(event.Text), telegramRichBytes) {
371 b.deliverRich(ctx, markdown)
375 // pause gives err to outage and waits the longer of wait and asked, or until
376 // ctx ends. It returns the wait of the next failure: twice wait, up to maxWait.
377 func (b *TelegramBot) pause(ctx context.Context, outage *TelegramOutage, err error, wait, asked time.Duration) time.Duration {
378 delay := max(wait, asked)
379 outage.Fail(err, delay)
381 timer := time.NewTimer(delay)
389 return min(2*wait, b.maxWait)
392 // handle runs one update. A text message of the owner in the private chat goes
393 // to the agent, and handle returns when it is durable in the log. The line
394 // /stop interrupts the turn, the line /stop NAME stops the subagent NAME, and a
395 // line that starts with /whatsapp runs a WhatsApp command on whatsapp, whose
396 // answers go to the chat only. Photos and image documents enter the shared
397 // image store with their caption. Other media keep the text-only answer. Every
398 // other update is ignored, and its content is not logged.
399 func (b *TelegramBot) handle(ctx context.Context, l *TurnLoop, whatsapp *WhatsApp, update TelegramUpdate) error {
400 message := update.Message
401 if message == nil || message.Chat.Type != "private" || message.Chat.ID != b.owner || message.From == nil || message.From.ID != b.owner {
402 b.logger.Info("message ignored: not from the owner")
407 name, stop := stopSubagentName(message.Text)
408 args, isWhatsApp := whatsappCommandArgs(message.Text)
410 case len(message.Photo) > 0 || message.Document != nil:
411 text, err := telegramImageText(ctx, b.api, l.agent.Images(), message)
413 retry, _ := telegramRetryable(err)
415 return fmt.Errorf("receive image: %w", err)
419 case errors.Is(err, errTelegramOtherMedia):
420 b.notice(telegramTextOnly)
421 case errors.Is(err, errImageSize), errors.Is(err, errImageFormat), errors.Is(err, errTelegramPhotoSize):
422 b.notice(err.Error())
424 var answer *TelegramError
426 if !errors.As(err, &answer) {
427 return fmt.Errorf("receive Telegram image: %w", err)
430 b.notice("Cannot download image.")
436 _, err = l.Submit(telegramSource, text)
438 return fmt.Errorf("submit Telegram image: %w", err)
441 err = l.Flush(context.WithoutCancel(ctx))
443 return fmt.Errorf("flush Telegram image: %w", err)
445 case message.Text == "":
446 b.notice(telegramTextOnly)
447 case strings.TrimSpace(message.Text) == stopCommand:
449 b.notice("No turn runs.")
452 found, err := l.StopSubagent(name)
454 return fmt.Errorf("stop subagent %s: %w", name, err)
458 b.notice("No subagent " + name + " runs.")
461 whatsapp.Command(args, b.notice)
463 _, err := l.Submit(telegramSource, message.Text)
468 err = l.Flush(context.WithoutCancel(ctx))
470 return fmt.Errorf("flush the message from Telegram: %w", err)
477 // deliver sends part to the chat. When Telegram refuses a part with entities
478 // (HTTP 400), it sends the text of the part again once with no entities, so a
479 // reply is not lost to a bad entity. It tries again after each failure that a
480 // later try can fix, until ctx ends. It drops the part after any other failure.
481 func (b *TelegramBot) deliver(ctx context.Context, part TelegramPart) {
482 outage := b.sendOutage()
485 err := b.api.SendMessage(ctx, b.owner, part.text, part.entities)
486 retry, asked := telegramRetryable(err)
491 if err == nil || ctx.Err() != nil {
495 var answer *TelegramError
497 if len(part.entities) > 0 && errors.As(err, &answer) && answer.Status == http.StatusBadRequest {
498 b.logger.Warn("reply sent as plain text", "err", err)
506 b.logger.Error("reply lost", "err", err)
511 wait = b.pause(ctx, outage, err, wait, asked)
515 // deliverRich sends markdown, escaped with telegramEscapeTags, to the chat as a
516 // rich message. When the Bot API refuses it with HTTP 400 or 404, the message
517 // was not sent, so deliverRich sends the text of the part once with message
518 // entities, and the reply is not lost and does not repeat. Message entities
519 // read no HTML, so the fallback gets the Markdown of telegramUnescapeTags, as
520 // the model wrote it. It tries again after each failure that a later try can
521 // fix, until ctx ends. It drops the message after any other failure.
522 func (b *TelegramBot) deliverRich(ctx context.Context, markdown string) {
523 outage := b.sendOutage()
526 err := b.api.SendRichMessage(ctx, b.owner, markdown)
527 retry, asked := telegramRetryable(err)
532 if err == nil || ctx.Err() != nil {
536 if telegramRejected(err) {
537 b.logger.Warn("reply sent with simple formatting", "err", err)
539 for _, part := range telegramReplyParts(telegramUnescapeTags(markdown)) {
547 b.logger.Error("reply lost", "err", err)
552 wait = b.pause(ctx, outage, err, wait, asked)
556 // sendOutage returns a new outage of the messages to the chat.
557 func (b *TelegramBot) sendOutage() *TelegramOutage {
558 return &TelegramOutage{
565 // notice queues a short answer of the bot for the chat.
566 func (b *TelegramBot) notice(text string) {
573 // TelegramOutage is one run of failures of a kind of Bot API call. The first
574 // failure logs loss, its cause, and the wait of the next try. The retries log
575 // nothing. The next answer of Telegram logs back and the length of the outage.
576 // loss and back say what the user loses and gets again.
577 type TelegramOutage struct {
584 // Fail logs the start of an outage with err and delay, unless an outage runs.
585 func (o *TelegramOutage) Fail(err error, delay time.Duration) {
586 if !o.start.IsZero() {
591 o.logger.Warn(o.loss, "err", err, "retry", delay)
594 // End logs the end of the outage that runs, with its length.
595 func (o *TelegramOutage) End() {
596 if o.start.IsZero() {
600 o.logger.Info(o.back, "after", time.Since(o.start))
602 o.start = time.Time{}
605 // TelegramPart is the text of one message to the chat, at most
606 // telegramMessageUnits long, and its entities.
607 type TelegramPart struct {
609 entities []TelegramEntity
612 // TelegramOffsetFile is the content of the offset file.
613 type TelegramOffsetFile struct {
614 Offset int64 `json:"offset"`
617 // telegramLoadOffset reads the update offset at path. A missing file gives 0,
618 // which asks for every update that Telegram keeps.
619 func telegramLoadOffset(path string) (int64, error) {
620 data, err := os.ReadFile(path)
621 if errors.Is(err, os.ErrNotExist) {
626 return 0, fmt.Errorf("read update offset: %w", err)
629 var file TelegramOffsetFile
631 err = json.Unmarshal(data, &file)
633 return 0, fmt.Errorf("%s: %w", path, err)
636 return file.Offset, nil
639 // telegramSaveOffset replaces the update offset at path.
640 func telegramSaveOffset(path string, offset int64) error {
641 data, err := json.Marshal(TelegramOffsetFile{
645 return fmt.Errorf("encode update offset: %w", err)
648 err = writeFileAtomic(path, append(data, '\n'))
650 return fmt.Errorf("write update offset: %w", err)
656 // telegramSplitMessage cuts text into parts of at most limit UTF-16 code units,
657 // the unit of the Telegram message limit. It cuts after the last line break or
658 // space of a part when one is in its second half, and else at the limit. It
659 // never cuts a character.
660 func telegramSplitMessage(text string, limit int) []string {
664 end := telegramPrefixEnd(text, limit)
665 if end == len(text) {
666 return append(parts, text)
669 cut := strings.LastIndexByte(text[:end], '\n') + 1
671 cut = strings.LastIndexByte(text[:end], ' ') + 1
678 parts = append(parts, text[:cut])
683 // telegramText returns the text of event for the chat. A user message of
684 // another client has its source as a mark. A subagent shows only its start and
685 // how its run ended, because the reply of the agent carries the content of the
687 func telegramText(event Event) string {
690 return "[" + event.Source + "] " + event.Text
692 return "[" + event.Text + "] started"
694 return "[" + event.Source + "] " + event.Status
696 return "Error: " + event.Text
702 // telegramSplitRich cuts the Markdown of a reply into parts of at most limit
703 // bytes. It cuts after a blank line outside a code block, so a table, a code
704 // block, or a paragraph stays whole. When no such cut fits in a part, it cuts
705 // after the last line break outside a code block, then after the last line
706 // break in a code block, which it closes at the end of the part and opens again
707 // in the next part with the same fence line. A line longer than limit is cut at
708 // the limit, or before an & in the four bytes before the limit, so that it does
709 // not cut an entity of telegramEscapeTags. It never cuts a character.
710 func telegramSplitRich(markdown string, limit int) []string {
713 for len(markdown) > limit {
714 cut, fence, opening := telegramRichCut(markdown, limit)
716 parts = append(parts, markdown[:cut])
717 markdown = markdown[cut:]
722 parts = append(parts, markdown[:cut]+fence+"\n")
723 markdown = opening + "\n" + markdown[cut:]
726 return append(parts, markdown)
729 // telegramReplyParts returns the messages of the Markdown of a reply with
730 // message entities. A reply that has no text left after the conversion, such as
731 // an empty code block, goes as its Markdown.
732 func telegramReplyParts(markdown string) []TelegramPart {
733 text, entities := telegramMarkdownEntities(markdown)
734 if strings.TrimSpace(text) == "" {
735 text, entities = markdown, nil
738 return telegramSplitEntities(text, entities, telegramMessageUnits)
741 // telegramPrefixEnd returns the byte length of the longest prefix of text with
742 // at most limit UTF-16 code units.
743 func telegramPrefixEnd(text string, limit int) int {
745 for index, char := range text {
751 if units+size > limit {
761 // telegramRichCut returns where telegramSplitRich cuts markdown, which is
762 // longer than limit. For a cut in a code block, it also returns the fence that
763 // closes the block and the line that opens it. Each part before a cut holds
764 // text other than space, and a cut in a code block leaves room for the fence,
765 // so each cut makes the rest shorter.
766 func telegramRichCut(markdown string, limit int) (int, string, string) {
767 blank, line, code := 0, 0, 0
769 var fence, opening, inFence, inOpening string
771 for start := 0; start < limit; {
772 end := strings.IndexByte(markdown[start:], '\n')
773 if end < 0 || start+end+1 > limit {
778 text := strings.TrimRight(markdown[start:end], "\r\n")
779 _, opens := markdownCodeFence(text)
782 if markdownClosesFence(text, fence) {
784 } else if end > len(opening)+1 && end+len(fence)+1 <= limit {
785 code, inFence, inOpening = end, fence, opening
788 fence, opening = opens, text
789 case strings.TrimSpace(markdown[:end]) == "":
790 case strings.TrimSpace(text) == "":
794 if fence == "" && strings.TrimSpace(markdown[:end]) != "" {
807 return code, inFence, inOpening
811 for !utf8.RuneStart(markdown[cut]) {
815 start := max(cut-len("&")+1, 0)
816 entity := strings.LastIndexByte(markdown[start:cut], '&')
817 if entity >= 0 && start+entity > 0 {
824 // telegramSplitEntities cuts text into parts with telegramSplitMessage, and
825 // gives each part the entities in it, with offsets from the start of the part.
826 // An entity that crosses a cut becomes one entity in each part.
827 func telegramSplitEntities(text string, entities []TelegramEntity, limit int) []TelegramPart {
828 var parts []TelegramPart
831 for _, part := range telegramSplitMessage(text, limit) {
832 end := start + telegramUTF16Units(part)
834 var kept []TelegramEntity
836 for _, entity := range entities {
837 from := max(entity.Offset, start)
838 to := min(entity.Offset+entity.Length, end)
843 entity.Offset = from - start
844 entity.Length = to - from
845 kept = append(kept, entity)
848 parts = append(parts, TelegramPart{