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 message entities. The rest is plain
64 // text. Tool calls do not go to the chat.
66 // The offset file holds the ID of the next update. It moves past an update
67 // only after the message of the update is durable in the log, so a restart
68 // does not lose a message. A crash between the flush and the offset write
69 // makes Telegram send the update again, and the message repeats once.
71 // A failed Bot API call waits and tries again, from minWait up to maxWait, or
72 // as long as the Bot API asks. It never stops the agent.
73 type telegramBot struct {
86 // botPart is the text of one message to the chat, at most messageUnits long,
93 // offsetFile is the content of the offset file.
94 type offsetFile struct {
95 Offset int64 `json:"offset"`
98 // loadBotConfig reads telegram.json in dir. It returns false when the file
99 // does not exist. An error never holds the token.
100 func loadBotConfig(dir string) (botConfig, bool, error) {
101 path := filepath.Join(dir, botConfigFileName)
102 info, err := os.Stat(path)
103 if errors.Is(err, os.ErrNotExist) {
104 return botConfig{}, false, nil
108 return botConfig{}, false, fmt.Errorf("read bot config: %w", err)
111 if info.Mode().Perm()&0o077 != 0 {
112 return botConfig{}, false, fmt.Errorf("%s holds the bot token, so its mode must be 0600", botConfigFileName)
115 data, err := os.ReadFile(path)
117 return botConfig{}, false, fmt.Errorf("read bot config: %w", err)
121 decoder := json.NewDecoder(bytes.NewReader(data))
122 decoder.DisallowUnknownFields()
123 err = decoder.Decode(&config)
124 if err == nil && !errors.Is(decoder.Decode(&struct{}{}), io.EOF) {
125 err = errors.New("data after the JSON object")
129 return botConfig{}, false, fmt.Errorf("%s is not valid JSON with the fields token and owner", botConfigFileName)
132 err = config.validate()
134 return botConfig{}, false, fmt.Errorf("%s: %w", botConfigFileName, err)
137 return config, true, nil
140 // validate makes sure that the token has the form of a bot token and that the
141 // owner is a user ID. The token goes into a URL path, so it can only hold the
142 // characters of a bot token.
143 func (c botConfig) validate() error {
144 id, secret, found := strings.Cut(c.Token, ":")
145 if !found || id == "" || secret == "" || strings.Trim(id, "0123456789") != "" || strings.Trim(secret, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-") != "" {
146 return errors.New("token does not have the form of a bot token from BotFather")
150 return errors.New("owner must be the numeric Telegram user ID of the owner")
156 // newTelegramBot returns the bot of owner on api. The offset file is at
157 // offsetPath, and logger gets the failures. No log line holds the text of a
159 func newTelegramBot(api *botAPI, owner int64, offsetPath string, logger *log.Logger) *telegramBot {
163 offsetPath: offsetPath,
165 minWait: time.Second,
166 maxWait: time.Minute,
167 ready: make(chan struct{}, 1),
171 // Notify queues event for the chat. It never blocks, so a slow network does not
173 func (b *telegramBot) Notify(event Event) {
175 case "busy", "idle", "reply", "error", "notice":
177 if event.Source == telegramSource {
185 b.queue = append(b.queue, event)
189 case b.ready <- struct{}{}:
194 // Run polls for the messages of the owner and sends the queued events to the
195 // chat until ctx ends. It returns an error only when a message or the offset
196 // cannot be written, because then the bot would lose or repeat messages.
197 func (b *telegramBot) Run(ctx context.Context, l *loop) error {
198 ctx, cancel := context.WithCancel(ctx)
201 var sender sync.WaitGroup
209 err := b.poll(ctx, l)
216 // send sends each queued event to the chat in order until ctx ends. While a
217 // turn runs, it shows the typing action every typingInterval and after each
218 // message, because a message ends the action.
219 func (b *telegramBot) send(ctx context.Context) {
220 ticker := time.NewTicker(typingInterval)
224 for ctx.Err() == nil {
225 event, found := b.next()
243 ticker.Reset(typingInterval)
247 for _, part := range botParts(event) {
258 // next removes the first queued event and returns it.
259 func (b *telegramBot) next() (Event, bool) {
261 defer b.mutex.Unlock()
263 if len(b.queue) == 0 {
264 return Event{}, false
268 b.queue = b.queue[1:]
273 // typing shows the typing action once. A failure is not logged, because the
274 // next message or poll logs the state of the network.
275 func (b *telegramBot) typing(ctx context.Context) {
276 _ = b.api.SendTyping(ctx, b.owner)
279 // deliver sends part to the chat. When Telegram refuses a part with entities
280 // (HTTP 400), it sends the text of the part again once with no entities, so a
281 // reply is not lost to a bad entity. It tries again after each failure that a
282 // later try can fix, until ctx ends. It drops the part after any other failure.
283 func (b *telegramBot) deliver(ctx context.Context, part botPart) {
286 err := b.api.SendMessage(ctx, b.owner, part.text, part.entities)
287 if err == nil || ctx.Err() != nil {
292 if len(part.entities) > 0 && errors.As(err, &answer) && answer.Status == http.StatusBadRequest {
293 b.logger.Printf("entities refused, the message goes again as plain text: %v", err)
299 retry, asked := retryable(err)
301 b.logger.Printf("message dropped: %v", err)
305 wait = b.pause(ctx, err, wait, asked)
309 // pause logs err and waits the longer of wait and asked, or until ctx ends. It
310 // returns the wait of the next failure: twice wait, up to maxWait.
311 func (b *telegramBot) pause(ctx context.Context, err error, wait, asked time.Duration) time.Duration {
312 delay := max(wait, asked)
313 b.logger.Printf("%v (next try in %s)", err, delay)
315 timer := time.NewTimer(delay)
323 return min(2*wait, b.maxWait)
326 // poll gets the updates from the stored offset on and handles each one, until
327 // ctx ends. Each update is handled to its end also when ctx ends during it, so
328 // a stop does not repeat its message.
329 func (b *telegramBot) poll(ctx context.Context, l *loop) error {
330 offset, err := loadOffset(b.offsetPath)
336 for ctx.Err() == nil {
337 updates, err := b.api.GetUpdates(ctx, offset)
338 if ctx.Err() != nil {
343 _, asked := retryable(err)
344 wait = b.pause(ctx, err, wait, asked)
350 for _, update := range updates {
351 if ctx.Err() != nil {
355 err = b.handle(context.WithoutCancel(ctx), l, update)
360 offset = update.UpdateID + 1
361 err = saveOffset(b.offsetPath, offset)
371 // handle runs one update. A text message of the owner in the private chat goes
372 // to the agent, and handle returns when it is durable in the log. The line
373 // /stop interrupts the turn. Any other message of the owner gets the answer
374 // that only text is supported. Every other update is ignored, and its content
376 func (b *telegramBot) handle(ctx context.Context, l *loop, update botUpdate) error {
377 message := update.Message
378 if message == nil || message.Chat.Type != "private" || message.Chat.ID != b.owner || message.From == nil || message.From.ID != b.owner {
379 b.logger.Print("update ignored: not a message of the owner in the private chat")
384 case message.Text == "":
386 case strings.TrimSpace(message.Text) == stopCommand:
388 b.notice("No turn runs.")
391 _, err := l.Submit(telegramSource, message.Text)
398 return fmt.Errorf("flush the message from Telegram: %w", err)
405 // notice queues a short answer of the bot for the chat.
406 func (b *telegramBot) notice(text string) {
413 // loadOffset reads the update offset at path. A missing file gives 0, which
414 // asks for every update that Telegram keeps.
415 func loadOffset(path string) (int64, error) {
416 data, err := os.ReadFile(path)
417 if errors.Is(err, os.ErrNotExist) {
422 return 0, fmt.Errorf("read update offset: %w", err)
426 err = json.Unmarshal(data, &file)
428 return 0, fmt.Errorf("%s: %w", path, err)
431 return file.Offset, nil
434 // saveOffset replaces the update offset at path.
435 func saveOffset(path string, offset int64) error {
436 data, err := json.Marshal(offsetFile{
440 return fmt.Errorf("encode update offset: %w", err)
443 err = writeFileAtomic(path, append(data, '\n'))
445 return fmt.Errorf("write update offset: %w", err)
451 // botParts returns the messages of event for the chat. The Markdown of a reply
452 // becomes text with entities. Every other event is plain text. A reply that has
453 // no text left after the conversion, such as an empty code block, goes as its
455 func botParts(event Event) []botPart {
456 text, entities := botText(event), []botEntity(nil)
457 if event.Kind == "reply" {
458 text, entities = markdownEntities(event.Text)
461 if strings.TrimSpace(text) == "" {
462 text, entities = event.Text, nil
465 return splitEntities(text, entities, messageUnits)
468 // botText returns the text of event for the chat. A user message of another
469 // client has its source as a mark.
470 func botText(event Event) string {
473 return "[" + event.Source + "] " + event.Text
475 return "Error: " + event.Text
481 // splitEntities cuts text into parts with splitMessage, and gives each part the
482 // entities in it, with offsets from the start of the part. An entity that
483 // crosses a cut becomes one entity in each part.
484 func splitEntities(text string, entities []botEntity, limit int) []botPart {
487 for _, part := range splitMessage(text, limit) {
488 end := start + utf16Units(part)
490 for _, entity := range entities {
491 from := max(entity.Offset, start)
492 to := min(entity.Offset+entity.Length, end)
497 entity.Offset = from - start
498 entity.Length = to - from
499 kept = append(kept, entity)
502 parts = append(parts, botPart{
513 // splitMessage cuts text into parts of at most limit UTF-16 code units, the
514 // unit of the Telegram message limit. It cuts after the last line break or
515 // space of a part when one is in its second half, and else at the limit. It
516 // never cuts a character.
517 func splitMessage(text string, limit int) []string {
520 end := prefixEnd(text, limit)
521 if end == len(text) {
522 return append(parts, text)
525 cut := strings.LastIndexByte(text[:end], '\n') + 1
527 cut = strings.LastIndexByte(text[:end], ' ') + 1
534 parts = append(parts, text[:cut])
539 // prefixEnd returns the byte length of the longest prefix of text with at most
540 // limit UTF-16 code units.
541 func prefixEnd(text string, limit int) int {
543 for index, char := range text {
549 if units+size > limit {
559 // splitRich cuts the Markdown of a reply into parts of at most limit bytes. It
560 // cuts after a blank line outside a code block, so a table, a code block, or a
561 // paragraph stays whole. When no such cut fits in a part, it cuts after the
562 // last line break outside a code block, then after the last line break in a
563 // code block, which it closes at the end of the part and opens again in the
564 // next part with the same fence line. A line longer than limit is cut at the
565 // limit. It never cuts a character.
566 func splitRich(markdown string, limit int) []string {
568 for len(markdown) > limit {
569 cut, fence, opening := richCut(markdown, limit)
571 parts = append(parts, markdown[:cut])
572 markdown = markdown[cut:]
577 parts = append(parts, markdown[:cut]+fence+"\n")
578 markdown = opening + "\n" + markdown[cut:]
581 return append(parts, markdown)
584 // richCut returns where splitRich cuts markdown, which is longer than limit.
585 // For a cut in a code block, it also returns the fence that closes the block
586 // and the line that opens it. Each part before a cut holds text other than
587 // space, and a cut in a code block leaves room for the fence, so each cut makes
589 func richCut(markdown string, limit int) (int, string, string) {
590 blank, line, code := 0, 0, 0
591 var fence, opening, inFence, inOpening string
592 for start := 0; start < limit; {
593 end := strings.IndexByte(markdown[start:], '\n')
594 if end < 0 || start+end+1 > limit {
599 text := strings.TrimRight(markdown[start:end], "\r\n")
600 _, opens := codeFence(text)
603 if closesFence(text, fence) {
605 } else if end > len(opening)+1 && end+len(fence)+1 <= limit {
606 code, inFence, inOpening = end, fence, opening
609 fence, opening = opens, text
610 case strings.TrimSpace(markdown[:end]) == "":
611 case strings.TrimSpace(text) == "":
615 if fence == "" && strings.TrimSpace(markdown[:end]) != "" {
628 return code, inFence, inOpening
632 for !utf8.RuneStart(markdown[cut]) {