agentkit-context 0.1.0

Context loading for AGENTS.md files and skills directories in agentkit.
Documentation
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
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

use agentkit_core::{Item, ItemKind, MetadataMap, Part, TextPart};
use async_trait::async_trait;
use futures_lite::StreamExt;
use serde_json::Value;
use thiserror::Error;

const DEFAULT_AGENTS_FILE: &str = "AGENTS.md";
const DEFAULT_SKILL_FILE: &str = "SKILL.md";

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AgentsMdMode {
    Nearest,
    All,
}

#[async_trait]
pub trait ContextSource: Send + Sync {
    async fn load(&self) -> Result<Vec<Item>, ContextError>;
}

#[derive(Default)]
pub struct ContextLoader {
    sources: Vec<Box<dyn ContextSource>>,
}

impl ContextLoader {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_source(mut self, source: impl ContextSource + 'static) -> Self {
        self.sources.push(Box::new(source));
        self
    }

    pub async fn load(&self) -> Result<Vec<Item>, ContextError> {
        let mut items = Vec::new();

        for source in &self.sources {
            items.extend(source.load().await?);
        }

        Ok(items)
    }
}

#[derive(Clone, Debug)]
pub struct AgentsMd {
    start_dir: PathBuf,
    mode: AgentsMdMode,
    file_name: String,
    explicit_paths: Vec<PathBuf>,
    search_dirs: Vec<PathBuf>,
}

impl AgentsMd {
    pub fn discover(start_dir: impl Into<PathBuf>) -> Self {
        Self {
            start_dir: start_dir.into(),
            mode: AgentsMdMode::Nearest,
            file_name: DEFAULT_AGENTS_FILE.into(),
            explicit_paths: Vec::new(),
            search_dirs: Vec::new(),
        }
    }

    pub fn discover_all(start_dir: impl Into<PathBuf>) -> Self {
        Self::discover(start_dir).with_mode(AgentsMdMode::All)
    }

    pub fn with_mode(mut self, mode: AgentsMdMode) -> Self {
        self.mode = mode;
        self
    }

    pub fn with_file_name(mut self, file_name: impl Into<String>) -> Self {
        self.file_name = file_name.into();
        self
    }

    pub fn with_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.explicit_paths.push(path.into());
        self
    }

    pub fn with_search_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.search_dirs.push(dir.into());
        self
    }

    pub async fn resolve(&self) -> Result<Option<PathBuf>, ContextError> {
        Ok(self.resolve_all().await?.into_iter().next())
    }

    pub async fn resolve_all(&self) -> Result<Vec<PathBuf>, ContextError> {
        let mut paths = Vec::new();

        for path in &self.explicit_paths {
            if path_exists(path).await? {
                paths.push(path.clone());
            }
        }

        for dir in &self.search_dirs {
            let candidate = dir.join(&self.file_name);
            if path_exists(&candidate).await? {
                paths.push(candidate);
            }
        }

        paths.extend(
            find_in_ancestors_with_mode(
                &self.start_dir,
                &self.file_name,
                self.mode == AgentsMdMode::All,
            )
            .await?,
        );

        let mut seen = BTreeSet::new();
        paths.retain(|path| seen.insert(path.clone()));
        if self.mode == AgentsMdMode::Nearest {
            Ok(paths.into_iter().rev().take(1).collect())
        } else {
            Ok(paths)
        }
    }
}

#[async_trait]
impl ContextSource for AgentsMd {
    async fn load(&self) -> Result<Vec<Item>, ContextError> {
        let paths = self.resolve_all().await?;
        let mut items = Vec::with_capacity(paths.len());

        for path in paths {
            let body = async_fs::read_to_string(&path).await.map_err(|error| {
                ContextError::ReadFailed {
                    path: path.clone(),
                    error,
                }
            })?;

            items.push(context_item(
                format!(
                    "[Loaded AGENTS]\nPath: {}\n\n{}",
                    path.display(),
                    body.trim_end()
                ),
                metadata_for("agents_md", &path, None),
            ));
        }

        Ok(items)
    }
}

#[derive(Clone, Debug)]
pub struct SkillsDirectory {
    roots: Vec<PathBuf>,
    skill_file_name: String,
}

impl SkillsDirectory {
    pub fn from_dir(root: impl Into<PathBuf>) -> Self {
        Self {
            roots: vec![root.into()],
            skill_file_name: DEFAULT_SKILL_FILE.into(),
        }
    }

