summaryrefslogtreecommitdiff
path: root/Omni/Agent/Telegram/Messages.hs
blob: dfa3a3d5804f84b41a2aa2c7311036476928e048 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoImplicitPrelude #-}

-- | Telegram Message Queue - Unified async message delivery.
--
-- All outbound Telegram messages go through this queue, enabling:
-- - Immediate sends (sub-second latency via 1s polling)
-- - Scheduled/delayed sends (up to 30 days)
-- - Unified retry handling and error logging
--
-- : out omni-agent-telegram-messages
-- : dep aeson
-- : dep sqlite-simple
-- : dep uuid
module Omni.Agent.Telegram.Messages
  ( -- * Types
    ScheduledMessage (..),
    MessageStatus (..),

    -- * Database
    initScheduledMessagesTable,

    -- * Queueing
    queueMessage,
    enqueueImmediate,
    enqueueDelayed,

    -- * Fetching
    fetchDueMessages,
    listPendingMessages,
    getMessageById,

    -- * Status Updates
    markSending,
    markSent,
    markFailed,
    cancelMessage,

    -- * Dispatch Loop
    messageDispatchLoop,

    -- * Agent Tools
    sendMessageTool,
    listPendingMessagesTool,
    cancelMessageTool,

    -- * Constants
    maxDelaySeconds,
    maxRetries,

    -- * Testing
    main,
    test,
  )
where

import Alpha
import Data.Aeson ((.=))
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.KeyMap as KeyMap
import qualified Data.Text as Text
import Data.Time (NominalDiffTime, UTCTime, addUTCTime, getCurrentTime)
import Data.Time.Format (defaultTimeLocale, formatTime)
import qualified Data.UUID as UUID
import qualified Data.UUID.V4 as UUID
import qualified Database.SQLite.Simple as SQL
import qualified Omni.Agent.Engine as Engine
import qualified Omni.Agent.Memory as Memory
import qualified Omni.Test as Test

main :: IO ()
main = Test.run test

test :: Test.Tree
test =
  Test.group
    "Omni.Agent.Telegram.Messages"
    [ Test.unit "initScheduledMessagesTable is idempotent" <| do
        Memory.withMemoryDb <| \conn -> do
          initScheduledMessagesTable conn
          initScheduledMessagesTable conn
          pure (),
      Test.unit "MessageStatus JSON roundtrip" <| do
        let statuses = [Pending, Sending, Sent, Failed, Cancelled]
        forM_ statuses <| \s ->
          case Aeson.decode (Aeson.encode s) of
            Nothing -> Test.assertFailure ("Failed to decode MessageStatus: " <> show s)
            Just decoded -> decoded Test.@=? s,
      Test.unit "maxDelaySeconds is 30 days" <| do
        maxDelaySeconds Test.@=? (30 * 24 * 60 * 60)
    ]

data MessageStatus
  = Pending
  | Sending
  | Sent
  | Failed
  | Cancelled
  deriving (Show, Eq, Generic)

instance Aeson.ToJSON MessageStatus where
  toJSON Pending = Aeson.String "pending"
  toJSON Sending = Aeson.String "sending"
  toJSON Sent = Aeson.String "sent"
  toJSON Failed = Aeson.String "failed"
  toJSON Cancelled = Aeson.String "cancelled"

instance Aeson.FromJSON MessageStatus where
  parseJSON = Aeson.withText "MessageStatus" parseStatus
    where
      parseStatus "pending" = pure Pending
      parseStatus "sending" = pure Sending
      parseStatus "sent" = pure Sent
      parseStatus "failed" = pure Failed
      parseStatus "cancelled" = pure Cancelled
      parseStatus _ = empty

textToStatus :: Text -> Maybe MessageStatus
textToStatus "pending" = Just Pending
textToStatus "sending" = Just Sending
textToStatus "sent" = Just Sent
textToStatus "failed" = Just Failed
textToStatus "cancelled" = Just Cancelled
textToStatus _ = Nothing

