agentd-core 1.3.4

Minimal, MCP-native agent runtime as a library: the agentic loop, supervisor, workflows, and code-registered tools (the agentd engine)
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
// SPDX-License-Identifier: AGPL-3.0-only
//! **Skills**: named instruction bundles — the SKILL.md idiom —
//! discovered from MCP servers as **prompts** (`prompts/list` = catalogue,
//! `prompts/get` = body) or **resources** (`skill://<name>` URIs or
//! `mimeType: text/x-skill+markdown`), referenced as `@skill:<name>` in the
//! instruction, a step, or a chat message, and **preloaded** into the calling
//! context (progressive disclosure: the catalogue is always visible, a body
//! only when referenced or `skills.load`ed). Bodies are cached by hash, never
//! stored; the loaded set `[{name, hash}]` is part of the context record.

use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::BTreeMap;

/// The default reference prefix (`skills.reference_prefix`).
pub const DEFAULT_PREFIX: &str = "@skill:";
/// The URI scheme skills-as-resources use.
pub const SKILL_SCHEME: &str = "skill://";
/// The mime type that marks a resource as a skill.
pub const SKILL_MIME: &str = "text/x-skill+markdown";

/// A catalogue entry (no body).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SkillMeta {
    pub name: String,
    #[serde(default)]
    pub description: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub when_to_use: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub arguments: Vec<Value>,
    pub source: SkillSourceRef,
}

/// Where a skill comes from.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SkillSourceRef {
    pub server: String,
    #[serde(rename = "kind")]
    pub kind: SkillSourceKind,
    /// The prompt name or the resource URI.
    #[serde(rename = "ref")]
    pub reference: String,
    /// The body, for [`SkillSourceKind::Inline`] only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SkillSourceKind {
    Prompt,
    Resource,
    /// Defined by a `:::skill` directive in the instruction; the body lives on
    /// the meta — no server round trip, no server at all.
    Inline,
}

/// A loaded skill body (cached by hash).
#[derive(Debug, Clone, PartialEq)]
pub struct SkillBody {
    pub name: String,
    pub hash: String,
    pub body: String,
}

/// The MCP surface skill discovery needs — implemented for the MCP client and
/// by test fakes.
pub trait SkillServer {
    fn server_name(&self) -> String;
    fn supports_prompts(&self) -> bool;
    fn supports_resources(&self) -> bool;
    fn list_prompts(&self) -> Result<Vec<::mcp::wire::Prompt>, String>;
    fn get_prompt(&self, name: &str, arguments: Option<Value>) -> Result<Vec<Value>, String>;
    fn list_resources(&self) -> Result<Vec<::mcp::wire::Resource>, String>;
    fn read_resource(&self, uri: &str) -> Result<String, String>;
}

impl SkillServer for crate::mcp::client::McpClient {
    fn server_name(&self) -> String {
        self.name().to_string()
    }
    fn supports_prompts(&self) -> bool {
        self.capabilities().supports_prompts()
    }
    fn supports_resources(&self) -> bool {
        self.capabilities().supports_resources()
    }
    fn list_prompts(&self) -> Result<Vec<::mcp::wire::Prompt>, String> {
        crate::mcp::client::McpClient::list_prompts(self).map_err(|e| e.to_string())
    }
    fn get_prompt(&self, name: &str, arguments: Option<Value>) -> Result<Vec<Value>, String> {
        crate::mcp::client::McpClient::get_prompt(self, name, arguments)
            .map(|r| r.messages)
            .map_err(|e| e.to_string())
    }
    fn list_resources(&self) -> Result<Vec<::mcp::wire::Resource>, String> {
        crate::mcp::client::McpClient::list_resources(self).map_err(|e| e.to_string())
    }
    fn read_resource(&self, uri: &str) -> Result<String, String> {
        crate::mcp::client::McpClient::read_resource(self, uri)
            .map(|r| r.text())
            .map_err(|e| e.to_string())
    }
}

/// How to discover on one source (`skills.sources[].discover`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Discover {
    Prompts,
    Resources,
    Auto,
}

