agentkit-context 0.2.2

Context loading for AGENTS.md files 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
482
483
484
//! Context loaders for workspace-local agent instructions.
//!
//! This crate discovers and loads `AGENTS.md` files (project-level
//! instructions) into [`agentkit_core::Item`]s with [`ItemKind::Context`]. The
//! resulting items slot directly into a transcript alongside system, user, and
//! assistant messages, so the agent loop and providers do not need a separate
//! context path.
//!
//! # Overview
//!
//! * [`AgentsMd`] -- walks ancestor directories to find `AGENTS.md` files.
//! * [`ContextLoader`] -- combines multiple [`ContextSource`] implementations
//!   and loads them in order.
//!
//! # Example
//!
//! ```rust,no_run
//! use agentkit_context::{AgentsMd, ContextLoader};
//!
//! # async fn run() -> Result<(), agentkit_context::ContextError> {
//! let items = ContextLoader::new()
//!     .with_source(AgentsMd::discover("."))
//!     .load()
//!     .await?;
//! # Ok(())
//! # }
//! ```

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

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

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

/// Controls how many `AGENTS.md` files [`AgentsMd`] returns during ancestor
/// discovery.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AgentsMdMode {
    /// Stop at the first (nearest) `AGENTS.md` found while walking upward.
    Nearest,
    /// Collect every `AGENTS.md` from the filesystem root down to the start
    /// directory, ordered from outermost to innermost.
    All,
}

/// A source of context [`Item`]s.
///
/// Implement this trait to create custom context loaders that can be plugged
/// into a [`ContextLoader`]. Each call to [`load`](ContextSource::load) should
/// return zero or more [`Item`]s with [`ItemKind::Context`].
#[async_trait]
pub trait ContextSource: Send + Sync {
    /// Load context items from this source.
    ///
    /// # Errors
    ///
    /// Returns [`ContextError`] if the underlying filesystem operations fail.
    async fn load(&self) -> Result<Vec<Item>, ContextError>;
}

/// Composable loader that gathers context [`Item`]s from multiple
/// [`ContextSource`] implementations.
///
/// Sources are loaded in the order they were added and the resulting items are
/// concatenated into a single `Vec<Item>`. These items carry
/// [`ItemKind::Context`] and can be prepended to the transcript before the
/// user message.
///
/// # Example
///
/// ```rust,no_run
/// use agentkit_context::{AgentsMd, ContextLoader};
///
/// # async fn run() -> Result<(), agentkit_context::ContextError> {
/// let items = ContextLoader::new()
///     .with_source(AgentsMd::discover("."))
///     .load()
///     .await?;
///
/// println!("loaded {} context items", items.len());
/// # Ok(())
/// # }
/// ```
#[derive(Default)]
pub struct ContextLoader {
    sources: Vec<Box<dyn ContextSource>>,
}

impl ContextLoader {
    /// Create an empty loader with no sources.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a [`ContextSource`] to this loader.
    ///
    /// Sources are loaded in the order they are added. This method consumes
    /// and returns `self` so calls can be chained.
    pub fn with_source(mut self, source: impl ContextSource + 'static) -> Self {
        self.sources.push(Box::new(source));
        self
    }

    /// Load all registered sources and return a combined list of context
    /// [`Item`]s.
    ///
    /// # Errors
    ///
    /// Returns the first [`ContextError`] encountered while loading. Sources
    /// that appear before the failing source will have already been loaded.
    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)
    }
}

/// Discovers and loads `AGENTS.md` files by walking ancestor directories.
///
/// `AgentsMd` is the primary way to inject project-level instructions into an
/// agent session. It walks upward from a given starting directory, collecting
/// `AGENTS.md` files according to the configured [`AgentsMdMode`]. Explicit
/// paths and extra search directories can be added for cases that fall outside
/// simple ancestor discovery.
///
/// Loaded items carry metadata under the `agentkit.context.*` namespace:
///
/// | Key                        | Value                         |
/// |----------------------------|-------------------------------|
/// | `agentkit.context.source`  | `"agents_md"`                 |
/// | `agentkit.context.path`    | Filesystem path of the file   |
///
/// # Example
///
/// ```rust,no_run
/// use agentkit_context::AgentsMd;
/// use agentkit_context::ContextSource; // for `.load()`
///
/// # async fn run() -> Result<(), agentkit_context::ContextError> {
/// // Find the nearest AGENTS.md starting from the current directory.
/// let items = AgentsMd::discover(".").load().await?;
///
/// // Or collect all ancestor AGENTS.md files, with an extra search dir.
/// let items = AgentsMd::discover_all(".")
///     .with_search_dir("./.agent")
///     .load()
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct AgentsMd {
    start_dir: PathBuf,
    mode: AgentsMdMode,
    file_name: String,
    explicit_paths: Vec<PathBuf>,
    search_dirs: Vec<PathBuf>,
}

