summaryrefslogtreecommitdiff
path: root/Omni/Agent/Tools/Todos.hs
blob: 81253c16ec9ee92167b283c8b390c39771c22dbb (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
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE NoImplicitPrelude #-}

-- | Todo tool with due dates and reminders.
--
-- Provides user-scoped todos with optional due dates.
--
-- : out omni-agent-tools-todos
-- : dep aeson
-- : dep sqlite-simple
-- : dep time
module Omni.Agent.Tools.Todos
  ( -- * Tools
    todoAddTool,
    todoListTool,
    todoCompleteTool,
    todoDeleteTool,

    -- * Direct API
    Todo (..),
    createTodo,
    listTodos,
    listPendingTodos,
    listOverdueTodos,
    completeTodo,
    deleteTodo,

    -- * Database
    initTodosTable,

    -- * Testing
    main,
    test,
  )
where

import Alpha
import Data.Aeson ((.!=), (.:), (.:?), (.=))
import qualified Data.Aeson as Aeson
import qualified Data.Text as Text
import Data.Time (UTCTime, getCurrentTime)
import Data.Time.Format (defaultTimeLocale, parseTimeM)
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.Tools.Todos"
    [ Test.unit "todoAddTool has correct schema" <| do
        let tool = todoAddTool "test-user-id"
        Engine.toolName tool Test.@=? "todo_add",
      Test.unit "todoListTool has correct schema" <| do
        let tool = todoListTool "test-user-id"
        Engine.toolName tool Test.@=? "todo_list",
      Test.unit "todoCompleteTool has correct schema" <| do
        let tool = todoCompleteTool "test-user-id"
        Engine.toolName tool Test.@=? "todo_complete",
      Test.unit "todoDeleteTool has correct schema" <| do
        let tool = todoDeleteTool "test-user-id"
        Engine.toolName tool Test.@=? "todo_delete",
      Test.unit "Todo JSON roundtrip" <| do
        now <- getCurrentTime
        let td =
              Todo
                { todoId = 1,
                  todoUserId = "user-123",
                  todoTitle = "Buy milk",
                  todoDueDate = Just now,
                  todoCompleted = False,
                  todoCreatedAt = now
                }
        case Aeson.decode (Aeson.encode td) of
          Nothing -> Test.assertFailure "Failed to decode Todo"
          Just decoded -> do
            todoTitle decoded Test.@=? "Buy milk"
            todoCompleted decoded Test.@=? False,
      Test.unit "parseDueDate handles various formats" <| do
        isJust (parseDueDate "2024-12-25") Test.@=? True
        isJust (parseDueDate "2024-12-25 14:00") Test.@=? True
    ]

data Todo = Todo
  { todoId :: Int,
    todoUserId :: Text,
    todoTitle :: Text,
    todoDueDate :: Maybe UTCTime,
    todoCompleted :: Bool,
    todoCreatedAt :: UTCTime
  }
  deriving (Show, Eq, Generic)

instance Aeson.ToJSON Todo where
  toJSON td =
    Aeson.object
      [ "id" .= todoId td,
        "user_id" .= todoUserId td,
        "title" .= todoTitle td,
        "due_date" .= todoDueDate td,
        "completed" .= todoCompleted td,
        "created_at" .= todoCreatedAt td
      ]

instance Aeson.FromJSON Todo where
  parseJSON =
    Aeson.withObject "Todo" <| \v ->
      (Todo </ (v .: "id"))
        <*> (v .: "user_id")
        <*> (v .: "title")
        <*> (v .:? "due_date")
        <*> (v .: "completed")
        <*> (v .: "created_at")

instance SQL.FromRow Todo where
  fromRow =
    (Todo </ SQL.field)
      <*> SQL.field
      <*> SQL.field
      <*> SQL.field
      <*> SQL.field
      <*> SQL.field

initTodosTable :: SQL.Connection -> IO ()
initTodosTable conn = do
  SQL.execute_
    conn
    "CREATE TABLE IF NOT EXISTS todos (\
    \  id INTEGER PRIMARY KEY AUTOINCREMENT,\
    \  user_id TEXT NOT NULL,\
    \  title TEXT NOT NULL,\
    \  due_date TIMESTAMP,\
    \  completed INTEGER NOT NULL DEFAULT 0,\
    \  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\
    \)"
  SQL.execute_
    conn
    "CREATE INDEX IF NOT EXISTS idx_todos_user ON todos(user_id)"
  SQL.execute_
    conn
    "CREATE INDEX IF NOT EXISTS idx_todos_due ON todos(user_id, due_date)"

parseDueDate :: Text -> Maybe UTCTime
parseDueDate txt =
  let s = Text.unpack txt
   in parseTimeM True defaultTimeLocale "%Y-%m-%d %H:%M" s
        <|> parseTimeM True defaultTimeLocale "%Y-%m-%d" s
        <|> parseTimeM True defaultTimeLocale "%Y-%m-%dT%H:%M:%S" s
        <|> parseTimeM True defaultTimeLocale "%Y-%m-%dT%H:%M:%SZ" s

createTodo :: Text -> Text -> Maybe Text -> IO Todo
createTodo uid title maybeDueDateStr = do
  now <- getCurrentTime
  let dueDate = maybeDueDateStr +> parseDueDate
  Memory.withMemoryDb <| \conn -> do
    initTodosTable conn
    SQL.execute
      conn
      "INSERT INTO todos (user_id, title, due_date, completed, created_at) VALUES (?, ?, ?, 0, ?)"
      (uid, title, dueDate, now)
    rowId <- SQL.lastInsertRowId conn
    pure
      Todo
        { todoId = fromIntegral rowId,
          todoUserId = uid,
          todoTitle = title,
          todoDueDate = dueDate,
          todoCompleted = False,
          todoCreatedAt = now
        }

listTodos :: Text -> Int -> IO [Todo]
listTodos uid limit =
  Memory.withMemoryDb <| \conn -> do
    initTodosTable conn
    SQL.query
      conn
      "SELECT id, user_id, title, due_date, completed, created_at \
      \FROM todos WHERE user_id = ? \
      \ORDER BY completed ASC, due_date ASC NULLS LAST, created_at DESC LIMIT ?"
      (uid, limit)

listPendingTodos :: Text -> Int -> IO [Todo]
listPendingTodos uid limit =
  Memory.withMemoryDb <| \conn -> do
    initTodosTable conn
    SQL.query
      conn
      "SELECT id, user_id, title, due_date, completed, created_at \
      \FROM todos WHERE user_id = ? AND completed = 0 \
      \ORDER BY due_date ASC NULLS LAST, created_at DESC LIMIT ?"
      (uid, limit)

listOverdueTodos :: Text -> IO [Todo]
listOverdueTodos uid = do
  now <- getCurrentTime
  Memory.withMemoryDb <| \conn -> do
    initTodosTable conn
    SQL.query
      conn
      "SELECT id, user_id, title, due_date, completed, created_at \
      \FROM todos WHERE user_id = ? AND completed = 0 AND due_date < ? \
      \ORDER BY due_date ASC"
      (uid, now)

completeTodo :: Text -> Int -> IO Bool
completeTodo uid tid =
  Memory.withMemoryDb <| \conn -> do
    initTodosTable conn
    SQL.execute
      conn
      "UPDATE todos SET completed = 1 WHERE id = ? AND user_id = ?"
      (tid, uid)
    changes <- SQL.changes conn
    pure (changes > 0)

deleteTodo :: Text -> Int -> IO Bool
deleteTodo uid tid =
  Memory.withMemoryDb <| \conn -> do
    initTodosTable conn
    SQL.execute
      conn
      "DELETE FROM todos WHERE id = ? AND user_id = ?"
      (tid, uid)
    changes <- SQL.changes conn
    pure (changes > 0)

todoAddTool :: Text -> Engine.Tool
todoAddTool uid =
  Engine.Tool
    { Engine.toolName = "todo_add",
      Engine.toolDescription =
        "Add a todo item with optional due date. Use for tasks, reminders, "
          <> "or anything the user needs to remember to do. "
          <> "Due date format: 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM'.",
      Engine.toolJsonSchema =
        Aeson.object
          [ "type" .= ("object" :: Text),
            "properties"
              .= Aeson.object
                [ "title"
                    .= Aeson.object
                      [ "type" .= ("string" :: Text),
                        "description" .= ("What needs to be done" :: Text)
                      ],
                  "due_date"
                    .= Aeson.object
                      [ "type" .= ("string" :: Text),
                        "description" .= ("Optional due date: 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM'" :: Text)
                      ]
                ],
            "required" .= (["title"] :: [Text])
          ],
      Engine.toolExecute = executeTodoAdd uid
    }

executeTodoAdd :: Text -> Aeson.Value -> IO Aeson.Value
executeTodoAdd uid v =
  case Aeson.fromJSON v of
    Aeson.Error e -> pure (Aeson.object ["error" .= Text.pack e])
    Aeson.Success (args :: TodoAddArgs) -> do
      td <- createTodo uid (taTitle args) (taDueDate args)
      let dueDateMsg = case todoDueDate td of
            Just d -> " (due: " <> tshow d <> ")"
            Nothing -> ""
      pure
        ( Aeson.object
            [ "success" .= True,
              "todo_id" .= todoId td,
              "message" .= ("Added todo: " <> todoTitle td <> dueDateMsg)
            ]
        )

data TodoAddArgs = TodoAddArgs
  { taTitle :: Text,
    taDueDate :: Maybe Text
  }
  deriving (Generic)

instance Aeson.FromJSON TodoAddArgs where
  parseJSON =
    Aeson.withObject "TodoAddArgs" <| \v ->
      (TodoAddArgs </ (v .: "title"))
        <*> (v .:? "due_date")

todoListTool :: Text -> Engine.Tool
todoListTool uid =
  Engine.Tool
    { Engine.toolName = "todo_list",
      Engine.toolDescription =
        "List todos. By default shows pending (incomplete) todos. "
          <> "Can show all todos or just overdue ones.",
      Engine.toolJsonSchema =
        Aeson.object
          [ "type" .= ("object" :: Text),
            "properties"
              .= Aeson.object
                [ "filter"
                    .= Aeson.object
                      [ "type" .= ("string" :: Text),
                        "description" .= ("Filter: 'pending' (default), 'all', or 'overdue'" :: Text)
                      ],
                  "limit"
                    .= Aeson.object
                      [ "type" .= ("integer" :: Text),
                        "description" .= ("Max todos to return (default: 20)" :: Text)
                      ]
                ],
            "required" .= ([] :: [Text])
          ],
      Engine.toolExecute = executeTodoList uid
    }

executeTodoList :: Text -> Aeson.Value -> IO Aeson.Value
executeTodoList uid v =
  case Aeson.fromJSON v of
    Aeson.Error e -> pure (Aeson.object ["error" .= Text.pack e])
    Aeson.Success (args :: TodoListArgs) -> do
      let lim = min 50 (max 1 (tlLimit args))
      todos <- case tlFilter args of
        "all" -> listTodos uid lim
        "overdue" -> listOverdueTodos uid
        _ -> listPendingTodos uid lim
      pure
        ( Aeson.object
            [ "success" .= True,
              "count" .= length todos,
              "todos" .= formatTodosForLLM todos
            ]
        )

formatTodosForLLM :: [Todo] -> Text
formatTodosForLLM [] = "No todos found."
formatTodosForLLM todos =
  Text.unlines (map formatTodo todos)
  where
    formatTodo td =
      let status = if todoCompleted td then "[x]" else "[ ]"
          dueStr = case todoDueDate td of
            Just d -> " (due: " <> Text.pack (show d) <> ")"
            Nothing -> ""
       in status <> " " <> todoTitle td <> dueStr <> " (id: " <> tshow (todoId td) <> ")"

data TodoListArgs = TodoListArgs
  { tlFilter :: Text,
    tlLimit :: Int
  }
  deriving (Generic)

instance Aeson.FromJSON TodoListArgs where
  parseJSON =
    Aeson.withObject "TodoListArgs" <| \v ->
      (TodoListArgs </ (v .:? "filter" .!= "pending"))
        <*> (v .:? "limit" .!= 20)

todoCompleteTool :: Text -> Engine.Tool
todoCompleteTool uid =
  Engine.Tool
    { Engine.toolName = "todo_complete",
      Engine.toolDescription =
        "Mark a todo as completed. Use when the user says they finished something.",
      Engine.toolJsonSchema =
        Aeson.object
          [ "type" .= ("object" :: Text),
            "properties"
              .= Aeson.object
                [ "todo_id"
                    .= Aeson.object
                      [ "type" .= ("integer" :: Text),
                        "description" .= ("The ID of the todo to complete" :: Text)
                      ]
                ],
            "required" .= (["todo_id"] :: [Text])
          ],
      Engine.toolExecute = executeTodoComplete uid
    }

executeTodoComplete :: Text -> Aeson.Value -> IO Aeson.Value
executeTodoComplete uid v =
  case Aeson.fromJSON v of
    Aeson.Error e -> pure (Aeson.object ["error" .= Text.pack e])
    Aeson.Success (args :: TodoCompleteArgs) -> do
      completed <- completeTodo uid (tcTodoId args)
      if completed
        then
          pure
            ( Aeson.object
                [ "success" .= True,
                  "message" .= ("Todo marked as complete" :: Text)
                ]
            )
        else
          pure
            ( Aeson.object
                [ "success" .= False,
                  "error" .= ("Todo not found" :: Text)
                ]
            )

newtype TodoCompleteArgs = TodoCompleteArgs
  { tcTodoId :: Int
  }
  deriving (Generic)

instance Aeson.FromJSON TodoCompleteArgs where
  parseJSON =
    Aeson.withObject "TodoCompleteArgs" <| \v ->
      TodoCompleteArgs </ (v .: "todo_id")

todoDeleteTool :: Text -> Engine.Tool
todoDeleteTool uid =
  Engine.Tool
    { Engine.toolName = "todo_delete",
      Engine.toolDescription =
        "Delete a todo permanently. Use when a todo is no longer needed.",
      Engine.toolJsonSchema =
        Aeson.object
          [ "type" .= ("object" :: Text),
            "properties"
              .= Aeson.object
                [ "todo_id"
                    .= Aeson.object
                      [ "type" .= ("integer" :: Text),
                        "description" .= ("The ID of the todo to delete" :: Text)
                      ]
                ],
            "required" .= (["todo_id"] :: [Text])
          ],
      Engine.toolExecute = executeTodoDelete uid
    }

executeTodoDelete :: Text -> Aeson.Value -> IO Aeson.Value
executeTodoDelete uid v =
  case Aeson.fromJSON v of
    Aeson.Error e -> pure (Aeson.object ["error" .= Text.pack e])
    Aeson.Success (args :: TodoDeleteArgs) -> do
      deleted <- deleteTodo uid (tdTodoId args)
      if deleted
        then
          pure
            ( Aeson.object
                [ "success" .= True,
                  "message" .= ("Todo deleted" :: Text)
                ]
            )
        else
          pure
            ( Aeson.object
                [ "success" .= False,
                  "error" .= ("Todo not found" :: Text)
                ]
            )

newtype TodoDeleteArgs = TodoDeleteArgs
  { tdTodoId :: Int
  }
  deriving (Generic)

instance Aeson.FromJSON TodoDeleteArgs where
  parseJSON =
    Aeson.withObject "TodoDeleteArgs" <| \v ->
      TodoDeleteArgs </ (v .: "todo_id")