agent-plugins 0.1.1

Sans-IO implementation of the Agent Plugins specification (agent-plugins.org): load, validate, and prepare agent plugins from any IO
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
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! The sans-IO loader: a conversation, not a filesystem walk.
//!
//! [`Loading`] is a state machine that knows the Agent Plugins specification
//! and nothing about IO. It asks [`Question`]s — *what kind of entry is
//! `plugin.json`? read it for me; list `skills/`* — and you feed back
//! [`Answer`]s from wherever the plugin actually lives: a directory, a
//! tarball, an in-memory map, an object store, an async runtime. The machine
//! sequences the spec; the caller owns every byte of IO.
//!
//! ```no_run
//! use agent_plugins::{Answer, Loading, Question};
//!
//! let mut loading = Loading::start();
//! while let Some(question) = loading.question() {
//!     let answer: Answer = match question {
//!         Question::Kind(path) => todo!("stat {path}"),
//!         Question::Confined(path) => todo!("does {path} resolve inside the root?"),
//!         Question::Read(path) => todo!("read {path}"),
//!         Question::List(path) => todo!("list {path}"),
//!     };
//!     loading.answer(answer)?;
//! }
//! let outcome = loading.finish();
//! # Ok::<(), agent_plugins::AnswerMismatch>(())
//! ```
//!
//! Every failure lands on the narrowest boundary §4.1 and §11.3 allow: a bad
//! manifest rejects the plugin, a bad `mcp.json` disables one component type,
//! a bad skill or server entry skips only itself — each recorded as a
//! [`Diagnostic`](crate::Diagnostic).

use std::collections::VecDeque;
use std::fmt;

use crate::diag::{Diagnostic, Origin, Rule};
use crate::manifest::{Manifest, ManifestRejection};
use crate::mcp::{McpConfig, McpDisabledReason};
use crate::path::PackagePath;
use crate::skill::{parse_skill_md, Skill};

/// What kind of entry a package path resolves to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileKind {
    /// A regular file (or a symlink resolving to one).
    File,
    /// A directory (or a symlink resolving to one).
    Directory,
    /// Anything else — sockets, devices, dangling links.
    Other,
}

/// One entry from a directory listing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirEntry {
    /// The entry's name within its directory (no separators).
    pub name: String,
    /// What the entry resolves to.
    pub kind: FileKind,
}

impl DirEntry {
    /// A directory entry with the given name and kind.
    pub fn new(name: impl Into<String>, kind: FileKind) -> Self {
        Self { name: name.into(), kind }
    }
}

/// A question the loader needs answered before it can continue.
///
/// Deliberately exhaustive: a driver must answer every kind of question, so
/// a new kind would rightly be a breaking change.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Question {
    /// What kind of entry is this path? Follow symlinks; answer
    /// `Answer::Kind(None)` if it does not exist.
    Kind(PackagePath),
    /// Does this path, fully resolved (symlinks and all), stay within the
    /// filesystem-resolved plugin root? Sources without links — archives,
    /// memory maps — truthfully answer `true` (§4.1).
    Confined(PackagePath),
    /// Read the file's bytes.
    Read(PackagePath),
    /// List the directory's immediate entries. Order is up to the source;
    /// sort for reproducible output.
    List(PackagePath),
}

impl Question {
    /// The package path this question is about.
    pub fn path(&self) -> &PackagePath {
        match self {
            Self::Kind(p) | Self::Confined(p) | Self::Read(p) | Self::List(p) => p,
        }
    }
}

impl fmt::Display for Question {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Kind(p) => write!(f, "kind of {p}"),
            Self::Confined(p) => write!(f, "confinement of {p}"),
            Self::Read(p) => write!(f, "contents of {p}"),
            Self::List(p) => write!(f, "entries of {p}"),
        }
    }
}

