mentra 0.36.0

An agent runtime for tool-using LLM applications
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
//! The ordered set of skill roots a runtime holds.
//!
//! Roots stay separate here rather than being folded into one map at
//! registration time. Keeping the boundary is what makes a root removable at
//! all, and what makes removal *restorative*: a name a stronger root won is
//! still present in the weaker root's loader, so dropping the winner reveals
//! it again instead of deleting the name.
//!
//! Precedence is registration order, earliest first — the rule
//! [`SkillRegistry::resolve`] applies on every lookup.

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

use super::{SkillEntry, SkillInfo, SkillLoadError, SkillLoader, render_skill, skill_root_key};
use crate::agent::SkillProfile;

/// Returned when nothing is registered at all, to separate "this runtime has
/// no skills" from "that name is not one of them".
const NO_LOADER: &str = "Skill loader is not available";

/// One registered root: where a host said its skills live, and what loaded.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SkillRoot {
    /// The path the host passed, kept verbatim.
    ///
    /// This is what [`SkillInfo::root`] reports, so a host recognizes it and
    /// can hand it straight back to `unregister_skills_dir`.
    registered: PathBuf,
    /// The identity a root is matched by: its canonical path where the
    /// filesystem can resolve one, so two spellings of the same directory are
    /// one root rather than two.
    key: PathBuf,
    loader: SkillLoader,
}

impl SkillRoot {
    /// Loads a root without touching any registry.
    ///
    /// Splitting the load from the commit is what makes registration
    /// all-or-nothing: a caller loads every root first and only then hands the
    /// batch over, so a failure anywhere leaves the registry untouched.
    pub(crate) fn load(path: impl AsRef<Path>) -> Result<Self, SkillLoadError> {
        let path = path.as_ref();
        let loader = SkillLoader::from_dir(path)?;
        Ok(Self {
            registered: path.to_path_buf(),
            key: skill_root_key(path),
            loader,
        })
    }

    /// Whether `path` names this root.
    ///
    /// Canonical paths first, so `a/b/../b` and a symlinked parent still
    /// match. The verbatim comparison behind it covers the root whose
    /// directory has since been deleted — exactly when a host is cleaning up
    /// after a workspace and canonicalization can no longer answer.
    fn matches(&self, path: &Path, key: &Path) -> bool {
        self.key == key || self.registered == path
    }
}

/// Every skill root on a runtime, strongest first.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct SkillRegistry {
    roots: Vec<SkillRoot>,
}

impl SkillRegistry {
    /// Whether any root is registered.
    pub(crate) fn is_empty(&self) -> bool {
        self.roots.is_empty()
    }

    /// Commits already-loaded roots in one step.
    ///
    /// A root that is already registered is reloaded *in place*, keeping the
    /// precedence it had. One entry per root is what lets a single
    /// [`remove`](Self::remove) drop it: stacking a second, fully shadowed
    /// copy would leave residue behind the first removal.
    pub(crate) fn insert(&mut self, roots: Vec<SkillRoot>) {
        for root in roots {
            match self
                .roots
                .iter_mut()
                .find(|existing| existing.matches(&root.registered, &root.key))
            {
                Some(existing) => *existing = root,
                None => self.roots.push(root),
            }
        }
    }

    /// Drops the root `path` names, reporting whether one was there.
    ///
    /// Every skill that root contributed goes with it, and any name it had
    /// shadowed resolves to the weaker root again.
    pub(crate) fn remove(&mut self, path: impl AsRef<Path>) -> bool {
        let path = path.as_ref();
        let key = skill_root_key(path);
        let before = self.roots.len();
        self.roots.retain(|root| !root.matches(path, &key));
        self.roots.len() != before
    }

    /// The root and entry a name resolves to, or `None` if no root defines it.
    ///
    /// First root wins: roots are registered strongest first, so a workspace
    /// skill shadows a personal one of the same name. The shadowed entry is
    /// not lost, only outranked.
    fn resolve(&self, name: &str) -> Option<(&SkillRoot, &SkillEntry)> {
        self.roots
            .iter()
            .find_map(|root| root.loader.entry(name).map(|entry| (root, entry)))
    }

    /// Every visible skill, name-ordered, with the root it resolved from.
    fn visible(&self) -> BTreeMap<&str, (&SkillRoot, &SkillEntry)> {
        let mut visible = BTreeMap::new();
        for root in &self.roots {
            for (name, entry) in root.loader.entries() {
                visible.entry(name.as_str()).or_insert((root, entry));
            }
        }
        visible
    }

    /// Every loaded skill, name-ordered, without bodies.
    pub(crate) fn infos(&self) -> Vec<SkillInfo> {
        self.visible()
            .into_iter()
            .map(|(name, (root, entry))| SkillInfo {
                name: name.to_string(),
                description: entry.description.clone(),
                model_invocable: entry.model_invocable,
                path: entry.path.clone(),
                root: root.registered.clone(),
            })
            .collect()
    }