data ScheduledMessage = ScheduledMessage
  { smId :: Text,
    smUserId :: Maybe Text,
    smChatId :: Int,
    smContent :: Text,
    smSendAt :: UTCTime,
    smCreatedAt :: UTCTime,
    smStatus :: MessageStatus,
    smRetryCount :: Int,
    smLastAttemptAt :: Maybe UTCTime,
    smLastError :: Maybe Text,
    smMessageType :: Maybe Text,
    smCorrelationId :: Maybe Text,
    smTelegramMessageId :: Maybe Int
  }
  deriving (Show, Eq, Generic)

instance Aeson.ToJSON ScheduledMessage where
  toJSON m =
    Aeson.object
      [ "id" .= smId m,
        "user_id" .= smUserId m,
        "chat_id" .= smChatId m,
        "content" .= smContent m,
        "send_at" .= smSendAt m,
        "created_at" .= smCreatedAt m,
        "status" .= smStatus m,
        "retry_count" .= smRetryCount m,
        "last_attempt_at" .= smLastAttemptAt m,
        "last_error" .= smLastError m,
        "message_type" .= smMessageType m,
        "correlation_id" .= smCorrelationId m,
        "telegram_message_id" .= smTelegramMessageId m
      ]

instance SQL.FromRow ScheduledMessage where
  fromRow = do
    id' <- SQL.field
    userId <- SQL.field
    chatId <- SQL.field
    content <- SQL.field
    sendAt <- SQL.field
    createdAt <- SQL.field
    statusText <- SQL.field
    retryCount <- SQL.field
    lastAttemptAt <- SQL.field
    lastError <- SQL.field
    messageType <- SQL.field
    correlationId <- SQL.field
    telegramMessageId <- SQL.field
    let status = fromMaybe Pending (textToStatus (statusText :: Text))
    pure
      ScheduledMessage
        { smId = id',
          smUserId = userId,
          smChatId = chatId,
          smContent = content,
          smSendAt = sendAt,
          smCreatedAt = createdAt,
          smStatus = status,
          smRetryCount = retryCount,
          smLastAttemptAt = lastAttemptAt,
          smLastError = lastError,
          smMessageType = messageType,
          smCorrelationId = correlationId,
          smTelegramMessageId = telegramMessageId
        }

maxDelaySeconds :: Int
maxDelaySeconds = 30 * 24 * 60 * 60

maxRetries :: Int
maxRetries = 5

initScheduledMessagesTable :: SQL.Connection -> IO ()
initScheduledMessagesTable conn =
  SQL.execute_
    conn
    "CREATE TABLE IF NOT EXISTS scheduled_messages (\
    \  id TEXT PRIMARY KEY,\
    \  user_id TEXT,\
    \  chat_id INTEGER NOT NULL,\
    \  content TEXT NOT NULL,\
    \  send_at TIMESTAMP NOT NULL,\
    \  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\
    \  status TEXT NOT NULL DEFAULT 'pending',\
    \  retry_count INTEGER NOT NULL DEFAULT 0,\
    \  last_attempt_at TIMESTAMP,\
    \  last_error TEXT,\
    \  message_type TEXT,\
    \  correlation_id TEXT,\
    \  telegram_message_id INTEGER\
    \)"

queueMessage ::
  Maybe Text ->
  Int ->
  Text ->
  UTCTime ->
  Maybe Text ->
  Maybe Text ->
  IO Text
queueMessage mUserId chatId content sendAt msgType correlationId = do
  uuid <- UUID.nextRandom
  now <- getCurrentTime
  let msgId = UUID.toText uuid
  Memory.withMemoryDb <| \conn -> do
    initScheduledMessagesTable conn
    SQL.execute
      conn
      "INSERT INTO scheduled_messages \
      \(id, user_id, chat_id, content, send_at, created_at, status, retry_count, message_type, correlation_id) \
      \VALUES (?, ?, ?, ?, ?, ?, 'pending', 0, ?, ?)"
      (msgId, mUserId, chatId, content, sendAt, now, msgType, correlationId)
  pure msgId