/// The caller's reply to the pending [`Question`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Answer {
    /// Reply to [`Question::Kind`]; `None` means the path does not exist.
    Kind(Option<FileKind>),
    /// Reply to [`Question::Confined`].
    Confined(bool),
    /// Reply to [`Question::Read`].
    Bytes(Vec<u8>),
    /// Reply to [`Question::List`].
    Entries(Vec<DirEntry>),
    /// Reply to any question the source could not answer. The loader applies
    /// the narrowest failure boundary the spec allows for that question.
    Unavailable {
        /// The source's explanation, carried into diagnostics.
        detail: String,
    },
}

/// The reply did not match the pending question — a driver bug, not a plugin
/// problem.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnswerMismatch {
    /// What the loader had asked, if anything.
    pub expected: Option<&'static str>,
    /// What the reply was.
    pub got: &'static str,
}

impl fmt::Display for AnswerMismatch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.expected {
            Some(expected) => write!(
                f,
                "answer {got} does not match the pending question ({expected} expected)",
                got = self.got
            ),
            None => write!(f, "answer {} arrived with no question pending", self.got),
        }
    }
}

impl std::error::Error for AnswerMismatch {}

/// A fully loaded plugin: the §11.1 conformance outcome.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct LoadedPlugin {
    /// The validated manifest.
    pub manifest: Manifest,
    /// Valid skills, in discovery order.
    pub skills: Vec<Skill>,
    /// The MCP component's fate.
    pub mcp: McpOutcome,
    /// Everything non-fatal the loader decided along the way.
    pub diagnostics: Vec<Diagnostic>,
}

/// What became of the MCP component type (§6.2, §7.2.2).
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum McpOutcome {
    /// No `mcp.json` — expressly not an error (§6.2).
    Absent,
    /// MCP is disabled for this plugin; other components loaded on (§7.2.2).
    Disabled(McpDisabledReason),
    /// Valid configuration; individually invalid entries were skipped.
    Configured(McpConfig),
}

/// The plugin was rejected outright — nothing may be discovered or executed
/// (§5.2, §5.3, §4.1 rule 1).
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Rejection {
    /// No `plugin.json` at the plugin root (§5.1).
    ManifestMissing,
    /// `plugin.json` is not a regular file.
    ManifestNotAFile,
    /// `plugin.json` resolves outside the plugin root (§4.1 rule 1).
    ManifestEscapes,
    /// The manifest failed validation fatally (§5.2, §5.3, §5.5).
    Manifest(ManifestRejection),
    /// The IO source failed while the manifest was still in question.
    Source {
        /// The source's explanation.
        detail: String,
    },
    /// [`Loading::finish`] was called before the conversation ended.
    Incomplete,
}

impl fmt::Display for Rejection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ManifestMissing => f.write_str("no plugin.json at the plugin root (§5.1)"),
            Self::ManifestNotAFile => f.write_str("plugin.json is not a regular file"),
            Self::ManifestEscapes => {
                f.write_str("plugin.json resolves outside the plugin root (§4.1)")
            }
            Self::Manifest(rejection) => write!(f, "manifest rejected: {rejection}"),
            Self::Source { detail } => write!(f, "IO source failed: {detail}"),
            Self::Incomplete => f.write_str("loading finished before the machine was done"),
        }
    }
}

impl std::error::Error for Rejection {}

impl Rejection {
    /// Stable machine-readable code for this rejection, shared with the
    /// TypeScript implementation and the conformance fixtures.
    pub fn code(&self) -> &'static str {
        match self {
            Self::ManifestMissing => "manifest-missing",
            Self::ManifestNotAFile => "manifest-not-a-file",
            Self::ManifestEscapes => "manifest-escapes",
            Self::Manifest(ManifestRejection::UnsupportedSchema { .. }) => "unsupported-schema",
            Self::Manifest(_) => "invalid-manifest",
            Self::Source { .. } => "source-error",
            Self::Incomplete => "incomplete",
        }
    }
}

enum State {
    ManifestKind,
    ManifestConfined,
    ManifestRead,
    SkillsKind,
    SkillsConfined,
    SkillsList,
    SkillKind {
        current: String,
    },
    SkillConfined {
        current: String,
    },
    SkillRead {
        current: String,
    },
    McpKind,
    McpConfined,
    McpRead,
    Done(Box<Result<LoadedPlugin, Rejection>>),
    /// Transient marker while ownership moves between states.
    Poisoned,
}

