21 // telegramAPI is the Telegram Bot API service.
22 telegramAPI = "https://api.telegram.org"
24 // botConfigFileName is the bot config in the data directory. The daemon
25 // runs the bot only when the file exists.
26 botConfigFileName = "telegram.json"
28 // offsetFileName is the update offset of the bot in the agent directory.
29 offsetFileName = "telegram-offset.json"
31 // telegramSource is the source of the user messages from Telegram.
32 telegramSource = "telegram"
34 // messageUnits is the most UTF-16 code units of one Telegram message.
37 // richMessageBytes is the most bytes of the Markdown of one rich
38 // message. The Bot API allows 32768 characters of rendered text, and
39 // the Markdown of a text has at least as many bytes as the text has
41 richMessageBytes = 32768
43 // typingInterval is how often the bot shows the typing action while a
44 // turn runs. Telegram shows the action for about five seconds.
45 typingInterval = 4 * time.Second
47 // textOnly is the answer to a message that is not text.
48 textOnly = "Only text messages are supported."
51 // botConfig holds the settings of telegram.json: the bot token and the user ID
52 // of the owner. The token is a secret, so the file must have mode 0600.
53 type botConfig struct {
54 Token string `json:"token"`
55 Owner int64 `json:"owner"`
58 // telegramBot connects the private chat of the owner with the agent. It polls
59 // the Bot API for new messages and sends each text message of the owner to the
60 // agent. It ignores every other update. Its sender sends the replies, the
61 // errors, the notices of the bot, and the user messages of the other clients to
62 // the chat, and shows the typing action while a turn runs. Only the replies
63 // have a format: their Markdown goes as rich messages, which Telegram renders
64 // itself, and as message entities only when Telegram refuses a rich message.
65 // The rest is plain text. Tool calls do not go to the chat.
67 // The offset file holds the ID of the next update. It moves past an update
68 // only after the message of the update is durable in the log, so a restart
69 // does not lose a message. A crash between the flush and the offset write
70 // makes Telegram send the update again, and the message repeats once.
72 // A failed Bot API call waits and tries again, from minWait up to maxWait, or
73 // as long as the Bot API asks. It never stops the agent.
74 type telegramBot struct {
87 // botPart is the text of one message to the chat, at most messageUnits long,
94 // offsetFile is the content of the offset file.
95 type offsetFile struct {
96 Offset int64 `json:"offset"`
99 // loadBotConfig reads telegram.json in dir. It returns false when the file
100 // does not exist. An error never holds the token.
101 func loadBotConfig(dir string) (botConfig, bool, error) {
102 path := filepath.Join(dir, botConfigFileName)
103 info, err := os.Stat(path)
104 if errors.Is(err, os.ErrNotExist) {
105 return botConfig{}, false, nil
109 return botConfig{}, false, fmt.Errorf("read bot config: %w", err)
112 if info.Mode().Perm()&0o077 != 0 {
113 return botConfig{}, false, fmt.Errorf("%s holds the bot token, so its mode must be 0600", botConfigFileName)
116 data, err := os.ReadFile(path)
118 return botConfig{}, false, fmt.Errorf("read bot config: %w", err)
122 decoder := json.NewDecoder(bytes.NewReader(data))
123 decoder.DisallowUnknownFields()
124 err = decoder.Decode(&config)
125 if err == nil && !errors.Is(decoder.Decode(&struct{}{}), io.EOF) {
126 err = errors.New("data after the JSON object")
130 return botConfig{}, false, fmt.Errorf("%s is not valid JSON with the fields token and owner", botConfigFileName)
133 err = config.validate()
135 return botConfig{}, false, fmt.Errorf("%s: %w", botConfigFileName, err)
138 return config, true, nil
141 // validate makes sure that the token has the form of a bot token and that the
142 // owner is a user ID. The token goes into a URL path, so it can only hold the
143 // characters of a bot token.
144 func (c botConfig) validate() error {
145 id, secret, found := strings.Cut(c.Token, ":")
146 if !found || id == "" || secret == "" || strings.Trim(id, "0123456789") != "" || strings.Trim(secret, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-") != "" {
147 return errors.New("token does not have the form of a bot token from BotFather")
151 return errors.New("owner must be the numeric Telegram user ID of the owner")
157 // newTelegramBot returns the bot of owner on api. The offset file is at
158 // offsetPath, and logger gets the failures. No log line holds the text of a
160 func newTelegramBot(api *botAPI, owner int64, offsetPath string, logger *log.Logger) *telegramBot {
164 offsetPath: offsetPath,
166 minWait: time.Second,
167 maxWait: time.Minute,
168 ready: make(chan struct{}, 1),
172 // Notify queues event for the chat. It never blocks, so a slow network does not
174 func (b *telegramBot) Notify(event Event) {
176 case "busy", "idle", "reply", "error", "notice":
178 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
197 // cannot be written, because then the bot would lose or repeat messages.
198 func (b *telegramBot) Run(ctx context.Context, l *loop) error {
199 ctx, cancel := context.WithCancel(ctx)
202 var sender sync.WaitGroup
210 err := b.poll(ctx, l)
217 // send sends each queued event to the chat in order until ctx ends. While a
218 // turn runs, it shows the typing action every typingInterval and after each
219 // message, because a message ends the action.
220 func (b *telegramBot) send(ctx context.Context) {
221 ticker := time.NewTicker(typingInterval)
225 for ctx.Err() == nil {
226 event, found := b.next()
244 ticker.Reset(typingInterval)
257 // next removes the first queued event and returns it.
258 func (b *telegramBot) next() (Event, bool) {
260 defer b.mutex.Unlock()
262 if len(b.queue) == 0 {
263 return Event{}, false
267 b.queue = b.queue[1:]
272 // typing shows the typing action once. A failure is not logged, because the
273 // next message or poll logs the state of the network.
274 func (b *telegramBot) typing(ctx context.Context) {
275 _ = b.api.SendTyping(ctx, b.owner)
278 // post sends event to the chat. A reply goes as rich messages of its Markdown,
279 // split with splitRich. Every other event goes as plain text, split with
281 func (b *telegramBot) post(ctx context.Context, event Event) {
282 if event.Kind != "reply" {
283 for _, text := range splitMessage(botText(event), messageUnits) {
284 b.deliver(ctx, botPart{
292 for _, markdown := range splitRich(event.Text, richMessageBytes) {
293 b.deliverRich(ctx, markdown)
297 // deliverRich sends markdown to the chat as a rich message. When the Bot API
298 // refuses it with HTTP 400 or 404, the message was not sent, so deliverRich
299 // sends the same Markdown once with message entities, and the reply is not
300 // lost and does not repeat. It tries again after each failure that a later try
301 // can fix, until ctx ends. It drops the message after any other failure.
302 func (b *telegramBot) deliverRich(ctx context.Context, markdown string) {
305 err := b.api.SendRichMessage(ctx, b.owner, markdown)
306 if err == nil || ctx.Err() != nil {
311 b.logger.Printf("rich message refused, the reply goes with entities: %v", err)
312 for _, part := range replyParts(markdown) {
319 retry, asked := retryable(err)
321 b.logger.Printf("message dropped: %v", err)
325 wait = b.pause(ctx, err, wait, asked)
329 // deliver sends part to the chat. When Telegram refuses a part with entities
330 // (HTTP 400), it sends the text of the part again once with no entities, so a
331 // reply is not lost to a bad entity. It tries again after each failure that a
332 // later try can fix, until ctx ends. It drops the part after any other failure.
333 func (b *telegramBot) deliver(ctx context.Context, part botPart) {
336 err := b.api.SendMessage(ctx, b.owner, part.text, part.entities)
337 if err == nil || ctx.Err() != nil {
342 if len(part.entities) > 0 && errors.As(err, &answer) && answer.Status == http.StatusBadRequest {
343 b.logger.Printf("entities refused, the message goes again as plain text: %v", err)
349 retry, asked := retryable(err)
351 b.logger.Printf("message dropped: %v", err)
355 wait = b.pause(ctx, err, wait, asked)
359 // pause logs err and waits the longer of wait and asked, or until ctx ends. It
360 // returns the wait of the next failure: twice wait, up to maxWait.
361 func (b *telegramBot) pause(ctx context.Context, err error, wait, asked time.Duration) time.Duration {
362 delay := max(wait, asked)
363 b.logger.Printf("%v (next try in %s)", err, delay)
365 timer := time.NewTimer(delay)
373 return min(2*wait, b.maxWait)
376 // poll gets the updates from the stored offset on and handles each one, until
377 // ctx ends. Each update is handled to its end also when ctx ends during it, so
378 // a stop does not repeat its message.
379 func (b *telegramBot) poll(ctx context.Context, l *loop) error {
380 offset, err := loadOffset(b.offsetPath)
386 for ctx.Err() == nil {
387 updates, err := b.api.GetUpdates(ctx, offset)
388 if ctx.Err() != nil {
393 _, asked := retryable(err)
394 wait = b.pause(ctx, err, wait, asked)
400 for _, update := range updates {
401 if ctx.Err() != nil {
405 err = b.handle(context.WithoutCancel(ctx), l, update)
410 offset = update.UpdateID + 1
411 err = saveOffset(b.offsetPath, offset)
421 // handle runs one update. A text message of the owner in the private chat goes
422 // to the agent, and handle returns when it is durable in the log. The line
423 // /stop interrupts the turn. Any other message of the owner gets the answer
424 // that only text is supported. Every other update is ignored, and its content
426 func (b *telegramBot) handle(ctx context.Context, l *loop, update botUpdate) error {
427 message := update.Message
428 if message == nil || message.Chat.Type != "private" || message.Chat.ID != b.owner || message.From == nil || message.From.ID != b.owner {
429 b.logger.Print("update ignored: not a message of the owner in the private chat")
434 case message.Text == "":
436 case strings.TrimSpace(message.Text) == stopCommand:
438 b.notice("No turn runs.")
441 _, err := l.Submit(telegramSource, message.Text)
448 return fmt.Errorf("flush the message from Telegram: %w", err)
455 // notice queues a short answer of the bot for the chat.
456 func (b *telegramBot) notice(text string) {
463 // loadOffset reads the update offset at path. A missing file gives 0, which
464 // asks for every update that Telegram keeps.
465 func loadOffset(path string) (int64, error) {
466 data, err := os.ReadFile(path)
467 if errors.Is(err, os.ErrNotExist) {
472 return 0, fmt.Errorf("read update offset: %w", err)
476 err = json.Unmarshal(data, &file)
478 return 0, fmt.Errorf("%s: %w", path, err)
481 return file.Offset, nil
484 // saveOffset replaces the update offset at path.
485 func saveOffset(path string, offset int64) error {
486 data, err := json.Marshal(offsetFile{
490 return fmt.Errorf("encode update offset: %w", err)
493 err = writeFileAtomic(path, append(data, '\n'))
495 return fmt.Errorf("write update offset: %w", err)
501 // botText returns the text of event for the chat. A user message of another
502 // client has its source as a mark.
503 func botText(event Event) string {
506 return "[" + event.Source + "] " + event.Text
508 return "Error: " + event.Text
514 // splitMessage cuts text into parts of at most limit UTF-16 code units, the
515 // unit of the Telegram message limit. It cuts after the last line break or
516 // space of a part when one is in its second half, and else at the limit. It
517 // never cuts a character.
518 func splitMessage(text string, limit int) []string {
521 end := prefixEnd(text, limit)
522 if end == len(text) {
523 return append(parts, text)
526 cut := strings.LastIndexByte(text[:end], '\n') + 1
528 cut = strings.LastIndexByte(text[:end], ' ') + 1
535 parts = append(parts, text[:cut])
540 // prefixEnd returns the byte length of the longest prefix of text with at most
541 // limit UTF-16 code units.
542 func prefixEnd(text string, limit int) int {
544 for index, char := range text {
550 if units+size > limit {
560 // splitRich cuts the Markdown of a reply into parts of at most limit bytes. It
561 // cuts after a blank line outside a code block, so a table, a code block, or a
562 // paragraph stays whole. When no such cut fits in a part, it cuts after the
563 // last line break outside a code block, then after the last line break in a
564 // code block, which it closes at the end of the part and opens again in the
565 // next part with the same fence line. A line longer than limit is cut at the
566 // limit. It never cuts a character.
567 func splitRich(markdown string, limit int) []string {
569 for len(markdown) > limit {
570 cut, fence, opening := richCut(markdown, limit)
572 parts = append(parts, markdown[:cut])
573 markdown = markdown[cut:]
578 parts = append(parts, markdown[:cut]+fence+"\n")
579 markdown = opening + "\n" + markdown[cut:]
582 return append(parts, markdown)
585 // richCut returns where splitRich cuts markdown, which is longer than limit.
586 // For a cut in a code block, it also returns the fence that closes the block
587 // and the line that opens it. Each part before a cut holds text other than
588 // space, and a cut in a code block leaves room for the fence, so each cut makes
590 func richCut(markdown string, limit int) (int, string, string) {
591 blank, line, code := 0, 0, 0
592 var fence, opening, inFence, inOpening string
593 for start := 0; start < limit; {
594 end := strings.IndexByte(markdown[start:], '\n')
595 if end < 0 || start+end+1 > limit {
600 text := strings.TrimRight(markdown[start:end], "\r\n")
601 _, opens := codeFence(text)
604 if closesFence(text, fence) {
606 } else if end > len(opening)+1 && end+len(fence)+1 <= limit {
607 code, inFence, inOpening = end, fence, opening
610 fence, opening = opens, text
611 case strings.TrimSpace(markdown[:end]) == "":
612 case strings.TrimSpace(text) == "":
616 if fence == "" && strings.TrimSpace(markdown[:end]) != "" {
629 return code, inFence, inOpening
633 for !utf8.RuneStart(markdown[cut]) {
640 // replyParts returns the messages of the Markdown of a reply with message
641 // entities. A reply that has no text left after the conversion, such as an
642 // empty code block, goes as its Markdown.
643 func replyParts(markdown string) []botPart {
644 text, entities := markdownEntities(markdown)
645 if strings.TrimSpace(text) == "" {
646 text, entities = markdown, nil
649 return splitEntities(text, entities, messageUnits)
652 // splitEntities cuts text into parts with splitMessage, and gives each part the
653 // entities in it, with offsets from the start of the part. An entity that
654 // crosses a cut becomes one entity in each part.
655 func splitEntities(text string, entities []botEntity, limit int) []botPart {
658 for _, part := range splitMessage(text, limit) {
659 end := start + utf16Units(part)
661 for _, entity := range entities {
662 from := max(entity.Offset, start)
663 to := min(entity.Offset+entity.Length, end)
668 entity.Offset = from - start
669 entity.Length = to - from
670 kept = append(kept, entity)
673 parts = append(parts, botPart{