    pub fn with_dir(mut self, root: impl Into<PathBuf>) -> Self {
        self.roots.push(root.into());
        self
    }

    pub fn with_skill_file_name(mut self, skill_file_name: impl Into<String>) -> Self {
        self.skill_file_name = skill_file_name.into();
        self
    }
}

#[async_trait]
impl ContextSource for SkillsDirectory {
    async fn load(&self) -> Result<Vec<Item>, ContextError> {
        let mut skill_paths = Vec::new();
        for root in &self.roots {
            if !path_exists(root).await? {
                continue;
            }
            skill_paths.extend(collect_skill_files(root, &self.skill_file_name).await?);
        }
        skill_paths.sort();
        skill_paths.dedup();

        let mut items = Vec::with_capacity(skill_paths.len());

        for path in skill_paths {
            let body = async_fs::read_to_string(&path).await.map_err(|error| {
                ContextError::ReadFailed {
                    path: path.clone(),
                    error,
                }
            })?;
            let skill_name = path
                .parent()
                .and_then(Path::file_name)
                .map(|value| value.to_string_lossy().into_owned());

            items.push(context_item(
                format!(
                    "[Loaded Skill]\nName: {}\nPath: {}\n\n{}",
                    skill_name.clone().unwrap_or_else(|| "unknown".into()),
                    path.display(),
                    body.trim_end()
                ),
                metadata_for("skill", &path, skill_name),
            ));
        }

        Ok(items)
    }
}

fn context_item(text: String, metadata: MetadataMap) -> Item {
    Item {
        id: None,
        kind: ItemKind::Context,
        parts: vec![Part::Text(TextPart {
            text,
            metadata: MetadataMap::new(),
        })],
        metadata,
    }
}

fn metadata_for(source_kind: &str, path: &Path, name: Option<String>) -> MetadataMap {
    let mut metadata = MetadataMap::new();
    metadata.insert(
        "agentkit.context.source".into(),
        Value::String(source_kind.into()),
    );
    metadata.insert(
        "agentkit.context.path".into(),
        Value::String(path.display().to_string()),
    );
    if let Some(name) = name {
        metadata.insert("agentkit.context.name".into(), Value::String(name));
    }
    metadata
}

async fn path_exists(path: &Path) -> Result<bool, ContextError> {
    match async_fs::metadata(path).await {
        Ok(_) => Ok(true),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(error) => Err(ContextError::InspectFailed {
            path: path.to_path_buf(),
            error,
        }),
    }
}

async fn find_in_ancestors_with_mode(
    start_dir: &Path,
    file_name: &str,
    include_all: bool,
) -> Result<Vec<PathBuf>, ContextError> {
    let mut current = start_dir.to_path_buf();
    let mut matches = Vec::new();

    loop {
        let candidate = current.join(file_name);
        if path_exists(&candidate).await? {
            matches.push(candidate);
            if !include_all {
                break;
            }
        }
        let Some(parent) = current.parent() else {
            break;
        };
        current = parent.to_path_buf();
    }

    matches.reverse();
    Ok(matches)
}

async fn collect_skill_files(
    root: &Path,
    skill_file_name: &str,
) -> Result<Vec<PathBuf>, ContextError> {
    let mut pending = vec![root.to_path_buf()];
    let mut skill_paths = Vec::new();

    while let Some(dir_path) = pending.pop() {
        let mut read_dir =
            async_fs::read_dir(&dir_path)
                .await
                .map_err(|error| ContextError::InspectFailed {
                    path: dir_path.clone(),
                    error,
                })?;

        while let Some(entry) = read_dir.next().await {
            let entry = entry.map_err(|error| ContextError::InspectFailed {
                path: dir_path.clone(),
                error,
            })?;
            let path = entry.path();
            let file_type =
                entry
                    .file_type()
                    .await
                    .map_err(|error| ContextError::InspectFailed {
                        path: path.clone(),
                        error,
                    })?;

            if file_type.is_dir() {
                pending.push(path);
                continue;
            }

            if file_type.is_file() && path.file_name().is_some_and(|name| name == skill_file_name) {
                skill_paths.push(path);
            }
        }
    }

    skill_paths.sort();
    Ok(skill_paths)
}