enqueueImmediate ::
  Maybe Text ->
  Int ->
  Text ->
  Maybe Text ->
  Maybe Text ->
  IO Text
enqueueImmediate mUserId chatId content msgType correlationId = do
  now <- getCurrentTime
  queueMessage mUserId chatId content now msgType correlationId

enqueueDelayed ::
  Maybe Text ->
  Int ->
  Text ->
  NominalDiffTime ->
  Maybe Text ->
  Maybe Text ->
  IO Text
enqueueDelayed mUserId chatId content delay msgType correlationId = do
  now <- getCurrentTime
  let sendAt = addUTCTime delay now
  queueMessage mUserId chatId content sendAt msgType correlationId

fetchDueMessages :: UTCTime -> Int -> IO [ScheduledMessage]
fetchDueMessages now batchSize =
  Memory.withMemoryDb <| \conn -> do
    initScheduledMessagesTable conn
    SQL.query
      conn
      "SELECT id, user_id, chat_id, content, send_at, created_at, status, \
      \retry_count, last_attempt_at, last_error, message_type, correlation_id, telegram_message_id \
      \FROM scheduled_messages \
      \WHERE status = 'pending' AND send_at <= ? \
      \ORDER BY send_at ASC \
      \LIMIT ?"
      (now, batchSize)

listPendingMessages :: Maybe Text -> Int -> IO [ScheduledMessage]
listPendingMessages mUserId chatId =
  Memory.withMemoryDb <| \conn -> do
    initScheduledMessagesTable conn
    case mUserId of
      Just uid ->
        SQL.query
          conn
          "SELECT id, user_id, chat_id, content, send_at, created_at, status, \
          \retry_count, last_attempt_at, last_error, message_type, correlation_id, telegram_message_id \
          \FROM scheduled_messages \
          \WHERE user_id = ? AND chat_id = ? AND status = 'pending' AND send_at > datetime('now') \
          \ORDER BY send_at ASC"
          (uid, chatId)
      Nothing ->
        SQL.query
          conn
          "SELECT id, user_id, chat_id, content, send_at, created_at, status, \
          \retry_count, last_attempt_at, last_error, message_type, correlation_id, telegram_message_id \
          \FROM scheduled_messages \
          \WHERE chat_id = ? AND status = 'pending' AND send_at > datetime('now') \
          \ORDER BY send_at ASC"
          (SQL.Only chatId)

getMessageById :: Text -> IO (Maybe ScheduledMessage)
getMessageById msgId =
  Memory.withMemoryDb <| \conn -> do
    initScheduledMessagesTable conn
    results <-
      SQL.query
        conn
        "SELECT id, user_id, chat_id, content, send_at, created_at, status, \
        \retry_count, last_attempt_at, last_error, message_type, correlation_id, telegram_message_id \
        \FROM scheduled_messages \
        \WHERE id = ?"
        (SQL.Only msgId)
    pure (listToMaybe results)

markSending :: Text -> UTCTime -> IO ()
markSending msgId now =
  Memory.withMemoryDb <| \conn -> do
    initScheduledMessagesTable conn
    SQL.execute
      conn
      "UPDATE scheduled_messages SET status = 'sending', last_attempt_at = ? WHERE id = ?"
      (now, msgId)

markSent :: Text -> Maybe Int -> UTCTime -> IO ()
markSent msgId telegramMsgId now =
  Memory.withMemoryDb <| \conn -> do
    initScheduledMessagesTable conn
    SQL.execute
      conn
      "UPDATE scheduled_messages SET status = 'sent', telegram_message_id = ?, last_attempt_at = ? WHERE id = ?"
      (telegramMsgId, now, msgId)

