20 // telegramAPI is the Telegram Bot API service.
21 telegramAPI = "https://api.telegram.org"
23 // botConfigFileName is the bot config in the data directory. The daemon
24 // runs the bot only when the file exists.
25 botConfigFileName = "telegram.json"
27 // offsetFileName is the update offset of the bot in the agent directory.
28 offsetFileName = "telegram-offset.json"
30 // telegramSource is the source of the user messages from Telegram.
31 telegramSource = "telegram"
33 // messageUnits is the most UTF-16 code units of one Telegram message.
36 // typingInterval is how often the bot shows the typing action while a
37 // turn runs. Telegram shows the action for about five seconds.
38 typingInterval = 4 * time.Second
40 // textOnly is the answer to a message that is not text.
41 textOnly = "Only text messages are supported."
44 // botConfig holds the settings of telegram.json: the bot token and the user ID
45 // of the owner. The token is a secret, so the file must have mode 0600.
46 type botConfig struct {
47 Token string `json:"token"`
48 Owner int64 `json:"owner"`
51 // telegramBot connects the private chat of the owner with the agent. It polls
52 // the Bot API for new messages and sends each text message of the owner to the
53 // agent. It ignores every other update. Its sender sends the replies, the
54 // errors, the notices of the bot, and the user messages of the other clients to
55 // the chat, and shows the typing action while a turn runs. Only the replies
56 // have a format: their Markdown goes as message entities. The rest is plain
57 // text. Tool calls do not go to the chat.
59 // The offset file holds the ID of the next update. It moves past an update
60 // only after the message of the update is durable in the log, so a restart
61 // does not lose a message. A crash between the flush and the offset write
62 // makes Telegram send the update again, and the message repeats once.
64 // A failed Bot API call waits and tries again, from minWait up to maxWait, or
65 // as long as the Bot API asks. It never stops the agent.
66 type telegramBot struct {
79 // botPart is the text of one message to the chat, at most messageUnits long,
86 // offsetFile is the content of the offset file.
87 type offsetFile struct {
88 Offset int64 `json:"offset"`
91 // loadBotConfig reads telegram.json in dir. It returns false when the file
92 // does not exist. An error never holds the token.
93 func loadBotConfig(dir string) (botConfig, bool, error) {
94 path := filepath.Join(dir, botConfigFileName)
95 info, err := os.Stat(path)
96 if errors.Is(err, os.ErrNotExist) {
97 return botConfig{}, false, nil
101 return botConfig{}, false, fmt.Errorf("read bot config: %w", err)
104 if info.Mode().Perm()&0o077 != 0 {
105 return botConfig{}, false, fmt.Errorf("%s holds the bot token, so its mode must be 0600", botConfigFileName)
108 data, err := os.ReadFile(path)
110 return botConfig{}, false, fmt.Errorf("read bot config: %w", err)
114 decoder := json.NewDecoder(bytes.NewReader(data))
115 decoder.DisallowUnknownFields()
116 err = decoder.Decode(&config)
117 if err == nil && !errors.Is(decoder.Decode(&struct{}{}), io.EOF) {
118 err = errors.New("data after the JSON object")
122 return botConfig{}, false, fmt.Errorf("%s is not valid JSON with the fields token and owner", botConfigFileName)
125 err = config.validate()
127 return botConfig{}, false, fmt.Errorf("%s: %w", botConfigFileName, err)
130 return config, true, nil
133 // validate makes sure that the token has the form of a bot token and that the
134 // owner is a user ID. The token goes into a URL path, so it can only hold the
135 // characters of a bot token.
136 func (c botConfig) validate() error {
137 id, secret, found := strings.Cut(c.Token, ":")
138 if !found || id == "" || secret == "" || strings.Trim(id, "0123456789") != "" || strings.Trim(secret, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-") != "" {
139 return errors.New("token does not have the form of a bot token from BotFather")
143 return errors.New("owner must be the numeric Telegram user ID of the owner")
149 // newTelegramBot returns the bot of owner on api. The offset file is at
150 // offsetPath, and logger gets the failures. No log line holds the text of a
152 func newTelegramBot(api *botAPI, owner int64, offsetPath string, logger *log.Logger) *telegramBot {
156 offsetPath: offsetPath,
158 minWait: time.Second,
159 maxWait: time.Minute,
160 ready: make(chan struct{}, 1),
164 // Notify queues event for the chat. It never blocks, so a slow network does not
166 func (b *telegramBot) Notify(event Event) {
168 case "busy", "idle", "reply", "error", "notice":
170 if event.Source == telegramSource {
178 b.queue = append(b.queue, event)
182 case b.ready <- struct{}{}:
187 // Run polls for the messages of the owner and sends the queued events to the
188 // chat until ctx ends. It returns an error only when a message or the offset
189 // cannot be written, because then the bot would lose or repeat messages.
190 func (b *telegramBot) Run(ctx context.Context, l *loop) error {
191 ctx, cancel := context.WithCancel(ctx)
194 var sender sync.WaitGroup
202 err := b.poll(ctx, l)
209 // send sends each queued event to the chat in order until ctx ends. While a
210 // turn runs, it shows the typing action every typingInterval and after each
211 // message, because a message ends the action.
212 func (b *telegramBot) send(ctx context.Context) {
213 ticker := time.NewTicker(typingInterval)
217 for ctx.Err() == nil {
218 event, found := b.next()
236 ticker.Reset(typingInterval)
240 for _, part := range botParts(event) {
251 // next removes the first queued event and returns it.
252 func (b *telegramBot) next() (Event, bool) {
254 defer b.mutex.Unlock()
256 if len(b.queue) == 0 {
257 return Event{}, false
261 b.queue = b.queue[1:]
266 // typing shows the typing action once. A failure is not logged, because the
267 // next message or poll logs the state of the network.
268 func (b *telegramBot) typing(ctx context.Context) {
269 _ = b.api.SendTyping(ctx, b.owner)
272 // deliver sends part to the chat. When Telegram refuses a part with entities
273 // (HTTP 400), it sends the text of the part again once with no entities, so a
274 // reply is not lost to a bad entity. It tries again after each failure that a
275 // later try can fix, until ctx ends. It drops the part after any other failure.
276 func (b *telegramBot) deliver(ctx context.Context, part botPart) {
279 err := b.api.SendMessage(ctx, b.owner, part.text, part.entities)
280 if err == nil || ctx.Err() != nil {
285 if len(part.entities) > 0 && errors.As(err, &answer) && answer.Status == http.StatusBadRequest {
286 b.logger.Printf("entities refused, the message goes again as plain text: %v", err)
292 retry, asked := retryable(err)
294 b.logger.Printf("message dropped: %v", err)
298 wait = b.pause(ctx, err, wait, asked)
302 // pause logs err and waits the longer of wait and asked, or until ctx ends. It
303 // returns the wait of the next failure: twice wait, up to maxWait.
304 func (b *telegramBot) pause(ctx context.Context, err error, wait, asked time.Duration) time.Duration {
305 delay := max(wait, asked)
306 b.logger.Printf("%v (next try in %s)", err, delay)
308 timer := time.NewTimer(delay)
316 return min(2*wait, b.maxWait)
319 // poll gets the updates from the stored offset on and handles each one, until
320 // ctx ends. Each update is handled to its end also when ctx ends during it, so
321 // a stop does not repeat its message.
322 func (b *telegramBot) poll(ctx context.Context, l *loop) error {
323 offset, err := loadOffset(b.offsetPath)
329 for ctx.Err() == nil {
330 updates, err := b.api.GetUpdates(ctx, offset)
331 if ctx.Err() != nil {
336 _, asked := retryable(err)
337 wait = b.pause(ctx, err, wait, asked)
343 for _, update := range updates {
344 if ctx.Err() != nil {
348 err = b.handle(context.WithoutCancel(ctx), l, update)
353 offset = update.UpdateID + 1
354 err = saveOffset(b.offsetPath, offset)
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. Any other message of the owner gets the answer
367 // that only text is supported. Every other update is ignored, and its content
369 func (b *telegramBot) handle(ctx context.Context, l *loop, update botUpdate) error {
370 message := update.Message
371 if message == nil || message.Chat.Type != "private" || message.Chat.ID != b.owner || message.From == nil || message.From.ID != b.owner {
372 b.logger.Print("update ignored: not a message of the owner in the private chat")
377 case message.Text == "":
379 case strings.TrimSpace(message.Text) == stopCommand:
381 b.notice("No turn runs.")
384 _, err := l.Submit(telegramSource, message.Text)
391 return fmt.Errorf("flush the message from Telegram: %w", err)
398 // notice queues a short answer of the bot for the chat.
399 func (b *telegramBot) notice(text string) {
406 // loadOffset reads the update offset at path. A missing file gives 0, which
407 // asks for every update that Telegram keeps.
408 func loadOffset(path string) (int64, error) {
409 data, err := os.ReadFile(path)
410 if errors.Is(err, os.ErrNotExist) {
415 return 0, fmt.Errorf("read update offset: %w", err)
419 err = json.Unmarshal(data, &file)
421 return 0, fmt.Errorf("%s: %w", path, err)
424 return file.Offset, nil
427 // saveOffset replaces the update offset at path.
428 func saveOffset(path string, offset int64) error {
429 data, err := json.Marshal(offsetFile{
433 return fmt.Errorf("encode update offset: %w", err)
436 err = writeFileAtomic(path, append(data, '\n'))
438 return fmt.Errorf("write update offset: %w", err)
444 // botParts returns the messages of event for the chat. The Markdown of a reply
445 // becomes text with entities. Every other event is plain text. A reply that has
446 // no text left after the conversion, such as an empty code block, goes as its
448 func botParts(event Event) []botPart {
449 text, entities := botText(event), []botEntity(nil)
450 if event.Kind == "reply" {
451 text, entities = markdownEntities(event.Text)
454 if strings.TrimSpace(text) == "" {
455 text, entities = event.Text, nil
458 return splitEntities(text, entities, messageUnits)
461 // botText returns the text of event for the chat. A user message of another
462 // client has its source as a mark.
463 func botText(event Event) string {
466 return "[" + event.Source + "] " + event.Text
468 return "Error: " + event.Text
474 // splitEntities cuts text into parts with splitMessage, and gives each part the
475 // entities in it, with offsets from the start of the part. An entity that
476 // crosses a cut becomes one entity in each part.
477 func splitEntities(text string, entities []botEntity, limit int) []botPart {
480 for _, part := range splitMessage(text, limit) {
481 end := start + utf16Units(part)
483 for _, entity := range entities {
484 from := max(entity.Offset, start)
485 to := min(entity.Offset+entity.Length, end)
490 entity.Offset = from - start
491 entity.Length = to - from
492 kept = append(kept, entity)
495 parts = append(parts, botPart{
506 // splitMessage cuts text into parts of at most limit UTF-16 code units, the
507 // unit of the Telegram message limit. It cuts after the last line break or
508 // space of a part when one is in its second half, and else at the limit. It
509 // never cuts a character.
510 func splitMessage(text string, limit int) []string {
513 end := prefixEnd(text, limit)
514 if end == len(text) {
515 return append(parts, text)
518 cut := strings.LastIndexByte(text[:end], '\n') + 1
520 cut = strings.LastIndexByte(text[:end], ' ') + 1
527 parts = append(parts, text[:cut])
532 // prefixEnd returns the byte length of the longest prefix of text with at most
533 // limit UTF-16 code units.
534 func prefixEnd(text string, limit int) int {
536 for index, char := range text {
542 if units+size > limit {