    /// The skill list shown to an agent's model.
    ///
    /// Skills whose frontmatter disabled model invocation are left out, and
    /// so are those outside `profile`: naming one here and refusing it in
    /// `load_skill` would be an invitation followed by a refusal.
    pub(crate) fn get_descriptions(&self, profile: &SkillProfile) -> String {
        let invocable = self
            .visible()
            .into_iter()
            .filter(|(name, (_, entry))| entry.model_invocable && profile.allows(name))
            .collect::<Vec<_>>();
        if invocable.is_empty() {
            return String::new();
        }

        let mut lines = vec!["Skills available:".to_string()];
        for (name, (_, entry)) in invocable {
            lines.push(format!("  - {name}: {}", entry.description));
        }
        lines.push(
            "Use the load_skill tool only when one of these skills is relevant to the task."
                .to_string(),
        );
        lines.join("\n")
    }

    /// Returns a skill's body regardless of whether the model may invoke it.
    ///
    /// The host-side counterpart to [`get_content`](Self::get_content): a
    /// skill marked `disable-model-invocation` is refused there and returned
    /// here, which is the whole point of the flag.
    pub(crate) fn get_body(&self, name: &str) -> Result<String, String> {
        let (_, entry) = self.lookup(name)?;
        Ok(render_skill(name, &entry.body))
    }

    /// Returns a skill's body for an agent's model, refusing one it may not
    /// invoke.
    ///
    /// A skill outside `profile` is refused in the words an unregistered one
    /// is: for that agent it does not exist, and the refusal must not say
    /// otherwise.
    pub(crate) fn get_content(&self, name: &str, profile: &SkillProfile) -> Result<String, String> {
        if !self.roots.is_empty() && !profile.allows(name) {
            return Err(unknown_skill(name));
        }
        let (_, entry) = self.lookup(name)?;
        if !entry.model_invocable {
            return Err(format!("Skill '{name}' cannot be invoked by the model"));
        }
        Ok(render_skill(name, &entry.body))
    }

    fn lookup(&self, name: &str) -> Result<(&SkillRoot, &SkillEntry), String> {
        if self.roots.is_empty() {
            return Err(NO_LOADER.to_string());
        }
        self.resolve(name).ok_or_else(|| unknown_skill(name))
    }
}