/// The Agent Plugins loading conversation.
///
/// Ask [`question`](Self::question), reply with [`answer`](Self::answer),
/// repeat until there is no question left, then [`finish`](Self::finish).
pub struct Loading {
    state: State,
    manifest: Option<Manifest>,
    skills: Vec<Skill>,
    skill_queue: VecDeque<String>,
    diagnostics: Vec<Diagnostic>,
}

impl Loading {
    /// Begin loading a plugin.
    pub fn start() -> Self {
        Self {
            state: State::ManifestKind,
            manifest: None,
            skills: Vec::new(),
            skill_queue: VecDeque::new(),
            diagnostics: Vec::new(),
        }
    }

    /// The pending question, or `None` when the conversation is over and
    /// [`finish`](Self::finish) may be called. Idempotent.
    pub fn question(&self) -> Option<Question> {
        let path = |s: &str| PackagePath::new(s);
        Some(match &self.state {
            State::ManifestKind => Question::Kind(path("plugin.json")),
            State::ManifestConfined => Question::Confined(path("plugin.json")),
            State::ManifestRead => Question::Read(path("plugin.json")),
            State::SkillsKind => Question::Kind(path("skills")),
            State::SkillsConfined => Question::Confined(path("skills")),
            State::SkillsList => Question::List(path("skills")),
            State::SkillKind { current } => Question::Kind(skill_md(current)),
            State::SkillConfined { current } => Question::Confined(skill_md(current)),
            State::SkillRead { current } => Question::Read(skill_md(current)),
            State::McpKind => Question::Kind(path("mcp.json")),
            State::McpConfined => Question::Confined(path("mcp.json")),
            State::McpRead => Question::Read(path("mcp.json")),
            State::Done(_) | State::Poisoned => return None,
        })
    }

    /// Answer the pending question and advance.
    pub fn answer(&mut self, answer: Answer) -> Result<(), AnswerMismatch> {
        let state = std::mem::replace(&mut self.state, State::Poisoned);
        let (next, verdict) = self.transition(state, answer);
        self.state = next;
        verdict
    }

    /// Conclude the conversation. Returns [`Rejection::Incomplete`] if
    /// questions remain unanswered.
    pub fn finish(self) -> Result<LoadedPlugin, Rejection> {
        match self.state {
            State::Done(outcome) => *outcome,
            _ => Err(Rejection::Incomplete),
        }
    }

    fn transition(&mut self, state: State, answer: Answer) -> (State, Result<(), AnswerMismatch>) {
        use Answer as A;
        use State as S;

        let mismatch = |expected: &'static str, got: &Answer| AnswerMismatch {
            expected: Some(expected),
            got: match got {
                A::Kind(_) => "Kind",
                A::Confined(_) => "Confined",
                A::Bytes(_) => "Bytes",
                A::Entries(_) => "Entries",
                A::Unavailable { .. } => "Unavailable",
            },
        };