#[derive(Debug, Error)]
pub enum ContextError {
    #[error("failed to inspect {path}: {error}")]
    InspectFailed {
        path: PathBuf,
        #[source]
        error: std::io::Error,
    },
    #[error("failed to read {path}: {error}")]
    ReadFailed {
        path: PathBuf,
        #[source]
        error: std::io::Error,
    },
}

#[cfg(test)]
mod tests {
    use std::time::{SystemTime, UNIX_EPOCH};

    use super::*;

    #[tokio::test]
    async fn discovers_agents_file_in_ancestors() {
        let root = temp_path("agentkit-context-agents");
        let nested = root.join("nested/project");
        async_fs::create_dir_all(&nested).await.unwrap();
        let agents_path = root.join("AGENTS.md");
        async_fs::write(&agents_path, "project = lantern")
            .await
            .unwrap();

        let items = AgentsMd::discover(&nested).load().await.unwrap();
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].kind, ItemKind::Context);
        assert_eq!(
            items[0].metadata.get("agentkit.context.source"),
            Some(&Value::String("agents_md".into()))
        );

        async_fs::remove_dir_all(&root).await.unwrap();
    }

    #[tokio::test]
    async fn discovers_all_agents_files_when_requested() {
        let root = temp_path("agentkit-context-agents-all");
        let nested = root.join("nested/project");
        async_fs::create_dir_all(&nested).await.unwrap();
        async_fs::write(root.join("AGENTS.md"), "project = lantern")
            .await
            .unwrap();
        async_fs::write(root.join("nested/AGENTS.md"), "team = orbit")
            .await
            .unwrap();

        let items = AgentsMd::discover_all(&nested).load().await.unwrap();
        assert_eq!(items.len(), 2);

        async_fs::remove_dir_all(&root).await.unwrap();
    }

    #[tokio::test]
    async fn loads_agents_from_explicit_search_paths() {
        let root = temp_path("agentkit-context-agents-explicit");
        let nested = root.join("nested/project");
        let shared = root.join("shared");
        async_fs::create_dir_all(&nested).await.unwrap();
        async_fs::create_dir_all(&shared).await.unwrap();
        async_fs::write(shared.join("AGENTS.md"), "policy = explicit")
            .await
            .unwrap();

        let items = AgentsMd::discover(&nested)
            .with_search_dir(&shared)
            .load()
            .await
            .unwrap();
        assert_eq!(items.len(), 1);
        assert!(
            items[0]
                .metadata
                .get("agentkit.context.path")
                .and_then(Value::as_str)
                .is_some_and(|path| path.ends_with("/shared/AGENTS.md"))
        );

        async_fs::remove_dir_all(&root).await.unwrap();
    }

    #[tokio::test]
    async fn loads_skills_recursively() {
        let root = temp_path("agentkit-context-skills");
        let skill_dir = root.join("skills/release-notes");
        async_fs::create_dir_all(&skill_dir).await.unwrap();
        async_fs::write(skill_dir.join("SKILL.md"), "# Release Notes")
            .await
            .unwrap();

        let items = SkillsDirectory::from_dir(root.join("skills"))
            .load()
            .await
            .unwrap();
        assert_eq!(items.len(), 1);
        assert_eq!(
            items[0].metadata.get("agentkit.context.name"),
            Some(&Value::String("release-notes".into()))
        );

        async_fs::remove_dir_all(&root).await.unwrap();
    }

    #[tokio::test]
    async fn loads_skills_from_multiple_roots() {
        let root = temp_path("agentkit-context-skills-multi");
        let root_a = root.join("skills-a/release-notes");
        let root_b = root.join("skills-b/deploy");
        async_fs::create_dir_all(&root_a).await.unwrap();
        async_fs::create_dir_all(&root_b).await.unwrap();
        async_fs::write(root_a.join("SKILL.md"), "# Release Notes")
            .await
            .unwrap();
        async_fs::write(root_b.join("SKILL.md"), "# Deploy")
            .await
            .unwrap();

        let items = SkillsDirectory::from_dir(root.join("skills-a"))
            .with_dir(root.join("skills-b"))
            .load()
            .await
            .unwrap();
        assert_eq!(items.len(), 2);

        async_fs::remove_dir_all(&root).await.unwrap();
    }

    fn temp_path(prefix: &str) -> PathBuf {
        let suffix = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        std::env::temp_dir().join(format!("{prefix}-{suffix}"))
    }
}