markFailed :: Text -> UTCTime -> Text -> IO ()
markFailed msgId now errorMsg =
  Memory.withMemoryDb <| \conn -> do
    initScheduledMessagesTable conn
    results <-
      SQL.query
        conn
        "SELECT retry_count FROM scheduled_messages WHERE id = ?"
        (SQL.Only msgId) ::
        IO [SQL.Only Int]
    case results of
      [SQL.Only retryCount] ->
        if retryCount < maxRetries
          then do
            let backoffSeconds = 2 ^ retryCount :: Int
                nextAttempt = addUTCTime (fromIntegral backoffSeconds) now
            SQL.execute
              conn
              "UPDATE scheduled_messages SET \
              \status = 'pending', \
              \retry_count = retry_count + 1, \
              \last_attempt_at = ?, \
              \last_error = ?, \
              \send_at = ? \
              \WHERE id = ?"
              (now, errorMsg, nextAttempt, msgId)
            putText <| "Message " <> msgId <> " failed, retry " <> tshow (retryCount + 1) <> " in " <> tshow backoffSeconds <> "s"
          else do
            SQL.execute
              conn
              "UPDATE scheduled_messages SET status = 'failed', last_attempt_at = ?, last_error = ? WHERE id = ?"
              (now, errorMsg, msgId)
            putText <| "Message " <> msgId <> " permanently failed after " <> tshow maxRetries <> " retries"
      _ -> pure ()

cancelMessage :: Text -> IO Bool
cancelMessage msgId =
  Memory.withMemoryDb <| \conn -> do
    initScheduledMessagesTable conn
    SQL.execute
      conn
      "UPDATE scheduled_messages SET status = 'cancelled' WHERE id = ? AND status = 'pending'"
      (SQL.Only msgId)
    changes <- SQL.changes conn
    pure (changes > 0)

messageDispatchLoop :: (Int -> Text -> IO (Maybe Int)) -> IO ()
messageDispatchLoop sendFn =
  forever <| do
    now <- getCurrentTime
    due <- fetchDueMessages now 10
    if null due
      then threadDelay 1000000
      else do
        forM_ due <| \m -> dispatchOne sendFn m
        when (length due < 10) <| threadDelay 1000000

dispatchOne :: (Int -> Text -> IO (Maybe Int)) -> ScheduledMessage -> IO ()
dispatchOne sendFn m = do
  now <- getCurrentTime
  markSending (smId m) now
  result <- try (sendFn (smChatId m) (smContent m))
  case result of
    Left (e :: SomeException) -> do
      let err = "Exception sending Telegram message: " <> tshow e
      markFailed (smId m) now err
    Right Nothing -> do
      now' <- getCurrentTime
      markSent (smId m) Nothing now'
      putText <| "Sent message " <> smId m <> " (no message_id returned)"
    Right (Just telegramMsgId) -> do
      now' <- getCurrentTime
      markSent (smId m) (Just telegramMsgId) now'
      putText <| "Sent message " <> smId m <> " -> telegram_id " <> tshow telegramMsgId