        let next = match state {
            // ---- plugin.json: every failure here rejects the plugin ----
            S::ManifestKind => match answer {
                A::Kind(Some(FileKind::File)) => S::ManifestConfined,
                A::Kind(None) => S::Done(Box::new(Err(Rejection::ManifestMissing))),
                A::Kind(Some(_)) => S::Done(Box::new(Err(Rejection::ManifestNotAFile))),
                A::Unavailable { detail } => S::Done(Box::new(Err(Rejection::Source { detail }))),
                other => return (S::ManifestKind, Err(mismatch("Kind", &other))),
            },
            S::ManifestConfined => match answer {
                A::Confined(true) => S::ManifestRead,
                A::Confined(false) => S::Done(Box::new(Err(Rejection::ManifestEscapes))),
                A::Unavailable { detail } => S::Done(Box::new(Err(Rejection::Source { detail }))),
                other => return (S::ManifestConfined, Err(mismatch("Confined", &other))),
            },
            S::ManifestRead => match answer {
                A::Bytes(bytes) => match Manifest::parse(&bytes) {
                    Ok((manifest, mut diags)) => {
                        self.manifest = Some(manifest);
                        self.diagnostics.append(&mut diags);
                        S::SkillsKind
                    }
                    Err(rejection) => S::Done(Box::new(Err(Rejection::Manifest(rejection)))),
                },
                A::Unavailable { detail } => S::Done(Box::new(Err(Rejection::Source { detail }))),
                other => return (S::ManifestRead, Err(mismatch("Bytes", &other))),
            },

            // ---- skills/: failures narrow to the component or one skill ----
            S::SkillsKind => match answer {
                A::Kind(Some(FileKind::Directory)) => S::SkillsConfined,
                A::Kind(None) => S::McpKind, // absent is not an error (§6.2)
                A::Kind(Some(_)) => {
                    self.report(
                        Rule::ComponentInvalid,
                        Origin::Skills,
                        "`skills` exists but is not a directory (§6.2)",
                    );
                    S::McpKind
                }
                A::Unavailable { detail } => {
                    self.report(Rule::ComponentInvalid, Origin::Skills, detail);
                    S::McpKind
                }
                other => return (S::SkillsKind, Err(mismatch("Kind", &other))),
            },
            S::SkillsConfined => match answer {
                A::Confined(true) => S::SkillsList,
                A::Confined(false) => {
                    self.report(
                        Rule::ComponentInvalid,
                        Origin::Skills,
                        "`skills` resolves outside the plugin root (§4.1)",
                    );
                    S::McpKind
                }
                A::Unavailable { detail } => {
                    self.report(Rule::ComponentInvalid, Origin::Skills, detail);
                    S::McpKind
                }
                other => return (S::SkillsConfined, Err(mismatch("Confined", &other))),
            },
            S::SkillsList => match answer {
                A::Entries(entries) => {
                    // §7.1: each *immediate child directory* may hold one
                    // skill; files and deeper descendants are never searched.
                    self.skill_queue = entries
                        .into_iter()
                        .filter(|e| e.kind == FileKind::Directory)
                        .map(|e| e.name)
                        .collect();
                    self.next_skill()
                }
                A::Unavailable { detail } => {
                    self.report(Rule::ComponentInvalid, Origin::Skills, detail);
                    S::McpKind
                }
                other => return (S::SkillsList, Err(mismatch("Entries", &other))),
            },
            S::SkillKind { current } => match answer {
                A::Kind(Some(FileKind::File)) => S::SkillConfined { current },
                // No SKILL.md, or not a regular file: simply not a skill (§7.1).
                A::Kind(_) => self.next_skill(),
                A::Unavailable { detail } => {
                    self.skip_skill(&current, detail);
                    self.next_skill()
                }
                other => return (S::SkillKind { current }, Err(mismatch("Kind", &other))),
            },
            S::SkillConfined { current } => match answer {
                A::Confined(true) => S::SkillRead { current },
                A::Confined(false) => {
                    self.skip_skill(
                        &current,
                        "SKILL.md resolves outside the plugin root (§4.1)".to_owned(),
                    );
                    self.next_skill()
                }
                A::Unavailable { detail } => {
                    self.skip_skill(&current, detail);
                    self.next_skill()
                }
                other => return (S::SkillConfined { current }, Err(mismatch("Confined", &other))),
            },
            S::SkillRead { current } => match answer {
                A::Bytes(bytes) => {
                    match parse_skill_md(&current, &bytes) {
                        Ok((meta, body)) => self.skills.push(Skill {
                            directory: current.clone(),
                            path: PackagePath::new("skills").child(&current),
                            meta,
                            body,
                        }),
                        Err(why) => self.skip_skill(&current, why.to_string()),
                    }
                    self.next_skill()
                }
                A::Unavailable { detail } => {
                    self.skip_skill(&current, detail);
                    self.next_skill()
                }
                other => return (S::SkillRead { current }, Err(mismatch("Bytes", &other))),
            },

            // ---- mcp.json: failures disable MCP, never the plugin ----
            S::McpKind => match answer {
                A::Kind(Some(FileKind::File)) => S::McpConfined,
                A::Kind(None) => self.done(McpOutcome::Absent),
                A::Kind(Some(_)) => {
                    self.report(
                        Rule::ComponentInvalid,
                        Origin::Mcp,
                        "`mcp.json` exists but is not a regular file (§6.2)",
                    );
                    self.done(McpOutcome::Disabled(McpDisabledReason::NotAFile))
                }
                A::Unavailable { detail } => {
                    let reason = McpDisabledReason::Unavailable { detail };
                    self.report(Rule::McpDisabled, Origin::Mcp, reason.to_string());
                    self.done(McpOutcome::Disabled(reason))
                }
                other => return (S::McpKind, Err(mismatch("Kind", &other))),
            },
            S::McpConfined => match answer {
                A::Confined(true) => S::McpRead,
                A::Confined(false) => {
                    self.report(
                        Rule::ComponentInvalid,
                        Origin::Mcp,
                        "`mcp.json` resolves outside the plugin root (§4.1)",
                    );
                    self.done(McpOutcome::Disabled(McpDisabledReason::LocationEscapes))
                }
                A::Unavailable { detail } => {
                    let reason = McpDisabledReason::Unavailable { detail };
                    self.report(Rule::McpDisabled, Origin::Mcp, reason.to_string());
                    self.done(McpOutcome::Disabled(reason))
                }
                other => return (S::McpConfined, Err(mismatch("Confined", &other))),
            },
            S::McpRead => match answer {
                A::Bytes(bytes) => {
                    let spec =
                        self.manifest.as_ref().expect("manifest parsed before MCP phase").spec;
                    match McpConfig::parse(&bytes, spec) {
                        Ok((config, mut diags)) => {
                            self.diagnostics.append(&mut diags);
                            self.done(McpOutcome::Configured(config))
                        }
                        Err(reason) => {
                            self.report(Rule::McpDisabled, Origin::Mcp, reason.to_string());
                            self.done(McpOutcome::Disabled(reason))
                        }
                    }
                }
                A::Unavailable { detail } => {
                    let reason = McpDisabledReason::Unavailable { detail };
                    self.report(Rule::McpDisabled, Origin::Mcp, reason.to_string());
                    self.done(McpOutcome::Disabled(reason))
                }
                other => return (S::McpRead, Err(mismatch("Bytes", &other))),
            },

            S::Done(outcome) => {
                let got = mismatch("nothing", &answer);
                return (S::Done(outcome), Err(AnswerMismatch { expected: None, got: got.got }));
            }
            S::Poisoned => unreachable!("Loading state invariant broken"),
        };
        (next, Ok(()))
    }

    fn next_skill(&mut self) -> State {
        match self.skill_queue.pop_front() {
            Some(current) => State::SkillKind { current },
            None => State::McpKind,
        }
    }

    fn report(&mut self, rule: Rule, origin: Origin, message: impl Into<String>) {
        self.diagnostics.push(Diagnostic::new(rule, origin, message));
    }

    fn skip_skill(&mut self, directory: &str, why: String) {
        self.report(
            Rule::SkillSkipped,
            Origin::Skill(directory.to_owned()),
            format!("skill skipped (§7.1): {why}"),
        );
    }

    fn done(&mut self, mcp: McpOutcome) -> State {
        State::Done(Box::new(Ok(LoadedPlugin {
            manifest: self.manifest.take().expect("manifest parsed before completion"),
            skills: std::mem::take(&mut self.skills),
            mcp,
            diagnostics: std::mem::take(&mut self.diagnostics),
        })))
    }
}

fn skill_md(directory: &str) -> PackagePath {
    PackagePath::new("skills").child(directory).child("SKILL.md")
}

impl fmt::Debug for Loading {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Loading")
            .field("pending", &self.question())
            .field("skills_loaded", &self.skills.len())
            .field("diagnostics", &self.diagnostics.len())
            .finish_non_exhaustive()
    }
}