impl AgentsMd {
    /// Create a new `AgentsMd` that searches for the nearest `AGENTS.md`
    /// starting from `start_dir` and walking upward.
    ///
    /// This uses [`AgentsMdMode::Nearest`] by default. Call
    /// [`with_mode`](Self::with_mode) or use [`discover_all`](Self::discover_all)
    /// to collect every ancestor match instead.
    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(),
        }
    }

    /// Shorthand for `AgentsMd::discover(start_dir).with_mode(AgentsMdMode::All)`.
    ///
    /// Collects every `AGENTS.md` from the filesystem root down to `start_dir`,
    /// ordered outermost-first so that more specific instructions appear last.
    pub fn discover_all(start_dir: impl Into<PathBuf>) -> Self {
        Self::discover(start_dir).with_mode(AgentsMdMode::All)
    }

    /// Set the discovery mode.
    ///
    /// See [`AgentsMdMode`] for the available options.
    pub fn with_mode(mut self, mode: AgentsMdMode) -> Self {
        self.mode = mode;
        self
    }

    /// Override the file name to look for (default: `AGENTS.md`).
    ///
    /// Useful when a project uses a different convention such as `CLAUDE.md`.
    pub fn with_file_name(mut self, file_name: impl Into<String>) -> Self {
        self.file_name = file_name.into();
        self
    }

    /// Add an explicit file path to include.
    ///
    /// The path is checked for existence at load time; if it does not exist it
    /// is silently skipped. Explicit paths are loaded before ancestor discovery
    /// results.
    pub fn with_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.explicit_paths.push(path.into());
        self
    }

    /// Add a directory to search for the configured file name.
    ///
    /// Unlike ancestor discovery, this checks only the given directory (not its
    /// ancestors). This is useful for well-known sidecar locations like
    /// `.agent/` or `.config/`.
    pub fn with_search_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.search_dirs.push(dir.into());
        self
    }

    /// Resolve the first matching path without reading its contents.
    ///
    /// Returns `None` when no `AGENTS.md` file is found. This is a convenience
    /// wrapper around [`resolve_all`](Self::resolve_all).
    ///
    /// # Errors
    ///
    /// Returns [`ContextError`] if a filesystem metadata check fails.
    pub async fn resolve(&self) -> Result<Option<PathBuf>, ContextError> {
        Ok(self.resolve_all().await?.into_iter().next())
    }

    /// Resolve all matching paths without reading their contents.
    ///
    /// The returned paths are deduplicated and ordered from outermost to
    /// innermost. When the mode is [`AgentsMdMode::Nearest`], at most one path
    /// is returned.
    ///
    /// # Errors
    ///
    /// Returns [`ContextError`] if a filesystem metadata check fails.
    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)
    }
}

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)
}

/// Errors that can occur while discovering or reading context files.
#[derive(Debug, Error)]
pub enum ContextError {
    /// A filesystem metadata or directory-listing operation failed.
    ///
    /// This typically means the path exists but is not accessible (permission
    /// denied, broken symlink, etc.).
    #[error("failed to inspect {path}: {error}")]
    InspectFailed {
        /// The path that could not be inspected.
        path: PathBuf,
        /// The underlying I/O error.
        #[source]
        error: std::io::Error,
    },
    /// Reading the contents of a discovered file failed.
    #[error("failed to read {path}: {error}")]
    ReadFailed {
        /// The path that could not be read.
        path: PathBuf,
        /// The underlying I/O error.
        #[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();
    }

    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}"))
    }
}