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
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")
84 return TelegramConfig{}, false, fmt.Errorf("%s is not valid JSON with the fields token and owner", telegramConfigFileName)
87 err = config.validate()
89 return TelegramConfig{}, false, fmt.Errorf("%s: %w", telegramConfigFileName, err)
92 return config, true, nil
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
98 func newTelegramBot(api *TelegramAPI, owner int64, offsetPath string, logger *log.Logger) *TelegramBot {
102 offsetPath: offsetPath,
104 minWait: time.Second,
105 maxWait: time.Minute,
106 ready: make(chan struct{}, 1),
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"`
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")
127 return errors.New("owner must be the numeric Telegram user ID of the owner")
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.
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.
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 {
154 minWait time.Duration
155 maxWait time.Duration
162 // Notify queues event for the chat. It never blocks, so a slow network does not
164 func (b *TelegramBot) Notify(event Event) {
166 case "busy", "idle", "reply", "error", "notice":
168 if event.Source == telegramSource {
176 b.queue = append(b.queue, event)
180 case b.ready <- struct{}{}:
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)
192 var sender sync.WaitGroup
200 err := b.poll(ctx, l)
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)
215 for ctx.Err() == nil {
216 event, found := b.next()
234 ticker.Reset(telegramTypingInterval)
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)
257 for ctx.Err() == nil {
258 updates, err := b.api.GetUpdates(ctx, offset)
259 if ctx.Err() != nil {
264 _, asked := telegramRetryable(err)
265 wait = b.pause(ctx, err, wait, asked)
271 for _, update := range updates {
272 if ctx.Err() != nil {
276 err = b.handle(context.WithoutCancel(ctx), l, update)
281 offset = update.UpdateID + 1
282 err = telegramSaveOffset(b.offsetPath, offset)
292 // next removes the first queued event and returns it.
293 func (b *TelegramBot) next() (Event, bool) {
295 defer b.mutex.Unlock()
297 if len(b.queue) == 0 {
298 return Event{}, false
302 b.queue = b.queue[1:]
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)
313 // post sends event to the chat. A reply goes as rich messages of its Markdown,
314 // split with telegramSplitRich. Every other event goes as plain text, split
315 // with telegramSplitMessage.
316 func (b *TelegramBot) post(ctx context.Context, event Event) {
317 if event.Kind != "reply" {
318 for _, text := range telegramSplitMessage(telegramText(event), telegramMessageUnits) {
319 b.deliver(ctx, TelegramPart{
327 for _, markdown := range telegramSplitRich(event.Text, telegramRichBytes) {
328 b.deliverRich(ctx, markdown)
332 // pause logs err and waits the longer of wait and asked, or until ctx ends. It
333 // returns the wait of the next failure: twice wait, up to maxWait.
334 func (b *TelegramBot) pause(ctx context.Context, err error, wait, asked time.Duration) time.Duration {
335 delay := max(wait, asked)
336 b.logger.Printf("%v (next try in %s)", err, delay)
338 timer := time.NewTimer(delay)
346 return min(2*wait, b.maxWait)
349 // handle runs one update. A text message of the owner in the private chat goes
350 // to the agent, and handle returns when it is durable in the log. The line
351 // /stop interrupts the turn. Any other message of the owner gets the answer
352 // that only text is supported. Every other update is ignored, and its content
354 func (b *TelegramBot) handle(ctx context.Context, l *TurnLoop, update TelegramUpdate) error {
355 message := update.Message
356 if message == nil || message.Chat.Type != "private" || message.Chat.ID != b.owner || message.From == nil || message.From.ID != b.owner {
357 b.logger.Print("update ignored: not a message of the owner in the private chat")
362 case message.Text == "":
363 b.notice(telegramTextOnly)
364 case strings.TrimSpace(message.Text) == stopCommand:
366 b.notice("No turn runs.")
369 _, err := l.Submit(telegramSource, message.Text)
376 return fmt.Errorf("flush the message from Telegram: %w", err)
383 // deliver sends part to the chat. When Telegram refuses a part with entities
384 // (HTTP 400), it sends the text of the part again once with no entities, so a
385 // reply is not lost to a bad entity. It tries again after each failure that a
386 // later try can fix, until ctx ends. It drops the part after any other failure.
387 func (b *TelegramBot) deliver(ctx context.Context, part TelegramPart) {
390 err := b.api.SendMessage(ctx, b.owner, part.text, part.entities)
391 if err == nil || ctx.Err() != nil {
395 var answer *TelegramError
396 if len(part.entities) > 0 && errors.As(err, &answer) && answer.Status == http.StatusBadRequest {
397 b.logger.Printf("entities refused, the message goes again as plain text: %v", err)
403 retry, asked := telegramRetryable(err)
405 b.logger.Printf("message dropped: %v", err)
409 wait = b.pause(ctx, err, wait, asked)
413 // deliverRich sends markdown to the chat as a rich message. When the Bot API
414 // refuses it with HTTP 400 or 404, the message was not sent, so deliverRich
415 // sends the same Markdown once with message entities, and the reply is not
416 // lost and does not repeat. It tries again after each failure that a later try
417 // can fix, until ctx ends. It drops the message after any other failure.
418 func (b *TelegramBot) deliverRich(ctx context.Context, markdown string) {
421 err := b.api.SendRichMessage(ctx, b.owner, markdown)
422 if err == nil || ctx.Err() != nil {
426 if telegramRejected(err) {
427 b.logger.Printf("rich message refused, the reply goes with entities: %v", err)
428 for _, part := range telegramReplyParts(markdown) {
435 retry, asked := telegramRetryable(err)
437 b.logger.Printf("message dropped: %v", err)
441 wait = b.pause(ctx, err, wait, asked)
445 // notice queues a short answer of the bot for the chat.
446 func (b *TelegramBot) notice(text string) {
453 // TelegramPart is the text of one message to the chat, at most
454 // telegramMessageUnits long, and its entities.
455 type TelegramPart struct {
457 entities []TelegramEntity
460 // TelegramOffsetFile is the content of the offset file.
461 type TelegramOffsetFile struct {
462 Offset int64 `json:"offset"`
465 // telegramLoadOffset reads the update offset at path. A missing file gives 0,
466 // which asks for every update that Telegram keeps.
467 func telegramLoadOffset(path string) (int64, error) {
468 data, err := os.ReadFile(path)
469 if errors.Is(err, os.ErrNotExist) {
474 return 0, fmt.Errorf("read update offset: %w", err)
477 var file TelegramOffsetFile
478 err = json.Unmarshal(data, &file)
480 return 0, fmt.Errorf("%s: %w", path, err)
483 return file.Offset, nil
486 // telegramSaveOffset replaces the update offset at path.
487 func telegramSaveOffset(path string, offset int64) error {
488 data, err := json.Marshal(TelegramOffsetFile{
492 return fmt.Errorf("encode update offset: %w", err)
495 err = writeFileAtomic(path, append(data, '\n'))
497 return fmt.Errorf("write update offset: %w", err)
503 // telegramSplitMessage cuts text into parts of at most limit UTF-16 code units,
504 // the unit of the Telegram message limit. It cuts after the last line break or
505 // space of a part when one is in its second half, and else at the limit. It
506 // never cuts a character.
507 func telegramSplitMessage(text string, limit int) []string {
510 end := telegramPrefixEnd(text, limit)
511 if end == len(text) {
512 return append(parts, text)
515 cut := strings.LastIndexByte(text[:end], '\n') + 1
517 cut = strings.LastIndexByte(text[:end], ' ') + 1
524 parts = append(parts, text[:cut])
529 // telegramText returns the text of event for the chat. A user message of
530 // another client has its source as a mark.
531 func telegramText(event Event) string {
534 return "[" + event.Source + "] " + event.Text
536 return "Error: " + event.Text
542 // telegramSplitRich cuts the Markdown of a reply into parts of at most limit
543 // bytes. It cuts after a blank line outside a code block, so a table, a code
544 // block, or a paragraph stays whole. When no such cut fits in a part, it cuts
545 // after the last line break outside a code block, then after the last line
546 // break in a code block, which it closes at the end of the part and opens again
547 // in the next part with the same fence line. A line longer than limit is cut at
548 // the limit. It never cuts a character.
549 func telegramSplitRich(markdown string, limit int) []string {
551 for len(markdown) > limit {
552 cut, fence, opening := telegramRichCut(markdown, limit)
554 parts = append(parts, markdown[:cut])
555 markdown = markdown[cut:]
560 parts = append(parts, markdown[:cut]+fence+"\n")
561 markdown = opening + "\n" + markdown[cut:]
564 return append(parts, markdown)
567 // telegramReplyParts returns the messages of the Markdown of a reply with
568 // message entities. A reply that has no text left after the conversion, such as
569 // an empty code block, goes as its Markdown.
570 func telegramReplyParts(markdown string) []TelegramPart {
571 text, entities := telegramMarkdownEntities(markdown)
572 if strings.TrimSpace(text) == "" {
573 text, entities = markdown, nil
576 return telegramSplitEntities(text, entities, telegramMessageUnits)
579 // telegramPrefixEnd returns the byte length of the longest prefix of text with
580 // at most limit UTF-16 code units.
581 func telegramPrefixEnd(text string, limit int) int {
583 for index, char := range text {
589 if units+size > limit {
599 // telegramRichCut returns where telegramSplitRich cuts markdown, which is
600 // longer than limit. For a cut in a code block, it also returns the fence that
601 // closes the block and the line that opens it. Each part before a cut holds
602 // text other than space, and a cut in a code block leaves room for the fence,
603 // so each cut makes the rest shorter.
604 func telegramRichCut(markdown string, limit int) (int, string, string) {
605 blank, line, code := 0, 0, 0
606 var fence, opening, inFence, inOpening string
607 for start := 0; start < limit; {
608 end := strings.IndexByte(markdown[start:], '\n')
609 if end < 0 || start+end+1 > limit {
614 text := strings.TrimRight(markdown[start:end], "\r\n")
615 _, opens := telegramCodeFence(text)
618 if telegramClosesFence(text, fence) {
620 } else if end > len(opening)+1 && end+len(fence)+1 <= limit {
621 code, inFence, inOpening = end, fence, opening
624 fence, opening = opens, text
625 case strings.TrimSpace(markdown[:end]) == "":
626 case strings.TrimSpace(text) == "":
630 if fence == "" && strings.TrimSpace(markdown[:end]) != "" {
643 return code, inFence, inOpening
647 for !utf8.RuneStart(markdown[cut]) {
654 // telegramSplitEntities cuts text into parts with telegramSplitMessage, and
655 // gives each part the entities in it, with offsets from the start of the part.
656 // An entity that crosses a cut becomes one entity in each part.
657 func telegramSplitEntities(text string, entities []TelegramEntity, limit int) []TelegramPart {
658 var parts []TelegramPart
660 for _, part := range telegramSplitMessage(text, limit) {
661 end := start + telegramUTF16Units(part)
662 var kept []TelegramEntity
663 for _, entity := range entities {
664 from := max(entity.Offset, start)
665 to := min(entity.Offset+entity.Length, end)
670 entity.Offset = from - start
671 entity.Length = to - from
672 kept = append(kept, entity)
675 parts = append(parts, TelegramPart{