summaryrefslogtreecommitdiff
path: root/Omni/Agent/Skills.hs
blob: a9953b19aa01ca5291e3706b640586a6833cd714 (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
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoImplicitPrelude #-}

-- | Skills system for ava agent.
--
-- Skills are modular instruction sets that extend ava's capabilities.
-- They follow the Claude Skills format: a directory with SKILL.md and
-- optional scripts/, references/, and assets/ subdirectories.
--
-- Directory structure:
--   _/var/ava/skills/
--   ├── shared/           -- Skills available to all users
--   │   └── skill-creator/
--   ├── ben/              -- Ben's private skills
--   └── alice/            -- Alice's private skills
--
-- : out omni-agent-skills
-- : dep aeson
-- : dep directory
module Omni.Agent.Skills
  ( Skill (..),
    SkillMetadata (..),
    loadSkill,
    loadSkillMetadata,
    listSkills,
    listSkillsForUser,
    publishSkill,
    skillTool,
    listSkillsTool,
    publishSkillTool,
    skillsDir,
    main,
    test,
  )
where

import Alpha
import Data.Aeson ((.:), (.=))
import qualified Data.Aeson as Aeson
import qualified Data.List as List
import qualified Data.Text as Text
import qualified Data.Text.IO as TextIO
import qualified Omni.Agent.Engine as Engine
import qualified Omni.Test as Test
import qualified System.Directory as Directory
import qualified System.FilePath as FilePath

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

test :: Test.Tree
test =
  Test.group
    "Omni.Agent.Skills"
    [ Test.unit "skillsDir returns correct path" <| do
        let dir = skillsDir
        ("_/var/ava/skills" `Text.isSuffixOf` Text.pack dir) Test.@=? True,
      Test.unit "SkillMetadata parses from YAML frontmatter" <| do
        let yaml = "name: test-skill\ndescription: A test skill"
        case parseYamlFrontmatter yaml of
          Nothing -> Test.assertFailure "Failed to parse frontmatter"
          Just meta -> do
            skillMetaName meta Test.@=? "test-skill"
            skillMetaDescription meta Test.@=? "A test skill",
      Test.unit "parseSkillMd extracts frontmatter and body" <| do
        let content =
              "---\n\
              \name: my-skill\n\
              \description: Does things\n\
              \---\n\
              \# My Skill\n\
              \\n\
              \Instructions here."
        case parseSkillMd content of
          Nothing -> Test.assertFailure "Failed to parse SKILL.md"
          Just (meta, body) -> do
            skillMetaName meta Test.@=? "my-skill"
            ("# My Skill" `Text.isInfixOf` body) Test.@=? True,
      Test.unit "skillTool schema is valid" <| do
        let schema = Engine.toolJsonSchema (skillTool "test-user")
        case schema of
          Aeson.Object _ -> pure ()
          _ -> Test.assertFailure "Schema should be an object",
      Test.unit "listSkillsTool schema is valid" <| do
        let schema = Engine.toolJsonSchema (listSkillsTool "test-user")
        case schema of
          Aeson.Object _ -> pure ()
          _ -> Test.assertFailure "Schema should be an object"
    ]

-- | Base directory for all skills
skillsDir :: FilePath
skillsDir = "_/var/ava/skills"

-- | Skill metadata from YAML frontmatter
data SkillMetadata = SkillMetadata
  { skillMetaName :: Text,
    skillMetaDescription :: Text
  }
  deriving (Show, Eq, Generic)

instance Aeson.FromJSON SkillMetadata where
  parseJSON =
    Aeson.withObject "SkillMetadata" <| \v ->
      (SkillMetadata </ (v .: "name"))
        <*> (v .: "description")

instance Aeson.ToJSON SkillMetadata where
  toJSON m =
    Aeson.object
      [ "name" .= skillMetaName m,
        "description" .= skillMetaDescription m
      ]

-- | Simple YAML frontmatter parser for skill metadata
-- Parses lines like "name: value" and "description: value"
parseYamlFrontmatter :: Text -> Maybe SkillMetadata
parseYamlFrontmatter yaml = do
  let kvPairs = parseKvLines (Text.lines yaml)
      getName = List.lookup "name" kvPairs
      getDesc = List.lookup "description" kvPairs
  name' <- getName
  desc <- getDesc
  pure SkillMetadata {skillMetaName = name', skillMetaDescription = desc}
  where
    parseKvLines :: [Text] -> [(Text, Text)]
    parseKvLines = mapMaybe parseKvLine

    parseKvLine :: Text -> Maybe (Text, Text)
    parseKvLine line = do
      let (key, rest) = Text.breakOn ":" line
      guard (not (Text.null rest))
      let value = Text.strip (Text.drop 1 rest)
      guard (not (Text.null key))
      pure (Text.strip key, value)

-- | Full skill with metadata and content
data Skill = Skill
  { skillName :: Text,
    skillDescription :: Text,
    skillBody :: Text,
    skillPath :: FilePath
  }
  deriving (Show, Eq, Generic)

instance Aeson.ToJSON Skill where
  toJSON s =
    Aeson.object
      [ "name" .= skillName s,
        "description" .= skillDescription s,
        "body" .= skillBody s,
        "path" .= skillPath s
      ]

-- | Parse SKILL.md content into metadata and body
parseSkillMd :: Text -> Maybe (SkillMetadata, Text)
parseSkillMd content = do
  let stripped = Text.strip content
  guard (Text.isPrefixOf "---" stripped)
  let afterFirst = Text.drop 3 stripped
      (yamlPart, rest) = Text.breakOn "---" (Text.stripStart afterFirst)
  guard (not (Text.null rest))
  let body = Text.strip (Text.drop 3 rest)
  meta <- parseYamlFrontmatter (Text.strip yamlPart)
  pure (meta, body)

-- | Load just the metadata for a skill (for progressive disclosure)
loadSkillMetadata :: FilePath -> IO (Maybe SkillMetadata)
loadSkillMetadata skillDir = do
  let skillMd = skillDir FilePath.</> "SKILL.md"
  exists <- Directory.doesFileExist skillMd
  if exists
    then do
      content <- TextIO.readFile skillMd
      pure (fst </ parseSkillMd content)
    else pure Nothing

-- | Load a full skill by name for a user
loadSkill :: Text -> Text -> IO (Either Text Skill)
loadSkill userName skillName' = do
  let userDir = skillsDir FilePath.</> Text.unpack userName FilePath.</> Text.unpack skillName'
      sharedDir = skillsDir FilePath.</> "shared" FilePath.</> Text.unpack skillName'

  -- Try user's private skills first, then shared
  userExists <- Directory.doesDirectoryExist userDir
  sharedExists <- Directory.doesDirectoryExist sharedDir

  let targetDir
        | userExists = Just userDir
        | sharedExists = Just sharedDir
        | otherwise = Nothing

  case targetDir of
    Nothing -> do
      available <- listSkillsForUser userName
      pure
        <| Left
        <| "Skill not found: "
        <> skillName'
        <> ". Available skills: "
        <> Text.intercalate ", " (map skillMetaName available)
    Just dir -> do
      let skillMd = dir FilePath.</> "SKILL.md"
      exists <- Directory.doesFileExist skillMd
      if exists
        then do
          content <- TextIO.readFile skillMd
          case parseSkillMd content of
            Nothing -> pure <| Left "Failed to parse SKILL.md frontmatter"
            Just (meta, body) ->
              pure
                <| Right
                <| Skill
                  { skillName = skillMetaName meta,
                    skillDescription = skillMetaDescription meta,
                    skillBody = body,
                    skillPath = dir
                  }
        else pure <| Left ("SKILL.md not found in " <> Text.pack dir)

-- | List all skills in a directory
listSkillsInDir :: FilePath -> IO [SkillMetadata]
listSkillsInDir dir = do
  exists <- Directory.doesDirectoryExist dir
  if exists
    then do
      entries <- Directory.listDirectory dir
      catMaybes
        </ forM
          entries
          ( \entry -> do
              let entryPath = dir FilePath.</> entry
              isDir <- Directory.doesDirectoryExist entryPath
              if isDir
                then loadSkillMetadata entryPath
                else pure Nothing
          )
    else pure []

-- | List all available skills (shared only)
listSkills :: IO [SkillMetadata]
listSkills = listSkillsInDir (skillsDir FilePath.</> "shared")

-- | List skills available to a specific user (their private + shared)
listSkillsForUser :: Text -> IO [SkillMetadata]
listSkillsForUser userName = do
  userSkills <- listSkillsInDir (skillsDir FilePath.</> Text.unpack userName)
  sharedSkills <- listSkillsInDir (skillsDir FilePath.</> "shared")
  -- Dedupe by name, preferring user's version
  let userNames = map skillMetaName userSkills
      uniqueShared = filter (\s -> skillMetaName s `notElem` userNames) sharedSkills
  pure (userSkills <> uniqueShared)

-- | Publish a skill from user's private directory to shared
publishSkill :: Text -> Text -> IO (Either Text Text)
publishSkill userName skillName' = do
  let userDir = skillsDir FilePath.</> Text.unpack userName FilePath.</> Text.unpack skillName'
      sharedDir = skillsDir FilePath.</> "shared" FilePath.</> Text.unpack skillName'

  userExists <- Directory.doesDirectoryExist userDir
  if not userExists
    then pure <| Left ("Skill not found in your directory: " <> skillName')
    else do
      -- Copy recursively
      Directory.createDirectoryIfMissing True sharedDir
      copyDirectory userDir sharedDir
      pure <| Right ("Published " <> skillName' <> " to shared skills")

-- | Recursively copy a directory
copyDirectory :: FilePath -> FilePath -> IO ()
copyDirectory src dst = do
  entries <- Directory.listDirectory src
  forM_
    entries
    ( \entry -> do
        let srcPath = src FilePath.</> entry
            dstPath = dst FilePath.</> entry
        isDir <- Directory.doesDirectoryExist srcPath
        if isDir
          then do
            Directory.createDirectoryIfMissing True dstPath
            copyDirectory srcPath dstPath
          else Directory.copyFile srcPath dstPath
    )

-- Tool result helpers
mkSuccess :: Text -> Aeson.Value
mkSuccess output =
  Aeson.object
    [ "success" .= True,
      "output" .= output
    ]

mkError :: Text -> Aeson.Value
mkError err =
  Aeson.object
    [ "success" .= False,
      "error" .= err
    ]

-- | Tool to load a skill's instructions
skillTool :: Text -> Engine.Tool
skillTool userName =
  Engine.Tool
    { Engine.toolName = "skill",
      Engine.toolDescription =
        "Load specialized instructions for a domain or task. "
          <> "Skills provide expert workflows, scripts, and context. "
          <> "Use list_skills to see available skills.",
      Engine.toolJsonSchema =
        Aeson.object
          [ "type" .= ("object" :: Text),
            "properties"
              .= Aeson.object
                [ "name"
                    .= Aeson.object
                      [ "type" .= ("string" :: Text),
                        "description" .= ("Name of the skill to load" :: Text)
                      ]
                ],
            "required" .= (["name"] :: [Text])
          ],
      Engine.toolExecute = executeSkill userName
    }

newtype SkillArgs = SkillArgs {skillArgsName :: Text}
  deriving (Show, Eq, Generic)

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

executeSkill :: Text -> Aeson.Value -> IO Aeson.Value
executeSkill userName v =
  case Aeson.fromJSON v of
    Aeson.Error e -> pure <| mkError (Text.pack e)
    Aeson.Success args -> do
      result <- loadSkill userName (skillArgsName args)
      case result of
        Left err -> pure <| mkError err
        Right skill ->
          pure
            <| Aeson.object
              [ "success" .= True,
                "skill" .= skillName skill,
                "description" .= skillDescription skill,
                "instructions" .= skillBody skill,
                "path" .= skillPath skill
              ]

-- | Tool to list available skills
listSkillsTool :: Text -> Engine.Tool
listSkillsTool userName =
  Engine.Tool
    { Engine.toolName = "list_skills",
      Engine.toolDescription = "List all available skills you can load.",
      Engine.toolJsonSchema =
        Aeson.object
          [ "type" .= ("object" :: Text),
            "properties" .= Aeson.object []
          ],
      Engine.toolExecute = \_ -> executeListSkills userName
    }

executeListSkills :: Text -> IO Aeson.Value
executeListSkills userName = do
  skills <- listSkillsForUser userName
  let formatted =
        Text.unlines
          <| map formatSkillMeta skills
  pure
    <| Aeson.object
      [ "success" .= True,
        "count" .= length skills,
        "skills" .= skills,
        "formatted" .= formatted
      ]
  where
    formatSkillMeta m =
      "- " <> skillMetaName m <> ": " <> skillMetaDescription m

-- | Tool to publish a skill to shared
publishSkillTool :: Text -> Engine.Tool
publishSkillTool userName =
  Engine.Tool
    { Engine.toolName = "publish_skill",
      Engine.toolDescription =
        "Publish one of your private skills to the shared skills directory "
          <> "so other users can access it.",
      Engine.toolJsonSchema =
        Aeson.object
          [ "type" .= ("object" :: Text),
            "properties"
              .= Aeson.object
                [ "name"
                    .= Aeson.object
                      [ "type" .= ("string" :: Text),
                        "description" .= ("Name of the skill to publish" :: Text)
                      ]
                ],
            "required" .= (["name"] :: [Text])
          ],
      Engine.toolExecute = executePublishSkill userName
    }

executePublishSkill :: Text -> Aeson.Value -> IO Aeson.Value
executePublishSkill userName v =
  case Aeson.fromJSON v of
    Aeson.Error e -> pure <| mkError (Text.pack e)
    Aeson.Success args -> do
      result <- publishSkill userName (skillArgsName args)
      case result of
        Left err -> pure <| mkError err
        Right msg -> pure <| mkSuccess msg