-// deliverRich sends markdown to the chat as a rich message. When the Bot API
-// refuses it with HTTP 400 or 404, the message was not sent, so deliverRich
-// sends the same Markdown once with message entities, and the reply is not
-// lost and does not repeat. It tries again after each failure that a later try
-// can fix, until ctx ends. It drops the message after any other failure.
-func (b *telegramBot) deliverRich(ctx context.Context, markdown string) {
- wait := b.minWait
- for {
- err := b.api.SendRichMessage(ctx, b.owner, markdown)
- if err == nil || ctx.Err() != nil {
- return
+// pause gives err to outage and waits the longer of wait and asked, or until
+// ctx ends. It returns the wait of the next failure: twice wait, up to
+// telegramRetryLimit.
+func (b *TelegramBot) pause(ctx context.Context, outage *TelegramOutage, err error, wait, asked time.Duration) time.Duration {
+ delay := max(wait, asked)
+ outage.Fail(err, delay)
+
+ timer := time.NewTimer(delay)
+ defer timer.Stop()
+
+ select {
+ case <-timer.C:
+ case <-ctx.Done():
+ }
+
+ return min(2*wait, telegramRetryLimit)
+}
+
+// handle runs one update. A text message of the owner in the private chat goes
+// to the agent, and handle returns when it is durable in the log. The line
+// /stop interrupts the turn, the line /stop NAME stops the subagent NAME, and a
+// line that starts with /whatsapp runs a WhatsApp command on whatsapp, whose
+// answers go to the chat only. Photos and image documents enter the shared
+// image store with their caption. Voice notes keep their audio and local
+// transcript. Other media keep the text-only answer. Every other update is
+// ignored, and its content is not logged.
+func (b *TelegramBot) handle(ctx context.Context, l *TurnLoop, whatsapp *WhatsApp, update TelegramUpdate) error {
+ message := update.Message
+ if message == nil || message.Chat.Type != "private" || message.Chat.ID != b.owner || message.From == nil || message.From.ID != b.owner {
+ b.logger.Info("message ignored: not from the owner")
+
+ return nil
+ }
+
+ name, stop := stopSubagentName(message.Text)
+ args, isWhatsApp := whatsappCommandArgs(message.Text)
+ switch {
+ case message.Voice != nil:
+ text := telegramVoiceText(ctx, b.api, l.agent.Voices(), b.voice, message)
+ _, err := l.Submit(telegramSource, text)
+ if err != nil {
+ return fmt.Errorf("submit Telegram voice: %w", err)