/// The catalogue + body cache.
#[derive(Debug, Default)]
pub struct Catalogue {
    skills: BTreeMap<String, SkillMeta>,
    bodies: BTreeMap<String, SkillBody>, // by hash
    max_bytes: usize,
    pub prefix: String,
    /// Discovery errors per server (surfaced in status, never fatal).
    pub errors: BTreeMap<String, String>,
}

impl Catalogue {
    pub fn new(prefix: &str, max_bytes: usize) -> Catalogue {
        Catalogue {
            prefix: prefix.to_string(),
            max_bytes,
            ..Default::default()
        }
    }

    /// (Re)discover the skills of one server. Later sources do not override
    /// an existing name (first source wins; a collision is logged by the caller).
    /// Returns the names discovered on this server.
    pub fn discover(
        &mut self,
        server: &dyn SkillServer,
        mode: Discover,
        filter: Option<&str>,
    ) -> Vec<String> {
        let name = server.server_name();
        let mut found = Vec::new();
        let want_prompts =
            matches!(mode, Discover::Prompts | Discover::Auto) && server.supports_prompts();
        let want_resources =
            matches!(mode, Discover::Resources | Discover::Auto) && server.supports_resources();
        if want_prompts {
            match server.list_prompts() {
                Ok(prompts) => {
                    for p in prompts {
                        if !passes(filter, &p.name) {
                            continue;
                        }
                        let (description, when) =
                            split_when(p.description.as_deref().unwrap_or(""));
                        let meta = SkillMeta {
                            name: p.name.clone(),
                            description,
                            when_to_use: when,
                            arguments: p
                                .arguments
                                .iter()
                                .map(|a| serde_json::to_value(a).unwrap_or(Value::Null))
                                .collect(),
                            source: SkillSourceRef {
                                server: name.clone(),
                                kind: SkillSourceKind::Prompt,
                                reference: p.name.clone(),
                                body: None,
                            },
                        };
                        if self.insert(meta) {
                            found.push(p.name);
                        }
                    }
                }
                Err(e) => {
                    self.errors
                        .insert(name.clone(), format!("prompts/list: {e}"));
                }
            }
        }
        if want_resources {
            match server.list_resources() {
                Ok(resources) => {
                    for r in resources {
                        let is_skill = r.uri.starts_with(SKILL_SCHEME)
                            || r.mime_type.as_deref() == Some(SKILL_MIME);
                        if !is_skill {
                            continue;
                        }
                        let skill_name = r
                            .uri
                            .strip_prefix(SKILL_SCHEME)
                            .map(|s| s.trim_matches('/').to_string())
                            .filter(|s| !s.is_empty())
                            .or_else(|| r.name.clone())
                            .unwrap_or_else(|| r.uri.clone());
                        // The optional index resource `skill://` itself is not a skill.
                        if skill_name.is_empty() {
                            continue;
                        }
                        if !passes(filter, &skill_name) {
                            continue;
                        }
                        let (description, when) =
                            split_when(r.description.as_deref().unwrap_or(""));
                        let meta = SkillMeta {
                            name: skill_name.clone(),
                            description,
                            when_to_use: when,
                            arguments: Vec::new(),
                            source: SkillSourceRef {
                                server: name.clone(),
                                kind: SkillSourceKind::Resource,
                                reference: r.uri.clone(),
                                body: None,
                            },
                        };
                        if self.insert(meta) {
                            found.push(skill_name);
                        }
                    }
                }
                Err(e) => {
                    self.errors
                        .entry(name.clone())
                        .and_modify(|m| m.push_str(&format!("; resources/list: {e}")))
                        .or_insert(format!("resources/list: {e}"));
                }
            }
        }
        found
    }

    fn insert(&mut self, meta: SkillMeta) -> bool {
        if let Some(existing) = self.skills.get(&meta.name) {
            // Same source refreshed: replace; a different source: first wins.
            if existing.source == meta.source {
                self.skills.insert(meta.name.clone(), meta);
                return true;
            }
            return false;
        }
        self.skills.insert(meta.name.clone(), meta);
        true
    }

    /// Forget every skill of `server` (before a re-discovery).
    pub fn forget_server(&mut self, server: &str) {
        self.skills.retain(|_, m| m.source.server != server);
        self.errors.remove(server);
    }

