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. A TelegramOutage logs
149 // the first failure and the end of each run of failures, and the retries
150 // between them log nothing.
151 type TelegramBot struct {
156 minWait time.Duration
157 maxWait time.Duration
164 // Notify queues event for the chat. It never blocks, so a slow network does not
165 // stop the agent. The WhatsApp batches and the runs of the schedules do not go
166 // to the chat: the reply of the agent tells the user what needs the user.
167 func (b *TelegramBot) Notify(event Event) {
169 case "busy", "idle", "reply", "error", "notice", "subagent":
171 if event.Source == whatsappSource || event.Source == scheduleSource {
175 if event.Source == telegramSource {
183 b.queue = append(b.queue, event)
187 case b.ready <- struct{}{}:
192 // Run polls for the messages of the owner and sends the queued events to the
193 // chat until ctx ends. It returns an error only when a message or the offset
194 // cannot be written, because then the bot would lose or repeat messages.
195 func (b *TelegramBot) Run(ctx context.Context, l *TurnLoop, whatsapp *WhatsApp) error {
196 ctx, cancel := context.WithCancel(ctx)
199 var sender sync.WaitGroup
207 err := b.poll(ctx, l, whatsapp)
214 // send sends each queued event to the chat in order until ctx ends. While a
215 // turn runs, it shows the typing action every telegramTypingInterval and after
216 // each message, because a message ends the action.
217 func (b *TelegramBot) send(ctx context.Context) {
218 ticker := time.NewTicker(telegramTypingInterval)
222 for ctx.Err() == nil {
223 event, found := b.next()
241 ticker.Reset(telegramTypingInterval)
254 // poll gets the updates from the stored offset on and handles each one, until
255 // ctx ends. Each update is handled to its end also when ctx ends during it, so
256 // a stop does not repeat its message.
257 func (b *TelegramBot) poll(ctx context.Context, l *TurnLoop, whatsapp *WhatsApp) error {
258 offset, err := telegramLoadOffset(b.offsetPath)
263 outage := &TelegramOutage{
265 loss: "cannot get messages from Telegram",
266 back: "messages from Telegram come again",
270 for ctx.Err() == nil {
271 updates, err := b.api.GetUpdates(ctx, offset)
272 if ctx.Err() != nil {
277 _, asked := telegramRetryable(err)
278 wait = b.pause(ctx, outage, err, wait, asked)
285 for _, update := range updates {
286 if ctx.Err() != nil {
290 err = b.handle(context.WithoutCancel(ctx), l, whatsapp, update)
295 offset = update.UpdateID + 1
296 err = telegramSaveOffset(b.offsetPath, offset)
306 // next removes the first queued event and returns it.
307 func (b *TelegramBot) next() (Event, bool) {
309 defer b.mutex.Unlock()
311 if len(b.queue) == 0 {
312 return Event{}, false
316 b.queue = b.queue[1:]
321 // typing shows the typing action once. A failure is not logged, because the
322 // next message or poll logs the state of the network.
323 func (b *TelegramBot) typing(ctx context.Context) {
324 _ = b.api.SendTyping(ctx, b.owner)
327 // post sends event to the chat. A reply goes as rich messages of its Markdown,
328 // with each < and & outside code escaped by telegramEscapeTags and then split
329 // with telegramSplitRich, so that the length limit counts the escaped text.
330 // Every other event goes as plain text, split with telegramSplitMessage.
331 func (b *TelegramBot) post(ctx context.Context, event Event) {
332 if event.Kind != "reply" {
333 for _, text := range telegramSplitMessage(telegramText(event), telegramMessageUnits) {
334 b.deliver(ctx, TelegramPart{
342 for _, markdown := range telegramSplitRich(telegramEscapeTags(event.Text), telegramRichBytes) {
343 b.deliverRich(ctx, markdown)
347 // pause gives err to outage and waits the longer of wait and asked, or until
348 // ctx ends. It returns the wait of the next failure: twice wait, up to maxWait.
349 func (b *TelegramBot) pause(ctx context.Context, outage *TelegramOutage, err error, wait, asked time.Duration) time.Duration {
350 delay := max(wait, asked)
351 outage.Fail(err, delay)
353 timer := time.NewTimer(delay)
361 return min(2*wait, b.maxWait)
364 // handle runs one update. A text message of the owner in the private chat goes
365 // to the agent, and handle returns when it is durable in the log. The line
366 // /stop interrupts the turn, the line /stop NAME stops the subagent NAME, and a
367 // line that starts with /whatsapp runs a WhatsApp command on whatsapp, whose
368 // answers go to the chat only. Any other message of the owner gets the answer
369 // that only text is supported. Every other update is ignored, and its content
371 func (b *TelegramBot) handle(ctx context.Context, l *TurnLoop, whatsapp *WhatsApp, update TelegramUpdate) error {
372 message := update.Message
373 if message == nil || message.Chat.Type != "private" || message.Chat.ID != b.owner || message.From == nil || message.From.ID != b.owner {
374 b.logger.Print("a Telegram message is ignored, because it is not from the owner in the private chat")
378 name, stop := stopSubagentName(message.Text)
379 args, isWhatsApp := whatsappCommandArgs(message.Text)
381 case message.Text == "":
382 b.notice(telegramTextOnly)
383 case strings.TrimSpace(message.Text) == stopCommand:
385 b.notice("No turn runs.")
388 found, err := l.StopSubagent(name)
390 return fmt.Errorf("stop subagent %s: %w", name, err)
394 b.notice("No subagent " + name + " runs.")
397 whatsapp.Command(args, b.notice)
399 _, err := l.Submit(telegramSource, message.Text)
406 return fmt.Errorf("flush the message from Telegram: %w", err)
413 // deliver sends part to the chat. When Telegram refuses a part with entities
414 // (HTTP 400), it sends the text of the part again once with no entities, so a
415 // reply is not lost to a bad entity. It tries again after each failure that a
416 // later try can fix, until ctx ends. It drops the part after any other failure.
417 func (b *TelegramBot) deliver(ctx context.Context, part TelegramPart) {
418 outage := b.sendOutage()
421 err := b.api.SendMessage(ctx, b.owner, part.text, part.entities)
422 retry, asked := telegramRetryable(err)
427 if err == nil || ctx.Err() != nil {
431 var answer *TelegramError
432 if len(part.entities) > 0 && errors.As(err, &answer) && answer.Status == http.StatusBadRequest {
433 b.logger.Printf("a reply goes as plain text, because Telegram refused its formatting: %v", err)
440 b.logger.Printf("a reply to Telegram is lost: %v", err)
444 wait = b.pause(ctx, outage, err, wait, asked)
448 // deliverRich sends markdown, escaped with telegramEscapeTags, to the chat as a
449 // rich message. When the Bot API refuses it with HTTP 400 or 404, the message
450 // was not sent, so deliverRich sends the text of the part once with message
451 // entities, and the reply is not lost and does not repeat. Message entities
452 // read no HTML, so the fallback gets the Markdown of telegramUnescapeTags, as
453 // the model wrote it. It tries again after each failure that a later try can
454 // fix, until ctx ends. It drops the message after any other failure.
455 func (b *TelegramBot) deliverRich(ctx context.Context, markdown string) {
456 outage := b.sendOutage()
459 err := b.api.SendRichMessage(ctx, b.owner, markdown)
460 retry, asked := telegramRetryable(err)
465 if err == nil || ctx.Err() != nil {
469 if telegramRejected(err) {
470 b.logger.Printf("a reply goes with simpler formatting, because Telegram refused its full formatting: %v", err)
471 for _, part := range telegramReplyParts(telegramUnescapeTags(markdown)) {
479 b.logger.Printf("a reply to Telegram is lost: %v", err)
483 wait = b.pause(ctx, outage, err, wait, asked)
487 // sendOutage returns a new outage of the messages to the chat.
488 func (b *TelegramBot) sendOutage() *TelegramOutage {
489 return &TelegramOutage{
491 loss: "cannot send replies to Telegram",
492 back: "replies go to Telegram again",
496 // notice queues a short answer of the bot for the chat.
497 func (b *TelegramBot) notice(text string) {
504 // TelegramOutage is one run of failures of a kind of Bot API call. The first
505 // failure logs loss, its cause, and the wait of the next try. The retries log
506 // nothing. The next answer of Telegram logs back and the length of the outage.
507 // loss and back say what the user loses and gets again.
508 type TelegramOutage struct {
515 // Fail logs the start of an outage with err and delay, unless an outage runs.
516 func (o *TelegramOutage) Fail(err error, delay time.Duration) {
517 if !o.start.IsZero() {
522 o.logger.Printf("%s: %v (next try in %s)", o.loss, err, durationText(delay))
525 // End logs the end of the outage that runs, with its length.
526 func (o *TelegramOutage) End() {
527 if o.start.IsZero() {
531 o.logger.Printf("%s, after %s", o.back, durationText(time.Since(o.start)))
532 o.start = time.Time{}
535 // TelegramPart is the text of one message to the chat, at most
536 // telegramMessageUnits long, and its entities.
537 type TelegramPart struct {
539 entities []TelegramEntity
542 // TelegramOffsetFile is the content of the offset file.
543 type TelegramOffsetFile struct {
544 Offset int64 `json:"offset"`
547 // telegramLoadOffset reads the update offset at path. A missing file gives 0,
548 // which asks for every update that Telegram keeps.
549 func telegramLoadOffset(path string) (int64, error) {
550 data, err := os.ReadFile(path)
551 if errors.Is(err, os.ErrNotExist) {
556 return 0, fmt.Errorf("read update offset: %w", err)
559 var file TelegramOffsetFile
560 err = json.Unmarshal(data, &file)
562 return 0, fmt.Errorf("%s: %w", path, err)
565 return file.Offset, nil
568 // telegramSaveOffset replaces the update offset at path.
569 func telegramSaveOffset(path string, offset int64) error {
570 data, err := json.Marshal(TelegramOffsetFile{
574 return fmt.Errorf("encode update offset: %w", err)
577 err = writeFileAtomic(path, append(data, '\n'))
579 return fmt.Errorf("write update offset: %w", err)
585 // telegramSplitMessage cuts text into parts of at most limit UTF-16 code units,
586 // the unit of the Telegram message limit. It cuts after the last line break or
587 // space of a part when one is in its second half, and else at the limit. It
588 // never cuts a character.
589 func telegramSplitMessage(text string, limit int) []string {
592 end := telegramPrefixEnd(text, limit)
593 if end == len(text) {
594 return append(parts, text)
597 cut := strings.LastIndexByte(text[:end], '\n') + 1
599 cut = strings.LastIndexByte(text[:end], ' ') + 1
606 parts = append(parts, text[:cut])
611 // telegramText returns the text of event for the chat. A user message of
612 // another client has its source as a mark. A subagent shows only its start and
613 // how its run ended, because the reply of the agent carries the content of the
615 func telegramText(event Event) string {
618 return "[" + event.Source + "] " + event.Text
620 return "[" + event.Text + "] started"
622 return "[" + event.Source + "] " + event.Status
624 return "Error: " + event.Text
630 // telegramSplitRich cuts the Markdown of a reply into parts of at most limit
631 // bytes. It cuts after a blank line outside a code block, so a table, a code
632 // block, or a paragraph stays whole. When no such cut fits in a part, it cuts
633 // after the last line break outside a code block, then after the last line
634 // break in a code block, which it closes at the end of the part and opens again
635 // in the next part with the same fence line. A line longer than limit is cut at
636 // the limit, or before an & in the four bytes before the limit, so that it does
637 // not cut an entity of telegramEscapeTags. It never cuts a character.
638 func telegramSplitRich(markdown string, limit int) []string {
640 for len(markdown) > limit {
641 cut, fence, opening := telegramRichCut(markdown, limit)
643 parts = append(parts, markdown[:cut])
644 markdown = markdown[cut:]
649 parts = append(parts, markdown[:cut]+fence+"\n")
650 markdown = opening + "\n" + markdown[cut:]
653 return append(parts, markdown)
656 // telegramReplyParts returns the messages of the Markdown of a reply with
657 // message entities. A reply that has no text left after the conversion, such as
658 // an empty code block, goes as its Markdown.
659 func telegramReplyParts(markdown string) []TelegramPart {
660 text, entities := telegramMarkdownEntities(markdown)
661 if strings.TrimSpace(text) == "" {
662 text, entities = markdown, nil
665 return telegramSplitEntities(text, entities, telegramMessageUnits)
668 // telegramPrefixEnd returns the byte length of the longest prefix of text with
669 // at most limit UTF-16 code units.
670 func telegramPrefixEnd(text string, limit int) int {
672 for index, char := range text {
678 if units+size > limit {
688 // telegramRichCut returns where telegramSplitRich cuts markdown, which is
689 // longer than limit. For a cut in a code block, it also returns the fence that
690 // closes the block and the line that opens it. Each part before a cut holds
691 // text other than space, and a cut in a code block leaves room for the fence,
692 // so each cut makes the rest shorter.
693 func telegramRichCut(markdown string, limit int) (int, string, string) {
694 blank, line, code := 0, 0, 0
695 var fence, opening, inFence, inOpening string
696 for start := 0; start < limit; {
697 end := strings.IndexByte(markdown[start:], '\n')
698 if end < 0 || start+end+1 > limit {
703 text := strings.TrimRight(markdown[start:end], "\r\n")
704 _, opens := telegramCodeFence(text)
707 if telegramClosesFence(text, fence) {
709 } else if end > len(opening)+1 && end+len(fence)+1 <= limit {
710 code, inFence, inOpening = end, fence, opening
713 fence, opening = opens, text
714 case strings.TrimSpace(markdown[:end]) == "":
715 case strings.TrimSpace(text) == "":
719 if fence == "" && strings.TrimSpace(markdown[:end]) != "" {
732 return code, inFence, inOpening
736 for !utf8.RuneStart(markdown[cut]) {
740 start := max(cut-len("&")+1, 0)
741 entity := strings.LastIndexByte(markdown[start:cut], '&')
742 if entity >= 0 && start+entity > 0 {
749 // telegramSplitEntities cuts text into parts with telegramSplitMessage, and
750 // gives each part the entities in it, with offsets from the start of the part.
751 // An entity that crosses a cut becomes one entity in each part.
752 func telegramSplitEntities(text string, entities []TelegramEntity, limit int) []TelegramPart {
753 var parts []TelegramPart
755 for _, part := range telegramSplitMessage(text, limit) {
756 end := start + telegramUTF16Units(part)
757 var kept []TelegramEntity
758 for _, entity := range entities {
759 from := max(entity.Offset, start)
760 to := min(entity.Offset+entity.Length, end)
765 entity.Offset = from - start
766 entity.Length = to - from
767 kept = append(kept, entity)
770 parts = append(parts, TelegramPart{