fn unknown_skill(name: &str) -> String {
    format!("Unknown skill '{name}'")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::runtime::skill::tests::{temp_skills_dir, write_skill};

    fn registry(paths: &[&Path]) -> SkillRegistry {
        let roots = paths
            .iter()
            .map(|path| SkillRoot::load(path).expect("root loads"))
            .collect();
        let mut registry = SkillRegistry::default();
        registry.insert(roots);
        registry
    }

    #[test]
    fn the_earliest_root_wins_a_name_and_the_others_still_load() {
        let strong = temp_skills_dir("registry-strong");
        write_skill(&strong, "review", "---\nname: review\n---\nProject rules\n");
        let weak = temp_skills_dir("registry-weak");
        write_skill(&weak, "review", "---\nname: review\n---\nPersonal rules\n");
        write_skill(&weak, "deploy", "---\nname: deploy\n---\nPersonal deploy\n");

        let registry = registry(&[&strong, &weak]);

        assert!(
            registry
                .get_content("review", &SkillProfile::all())
                .expect("review resolves")
                .contains("Project rules")
        );
        assert!(registry.get_content("deploy", &SkillProfile::all()).is_ok());
    }

    #[test]
    fn removing_the_winner_reveals_the_skill_it_shadowed() {
        // The property a destructive merge cannot express: shadowing outranks
        // a skill, it does not delete it.
        let strong = temp_skills_dir("registry-restore-strong");
        write_skill(&strong, "review", "---\nname: review\n---\nProject rules\n");
        let weak = temp_skills_dir("registry-restore-weak");
        write_skill(&weak, "review", "---\nname: review\n---\nPersonal rules\n");

        let mut registry = registry(&[&strong, &weak]);
        assert!(registry.remove(&strong));

        assert!(
            registry
                .get_content("review", &SkillProfile::all())
                .expect("the weaker root answers now")
                .contains("Personal rules")
        );
        assert_eq!(registry.infos()[0].root, weak);
    }

    #[test]
    fn removing_the_last_root_leaves_nothing_reachable() {
        let root = temp_skills_dir("registry-empty");
        write_skill(&root, "one", "---\nname: one\n---\nBody\n");

        let mut registry = registry(&[&root]);
        assert!(registry.remove(&root));

        assert!(registry.is_empty());
        assert!(registry.infos().is_empty());
        assert_eq!(registry.get_descriptions(&SkillProfile::all()), "");
        assert_eq!(
            registry.get_content("one", &SkillProfile::all()),
            Err(NO_LOADER.to_string())
        );
        assert!(!registry.remove(&root), "a second removal finds nothing");
    }

    #[test]
    fn an_unknown_name_is_unknown_rather_than_unavailable() {
        let root = temp_skills_dir("registry-unknown");
        write_skill(&root, "one", "---\nname: one\n---\nBody\n");

        let registry = registry(&[&root]);

        assert_eq!(
            registry.get_body("two"),
            Err("Unknown skill 'two'".to_string())
        );
    }

    #[test]
    fn a_root_is_matched_by_canonical_path() {
        let root = temp_skills_dir("registry-canonical");
        write_skill(&root, "one", "---\nname: one\n---\nBody\n");

        let mut registry = registry(&[&root]);

        assert!(registry.remove(root.join("one").join("..")));
    }

    #[test]
    fn re_registering_a_root_replaces_its_entry_in_place() {
        let strong = temp_skills_dir("registry-reload-strong");
        write_skill(&strong, "review", "---\nname: review\n---\nFirst\n");
        let weak = temp_skills_dir("registry-reload-weak");
        write_skill(&weak, "review", "---\nname: review\n---\nPersonal\n");

        let mut registry = registry(&[&strong, &weak]);
        write_skill(&strong, "review", "---\nname: review\n---\nSecond\n");
        registry.insert(vec![SkillRoot::load(&strong).expect("reloads")]);

        assert_eq!(registry.roots.len(), 2, "no stacked copy of the same root");
        assert!(
            registry
                .get_content("review", &SkillProfile::all())
                .expect("review resolves")
                .contains("Second"),
            "the reloaded root kept its precedence"
        );
        assert!(registry.remove(&strong));
        assert!(
            registry
                .get_content("review", &SkillProfile::all())
                .expect("review resolves")
                .contains("Personal")
        );
    }

    #[test]
    fn infos_name_the_file_and_the_root_without_carrying_bodies() {
        let strong = temp_skills_dir("registry-infos-strong");
        write_skill(
            &strong,
            "review",
            "---\nname: review\ndescription: D1\n---\nSECRET BODY\n",
        );
        let weak = temp_skills_dir("registry-infos-weak");
        write_skill(
            &weak,
            "deploy",
            "---\nname: deploy\ndescription: D2\n---\nB\n",
        );

        let infos = registry(&[&strong, &weak]).infos();

        assert_eq!(infos.len(), 2);
        // Name-ordered, so `deploy` precedes `review`.
        assert_eq!(infos[0].name, "deploy");
        assert_eq!(infos[0].description, "D2");
        assert_eq!(infos[0].path, weak.join("deploy").join("SKILL.md"));
        assert_eq!(infos[0].root, weak);
        assert_eq!(infos[1].name, "review");
        assert_eq!(infos[1].root, strong);
        assert!(
            !format!("{infos:?}").contains("SECRET BODY"),
            "descriptions stay cheap: bodies arrive only through load_skill"
        );
    }

    #[test]
    fn descriptions_leave_out_skills_the_model_may_not_invoke() {
        let root = temp_skills_dir("registry-descriptions");
        write_skill(
            &root,
            "release",
            "---\nname: release\ndescription: cuts a release\ndisable-model-invocation: true\n---\nSteps\n",
        );
        write_skill(
            &root,
            "git",
            "---\nname: git\ndescription: Git helpers\n---\nStep 1\n",
        );

        let registry = registry(&[&root]);

        assert_eq!(
            registry.get_descriptions(&SkillProfile::all()),
            "Skills available:\n  - git: Git helpers\nUse the load_skill tool only when one of these skills is relevant to the task."
        );
        assert!(
            registry
                .get_content("release", &SkillProfile::all())
                .is_err()
        );
        assert!(registry.get_body("release").is_ok());
    }

    #[test]
    fn a_profile_leaves_other_skills_out_of_the_list_and_out_of_reach() {
        let root = temp_skills_dir("registry-profile");
        write_skill(
            &root,
            "build",
            "---\nname: build\ndescription: Runs builds\n---\nBuild steps\n",
        );
        write_skill(
            &root,
            "ask",
            "---\nname: ask\ndescription: Answers questions\n---\nAsk steps\n",
        );
        let registry = registry(&[&root]);
        let profile = SkillProfile::only(["ask"]);

        assert_eq!(
            registry.get_descriptions(&profile),
            "Skills available:\n  - ask: Answers questions\nUse the load_skill tool only when one of these skills is relevant to the task."
        );
        assert!(registry.get_content("ask", &profile).is_ok());
        // Refused in the words a skill that was never registered is.
        assert_eq!(
            registry.get_content("build", &profile),
            registry
                .get_content("never-registered", &SkillProfile::all())
                .map_err(|error| error.replace("never-registered", "build"))
        );
        // The host's own reader is not the model's: it still sees the body.
        assert!(registry.get_body("build").is_ok());
    }

    #[test]
    fn a_profile_allowing_nothing_lists_nothing() {
        let root = temp_skills_dir("registry-profile-none");
        write_skill(
            &root,
            "build",
            "---\nname: build\ndescription: Runs builds\n---\nBuild steps\n",
        );
        let registry = registry(&[&root]);
        let none = SkillProfile::only(Vec::<String>::new());

        assert!(none.allows_none());
        assert_eq!(registry.get_descriptions(&none), "");
        assert!(registry.get_content("build", &none).is_err());
    }
}