    pub fn get(&self, name: &str) -> Option<&SkillMeta> {
        self.skills.get(name)
    }
    pub fn names(&self) -> Vec<String> {
        self.skills.keys().cloned().collect()
    }
    pub fn len(&self) -> usize {
        self.skills.len()
    }
    pub fn is_empty(&self) -> bool {
        self.skills.is_empty()
    }

    /// `skills.list` output.
    pub fn list_value(&self) -> Value {
        json!({
            "skills": self.skills.values().map(|m| json!({
                "name": m.name, "description": m.description, "when_to_use": m.when_to_use,
                "arguments": m.arguments, "source": {"server": m.source.server, "kind": m.source.kind}
            })).collect::<Vec<_>>(),
            "errors": self.errors,
        })
    }

    /// The catalogue block for a prompt (names + descriptions), or `None`
    /// when empty.
    pub fn render_catalogue(&self) -> Option<String> {
        if self.skills.is_empty() {
            return None;
        }
        let mut out = format!(
            "Available skills (reference one as {}<name> or call skills.load to read its full instructions):\n",
            self.prefix
        );
        for m in self.skills.values() {
            out.push_str(&format!("- {}: {}", m.name, m.description));
            if let Some(w) = &m.when_to_use {
                out.push_str(&format!(" (use when: {w})"));
            }
            out.push('\n');
        }
        Some(out)
    }

    /// Fetch (or serve from cache) a skill body. `servers` resolves the source
    /// server by name.
    pub fn load(
        &mut self,
        name: &str,
        arguments: Option<Value>,
        servers: &dyn Fn(&str) -> Option<std::sync::Arc<dyn SkillServer>>,
    ) -> Result<SkillBody, String> {
        let meta = self
            .skills
            .get(name)
            .cloned()
            .ok_or_else(|| format!("unknown skill {name:?}"))?;
        let text = if meta.source.kind == SkillSourceKind::Inline {
            meta.source
                .body
                .clone()
                .ok_or_else(|| format!("inline skill {name:?} lost its body"))?
        } else {
            let server = servers(&meta.source.server).ok_or_else(|| {
                format!(
                    "skill {name:?}: server {:?} is not connected",
                    meta.source.server
                )
            })?;
            match meta.source.kind {
                SkillSourceKind::Prompt => {
                    let messages = server.get_prompt(&meta.source.reference, arguments)?;
                    prompt_messages_text(&messages)
                }
                SkillSourceKind::Resource => server.read_resource(&meta.source.reference)?,
                SkillSourceKind::Inline => unreachable!("handled above"),
            }
        };
        if text.trim().is_empty() {
            return Err(format!("skill {name:?} has an empty body"));
        }
        let text = if text.len() > self.max_bytes {
            let mut cut = self.max_bytes;
            while !text.is_char_boundary(cut) {
                cut -= 1;
            }
            format!(
                "{}\n\n[skill body truncated to skills.max_bytes = {} bytes]",
                &text[..cut],
                self.max_bytes
            )
        } else {
            text
        };
        let hash = crate::sha::sha256_hex(text.as_bytes());
        let body = SkillBody {
            name: name.to_string(),
            hash: hash.clone(),
            body: text,
        };
        self.bodies.insert(hash, body.clone());
        Ok(body)
    }

    /// A cached body by hash.
    /// Register the instruction's `:::skill` definitions. Inline skills win a
    /// name collision with discovered ones — the operator wrote them CLOSER to
    /// this agent than any server did.
    pub fn add_inline(&mut self, skills: &[crate::config::directives::InlineSkill]) -> Vec<String> {
        let mut names = Vec::new();
        for sk in skills {
            self.skills.insert(
                sk.name.clone(),
                SkillMeta {
                    name: sk.name.clone(),
                    description: sk.description.clone(),
                    when_to_use: sk.when_to_use.clone(),
                    arguments: Vec::new(),
                    source: SkillSourceRef {
                        server: "instruction".into(),
                        kind: SkillSourceKind::Inline,
                        reference: sk.name.clone(),
                        body: Some(sk.body.clone()),
                    },
                },
            );
            names.push(sk.name.clone());
        }
        names
    }