sendMessageTool :: Text -> Int -> Engine.Tool
sendMessageTool uid chatId =
  Engine.Tool
    { Engine.toolName = "send_message",
      Engine.toolDescription =
        "Send a message to the user, optionally delayed. Use for reminders, follow-ups, or multi-part responses. "
          <> "delay_seconds=0 sends immediately; max delay is 30 days (2592000 seconds). "
          <> "Returns a message_id you can use to cancel the message before it's sent.",
      Engine.toolJsonSchema =
        Aeson.object
          [ "type" .= ("object" :: Text),
            "properties"
              .= Aeson.object
                [ "text"
                    .= Aeson.object
                      [ "type" .= ("string" :: Text),
                        "description" .= ("The message text to send (Telegram basic markdown supported)" :: Text)
                      ],
                  "delay_seconds"
                    .= Aeson.object
                      [ "type" .= ("integer" :: Text),
                        "minimum" .= (0 :: Int),
                        "maximum" .= maxDelaySeconds,
                        "description" .= ("Seconds to wait before sending (0 or omit for immediate)" :: Text)
                      ]
                ],
            "required" .= (["text"] :: [Text])
          ],
      Engine.toolExecute = \argsVal -> do
        case argsVal of
          Aeson.Object obj -> do
            let textM = case KeyMap.lookup "text" obj of
                  Just (Aeson.String t) -> Just t
                  _ -> Nothing
                delaySeconds = case KeyMap.lookup "delay_seconds" obj of
                  Just (Aeson.Number n) -> Just (round n :: Int)
                  _ -> Nothing
            case textM of
              Nothing ->
                pure <| Aeson.object ["status" .= ("error" :: Text), "error" .= ("missing 'text' field" :: Text)]
              Just text -> do
                let delay = fromIntegral (fromMaybe 0 delaySeconds)
                now <- getCurrentTime
                let sendAt = addUTCTime delay now
                msgId <- queueMessage (Just uid) chatId text sendAt (Just "agent_tool") Nothing
                pure
                  <| Aeson.object
                    [ "status" .= ("queued" :: Text),
                      "message_id" .= msgId,
                      "scheduled_for" .= formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%SZ" sendAt,
                      "delay_seconds" .= fromMaybe 0 delaySeconds
                    ]
          _ ->
            pure <| Aeson.object ["status" .= ("error" :: Text), "error" .= ("invalid arguments" :: Text)]
    }

listPendingMessagesTool :: Text -> Int -> Engine.Tool
listPendingMessagesTool uid chatId =
  Engine.Tool
    { Engine.toolName = "list_pending_messages",
      Engine.toolDescription =
        "List all pending scheduled messages that haven't been sent yet. "
          <> "Shows message_id, content preview, and scheduled send time.",
      Engine.toolJsonSchema =
        Aeson.object
          [ "type" .= ("object" :: Text),
            "properties" .= Aeson.object []
          ],
      Engine.toolExecute = \_ -> do
        msgs <- listPendingMessages (Just uid) chatId
        let formatted =
              [ Aeson.object
                  [ "message_id" .= smId m,
                    "content_preview" .= Text.take 50 (smContent m),
                    "scheduled_for" .= formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%SZ" (smSendAt m),
                    "message_type" .= smMessageType m
                  ]
                | m <- msgs
              ]
        pure
          <| Aeson.object
            [ "status" .= ("ok" :: Text),
              "count" .= length msgs,
              "messages" .= formatted
            ]
    }

cancelMessageTool :: Engine.Tool
cancelMessageTool =
  Engine.Tool
    { Engine.toolName = "cancel_message",
      Engine.toolDescription =
        "Cancel a pending scheduled message by its message_id. "
          <> "Only works for messages that haven't been sent yet.",
      Engine.toolJsonSchema =
        Aeson.object
          [ "type" .= ("object" :: Text),
            "properties"
              .= Aeson.object
                [ "message_id"
                    .= Aeson.object
                      [ "type" .= ("string" :: Text),
                        "description" .= ("The message_id returned by send_message" :: Text)
                      ]
                ],
            "required" .= (["message_id"] :: [Text])
          ],
      Engine.toolExecute = \argsVal -> do
        case argsVal of
          Aeson.Object obj -> do
            let msgIdM = case KeyMap.lookup "message_id" obj of
                  Just (Aeson.String t) -> Just t
                  _ -> Nothing
            case msgIdM of
              Nothing ->
                pure <| Aeson.object ["status" .= ("error" :: Text), "error" .= ("missing 'message_id' field" :: Text)]
              Just msgId -> do
                success <- cancelMessage msgId
                if success
                  then pure <| Aeson.object ["status" .= ("cancelled" :: Text), "message_id" .= msgId]
                  else pure <| Aeson.object ["status" .= ("not_found" :: Text), "message_id" .= msgId, "error" .= ("message not found or already sent" :: Text)]
          _ ->
            pure <| Aeson.object ["status" .= ("error" :: Text), "error" .= ("invalid arguments" :: Text)]
    }