    /// Register a LOCAL folder of skill files.
    ///
    /// Two layouts, because both are in the wild: `<dir>/<name>.md`, and the
    /// Agent Skill directory form `<dir>/<name>/SKILL.md`. Either may carry
    /// YAML frontmatter (`name`, `description`); without it the file stem is
    /// the name and the first paragraph is the description, so a plain
    /// markdown file is a usable skill with no ceremony.
    ///
    /// Registered as [`SkillSourceKind::Inline`] with the body already read:
    /// a skill is prose, so there is nothing to fetch later and nothing that
    /// can fail at load time. Like `:::skill`, a local file WINS a name
    /// collision with a discovered one — the operator put it closer to this
    /// agent than any server did.
    pub fn add_dir(&mut self, dir: &std::path::Path) -> (Vec<String>, Vec<String>) {
        let (mut names, mut errs) = (Vec::new(), Vec::new());
        let Ok(rd) = std::fs::read_dir(dir) else {
            return (names, errs);
        };
        let mut candidates: Vec<(String, std::path::PathBuf)> = Vec::new();
        for ent in rd.flatten() {
            let path = ent.path();
            let stem = path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or_default()
                .to_string();
            if path.is_dir() {
                let inner = path.join("SKILL.md");
                if inner.is_file() {
                    candidates.push((stem, inner));
                }
            } else if path.extension().and_then(|e| e.to_str()) == Some("md") {
                candidates.push((stem, path));
            }
        }
        // Sorted so a folder's registration order is its filename order — the
        // only ordering an operator can see without reading this function.
        candidates.sort();
        for (stem, path) in candidates {
            let text = match std::fs::read_to_string(&path) {
                Ok(t) => t,
                Err(e) => {
                    errs.push(format!("{}: {e}", path.display()));
                    continue;
                }
            };
            let (meta, body) = split_frontmatter(&text);
            if body.trim().is_empty() {
                errs.push(format!("{}: empty skill body", path.display()));
                continue;
            }
            let name = meta
                .as_ref()
                .and_then(|m| m.get("name"))
                .and_then(|v| v.as_str())
                .map(str::to_string)
                .unwrap_or(stem);
            let raw_desc = meta
                .as_ref()
                .and_then(|m| m.get("description"))
                .and_then(|v| v.as_str())
                .map(str::to_string)
                .unwrap_or_else(|| first_paragraph(&body));
            let (description, when_to_use) = split_when(&raw_desc);
            self.skills.insert(
                name.clone(),
                SkillMeta {
                    name: name.clone(),
                    description,
                    when_to_use,
                    arguments: Vec::new(),
                    source: SkillSourceRef {
                        server: "file".into(),
                        kind: SkillSourceKind::Inline,
                        reference: path.to_string_lossy().into_owned(),
                        body: Some(body),
                    },
                },
            );
            names.push(name);
        }
        (names, errs)
    }

    pub fn body(&self, hash: &str) -> Option<&SkillBody> {
        self.bodies.get(hash)
    }

    /// Drop cached bodies whose hash is not in `keep`.
    pub fn evict_except(&mut self, keep: &[String]) {
        self.bodies.retain(|h, _| keep.iter().any(|k| k == h));
    }

    /// The `@skill:<name>` references in a text (deduplicated, in order).
    pub fn references(&self, text: &str) -> Vec<String> {
        find_references(text, &self.prefix)
    }
}

/// `@skill:<name>` references in `text` — a name is `[A-Za-z0-9_.:-]+`
/// (trailing punctuation stripped), deduplicated in order of appearance.
pub fn find_references(text: &str, prefix: &str) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    if prefix.is_empty() {
        return out;
    }
    let mut rest = text;
    while let Some(pos) = rest.find(prefix) {
        let after = &rest[pos + prefix.len()..];
        let name: String = after
            .chars()
            .take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/'))
            .collect();
        let name = name.trim_end_matches(['.', '/']).to_string();
        let consumed = name.len().min(after.len());
        if !name.is_empty() && !out.contains(&name) {
            out.push(name);
        }
        rest = &after[consumed..];
    }
    out
}

/// A `prompts/get` result's text: the concatenated text parts of its messages.
pub fn prompt_messages_text(messages: &[Value]) -> String {
    let mut out = String::new();
    for m in messages {
        let content = m.get("content").unwrap_or(&Value::Null);
        let text = match content {
            Value::String(s) => s.clone(),
            Value::Object(o) => o
                .get("text")
                .and_then(Value::as_str)
                .unwrap_or("")
                .to_string(),
            Value::Array(parts) => parts
                .iter()
                .filter_map(|p| p.get("text").and_then(Value::as_str))
                .collect::<Vec<_>>()
                .join("\n"),
            _ => String::new(),
        };
        if !text.is_empty() {
            if !out.is_empty() {
                out.push_str("\n\n");
            }
            out.push_str(&text);
        }
    }
    out
}

/// Render the loaded skill bodies as one system block.
pub fn render_bodies(bodies: &[&SkillBody]) -> Option<String> {
    if bodies.is_empty() {
        return None;
    }
    let mut out = String::from("Loaded skills — follow these instructions when relevant:\n");
    for b in bodies {
        out.push_str(&format!("\n### Skill: {}\n{}\n", b.name, b.body.trim()));
    }
    Some(out)
}

fn passes(filter: Option<&str>, name: &str) -> bool {
    match filter {
        None => true,
        Some(f) => {
            let f = f.trim();
            if let Some(prefix) = f.strip_suffix('*') {
                name.starts_with(prefix)
            } else {
                f == name || f.is_empty()
            }
        }
    }
}

/// Split `---\nyaml\n---\nbody` into its parts. No frontmatter is not an
/// error: a plain markdown file is a perfectly good skill, and demanding a
/// header would make the simplest case the annoying one.
fn split_frontmatter(text: &str) -> (Option<serde_json::Value>, String) {
    let rest = match text.strip_prefix("---\n") {
        Some(r) => r,
        None => return (None, text.to_string()),
    };
    let Some((head, body)) = rest.split_once("\n---\n") else {
        return (None, text.to_string());
    };
    match crate::config::file::parse_document(head, crate::config::file::Format::Yaml) {
        Ok(v) if v.is_object() => (Some(v), body.to_string()),
        // Malformed frontmatter falls back to treating the whole file as body
        // rather than failing: the skill still reads, and a wrong name is more
        // recoverable than a daemon that will not start.
        _ => (None, text.to_string()),
    }
}

/// The first non-empty paragraph, minus a leading markdown heading — the
/// description for a file that carries no frontmatter.
fn first_paragraph(body: &str) -> String {
    body.split("\n\n")
        .map(str::trim)
        .find(|p| !p.is_empty() && !p.starts_with('#'))
        .unwrap_or("")
        .replace('\n', " ")
}

/// Split a description of the form `"… When to use: …"` (or `"… Use when …"`).
fn split_when(desc: &str) -> (String, Option<String>) {
    for marker in ["When to use:", "when to use:", "Use when:", "use when:"] {
        if let Some((a, b)) = desc.split_once(marker) {
            let w = b.trim();
            return (
                a.trim().trim_end_matches('.').to_string(),
                (!w.is_empty()).then(|| w.to_string()),
            );
        }
    }
    (desc.trim().to_string(), None)
}

#[cfg(test)]
mod tests {
    use super::*;
    use ::mcp::wire::{Prompt, PromptArgument, Resource};

    struct Fake {
        name: String,
        prompts: Vec<Prompt>,
        resources: Vec<Resource>,
        bodies: BTreeMap<String, String>,
    }
    impl SkillServer for Fake {
        fn server_name(&self) -> String {
            self.name.clone()
        }
        fn supports_prompts(&self) -> bool {
            !self.prompts.is_empty()
        }
        fn supports_resources(&self) -> bool {
            !self.resources.is_empty()
        }
        fn list_prompts(&self) -> Result<Vec<Prompt>, String> {
            Ok(self.prompts.clone())
        }
        fn get_prompt(&self, name: &str, arguments: Option<Value>) -> Result<Vec<Value>, String> {
            let body = self.bodies.get(name).cloned().ok_or("no such prompt")?;
            let body = match arguments
                .and_then(|a| a.get("target").and_then(Value::as_str).map(str::to_string))
            {
                Some(t) => body.replace("{target}", &t),
                None => body,
            };
            Ok(vec![
                json!({"role": "user", "content": {"type": "text", "text": body}}),
            ])
        }
        fn list_resources(&self) -> Result<Vec<Resource>, String> {
            Ok(self.resources.clone())
        }
        fn read_resource(&self, uri: &str) -> Result<String, String> {
            self.bodies
                .get(uri)
                .cloned()
                .ok_or("no such resource".into())
        }
    }

    fn fake() -> Fake {
        Fake {
            name: "skills".into(),
            prompts: vec![
                Prompt {
                    name: "review-pr".into(),
                    title: None,
                    description: Some(
                        "Review a pull request. When to use: any code review request".into(),
                    ),
                    arguments: vec![PromptArgument {
                        name: "target".into(),
                        title: None,
                        description: None,
                        required: Some(false),
                    }],
                },
                Prompt {
                    name: "internal-tool".into(),
                    title: None,
                    description: None,
                    arguments: vec![],
                },
            ],
            resources: vec![
                Resource {
                    uri: "skill://deploy".into(),
                    name: Some("deploy".into()),
                    title: None,
                    description: Some("Deploy safely".into()),
                    mime_type: Some(SKILL_MIME.into()),
                },
                Resource {
                    uri: "file:///readme.md".into(),
                    name: None,
                    title: None,
                    description: None,
                    mime_type: Some("text/markdown".into()),
                },
                Resource {
                    uri: "notes://x".into(),
                    name: Some("x".into()),
                    title: None,
                    description: None,
                    mime_type: Some(SKILL_MIME.into()),
                },
            ],
            bodies: [
                (
                    "review-pr".to_string(),
                    "# Review PR\nLook at {target} carefully.".to_string(),
                ),
                ("internal-tool".to_string(), "internal".to_string()),
                (
                    "skill://deploy".to_string(),
                    "# Deploy\n1. plan 2. apply".to_string(),
                ),
                ("notes://x".to_string(), "x body".to_string()),
            ]
            .into_iter()
            .collect(),
        }
    }

    #[test]
    fn discovery_over_prompts_and_resources_with_filters() {
        let f = fake();
        let mut c = Catalogue::new(DEFAULT_PREFIX, 1024);
        let found = c.discover(&f, Discover::Auto, None);
        assert_eq!(found, vec!["review-pr", "internal-tool", "deploy", "x"]);
        let m = c.get("review-pr").unwrap();
        assert_eq!(m.description, "Review a pull request");
        assert_eq!(m.when_to_use.as_deref(), Some("any code review request"));
        assert_eq!(m.arguments.len(), 1);
        assert_eq!(
            c.get("deploy").unwrap().source.kind,
            SkillSourceKind::Resource
        );
        assert!(
            c.get("readme.md").is_none(),
            "a plain markdown resource is not a skill"
        );
        let cat = c.render_catalogue().unwrap();
        assert!(
            cat.contains("- review-pr: Review a pull request (use when: any code review request)"),
            "{cat}"
        );
        // Filter + prompts-only.
        let mut c2 = Catalogue::new(DEFAULT_PREFIX, 1024);
        assert_eq!(
            c2.discover(&f, Discover::Prompts, Some("review-*")),
            vec!["review-pr"]
        );
        // A second source does not steal an existing name.
        let mut other = fake();
        other.name = "other".into();
        assert!(c.discover(&other, Discover::Auto, None).is_empty());
        assert_eq!(c.get("deploy").unwrap().source.server, "skills");
        c.forget_server("skills");
        assert!(c.is_empty());
    }

    #[test]
    fn load_caches_by_hash_truncates_and_renders() {
        let f = std::sync::Arc::new(fake());
        let mut c = Catalogue::new(DEFAULT_PREFIX, 30);
        c.discover(&*f, Discover::Auto, None);
        let f2 = f.clone();
        let servers = move |n: &str| -> Option<std::sync::Arc<dyn SkillServer>> {
            (n == "skills").then(|| f2.clone() as std::sync::Arc<dyn SkillServer>)
        };
        let b = c
            .load("review-pr", Some(json!({"target": "PR #7"})), &servers)
            .unwrap();
        assert!(b.body.contains("PR #7"));
        assert!(b.body.contains("truncated to skills.max_bytes"));
        assert!(c.body(&b.hash).is_some());
        let d = c.load("deploy", None, &servers).unwrap();
        assert!(d.body.starts_with("# Deploy"));
        assert!(c.load("nope", None, &servers).is_err());
        assert!(
            c.load("deploy", None, &|_| None).is_err(),
            "server not connected"
        );
        let block = render_bodies(&[&b, &d]).unwrap();
        assert!(block.contains("### Skill: review-pr") && block.contains("### Skill: deploy"));
        c.evict_except(std::slice::from_ref(&d.hash));
        assert!(c.body(&b.hash).is_none());
        assert!(c.body(&d.hash).is_some());
    }

    #[test]
    fn references_are_found_and_deduped() {
        let refs = find_references(
            "please @skill:review-pr this, then @skill:deploy. Also @skill:review-pr again and @skill:",
            "@skill:",
        );
        assert_eq!(refs, vec!["review-pr", "deploy"]);
        assert!(find_references("nothing here", "@skill:").is_empty());
        assert_eq!(find_references("use +s:x/y.", "+s:"), vec!["x/y"]);
        assert_eq!(
            prompt_messages_text(&[
                json!({"content": "a"}),
                json!({"content": [{"type": "text", "text": "b"}, {"type": "image"}]})
            ]),
            "a\n\nb"
        );
    }

    /// A local folder: three layouts, one catalogue. The frontmatter `name`
    /// wins over the filename, because a file can be renamed and a skill
    /// reference should not break when it is.
    #[test]
    fn a_local_folder_registers_every_layout() {
        let dir = std::env::temp_dir().join(format!("agentd-skilldir-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("runbook")).unwrap();

        std::fs::write(
            dir.join("triage.md"),
            "---\nname: triage\ndescription: Triage an issue. Use when: it has no labels\n---\n\nRead it, label it.\n",
        )
        .unwrap();
        // The Agent Skill directory form, with a frontmatter name that differs
        // from the directory it lives in.
        std::fs::write(
            dir.join("runbook/SKILL.md"),
            "---\nname: incident\ndescription: Handle an incident. When to use: an alert fires\n---\n\nAcknowledge, then mitigate.\n",
        )
        .unwrap();
        // No frontmatter at all: the stem names it and the first real
        // paragraph describes it, so a plain note is a usable skill.
        std::fs::write(
            dir.join("deploy.md"),
            "# Deploy safely\n\nAlways deploy behind a flag.\n",
        )
        .unwrap();

        let mut cat = Catalogue::new(DEFAULT_PREFIX, 32_768);
        let (names, errs) = cat.add_dir(&dir);
        assert!(errs.is_empty(), "{errs:?}");
        assert_eq!(
            names,
            ["deploy", "incident", "triage"],
            "sorted by file stem"
        );

        let triage = cat.skills.get("triage").expect("triage");
        assert_eq!(triage.description, "Triage an issue");
        assert_eq!(triage.when_to_use.as_deref(), Some("it has no labels"));

        let incident = cat.skills.get("incident").expect("frontmatter name wins");
        assert_eq!(incident.when_to_use.as_deref(), Some("an alert fires"));

        let deploy = cat.skills.get("deploy").expect("deploy");
        assert_eq!(deploy.description, "Always deploy behind a flag.");
        assert!(deploy.when_to_use.is_none());

        // The body is already in hand — a skill is prose, so there is nothing
        // to fetch later and no server that can be down when it is read.
        let body = cat
            .load("deploy", None, &|_| None)
            .expect("an inline body needs no server");
        assert!(body.body.contains("behind a flag"), "{}", body.body);

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A file that only LOOKS like it has frontmatter still reads as a skill.
    /// Refusing to start over a stray `---` would be a poor trade.
    #[test]
    fn malformed_frontmatter_degrades_to_body() {
        let (meta, body) = split_frontmatter("---\n: : not yaml\n---\nhello\n");
        assert!(meta.is_none());
        assert!(body.contains("hello"), "{body}");

        let (meta, body) = split_frontmatter("no header here\n");
        assert!(meta.is_none());
        assert_eq!(body, "no header here\n");
    }
}