Skip to main content

troupekit_agent/
loader.rs

1use crate::error::{AgentError, PersonaError};
2use crate::persona::{valid_name, valid_relative_path, Persona};
3use async_trait::async_trait;
4use std::collections::HashMap;
5use std::path::PathBuf;
6use std::sync::Arc;
7use troupekit_trace::TraceSpec;
8
9/// A place persona files live: a folder, a database-backed virtual folder
10/// or the built-in set. `read` takes a relative path (`<name>.toml` or an
11/// `instructions_file`) and returns `None` when there is no such file.
12#[async_trait]
13pub trait PersonaSource: Send + Sync {
14    fn label(&self) -> &str;
15    async fn read(&self, path: &str) -> Result<Option<String>, AgentError>;
16}
17
18/// Persona files in a directory on disk.
19/// Paths are checked with `valid_relative_path` before the join, so a
20/// persona can never read outside its directory.
21#[derive(Debug, Clone)]
22pub struct DirSource {
23    label: String,
24    dir: PathBuf,
25}
26
27impl DirSource {
28    /// Builds a source over `dir`, labelled with the directory path.
29    /// The directory is read only on `read`, with blocking file I/O.
30    /// Returns the source.
31    pub fn new(dir: impl Into<PathBuf>) -> Self {
32        let dir = dir.into();
33        Self {
34            label: dir.display().to_string(),
35            dir,
36        }
37    }
38}
39
40#[async_trait]
41impl PersonaSource for DirSource {
42    fn label(&self) -> &str {
43        &self.label
44    }
45
46    async fn read(&self, path: &str) -> Result<Option<String>, AgentError> {
47        if !valid_relative_path(path) {
48            return Err(AgentError::Source(format!(
49                "{}: unsafe path `{path}`",
50                self.label
51            )));
52        }
53        match std::fs::read_to_string(self.dir.join(path)) {
54            Ok(text) => Ok(Some(text)),
55            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
56            Err(e) => Err(AgentError::Source(format!("{}/{path}: {e}", self.label))),
57        }
58    }
59}
60
61/// Persona files held in memory, keyed by relative path.
62/// Hosts use it for files loaded from a database; `builtin` uses it for
63/// the personas shipped with this crate.
64#[derive(Debug, Clone, Default)]
65pub struct MemorySource {
66    label: String,
67    files: HashMap<String, String>,
68}
69
70impl MemorySource {
71    /// Builds a source labelled `label` holding `files` as (path, text).
72    /// Paths are matched exactly.
73    /// Returns the source.
74    pub fn new(
75        label: impl Into<String>,
76        files: impl IntoIterator<Item = (String, String)>,
77    ) -> Self {
78        Self {
79            label: label.into(),
80            files: files.into_iter().collect(),
81        }
82    }
83}
84
85#[async_trait]
86impl PersonaSource for MemorySource {
87    fn label(&self) -> &str {
88        &self.label
89    }
90
91    async fn read(&self, path: &str) -> Result<Option<String>, AgentError> {
92        Ok(self.files.get(path).cloned())
93    }
94}
95
96/// The personas shipped with this crate, labelled `builtin`:
97/// `assistant` (no tools) and `researcher` (`web_search`, `web_fetch`).
98/// Put it last in a loader so every other source can override it.
99pub fn builtin() -> MemorySource {
100    MemorySource::new(
101        "builtin",
102        [
103            (
104                "assistant.toml".to_string(),
105                include_str!("../personas/assistant.toml").to_string(),
106            ),
107            (
108                "researcher.toml".to_string(),
109                include_str!("../personas/researcher.toml").to_string(),
110            ),
111        ],
112    )
113}
114
115/// Finds personas by name across sources in lookup order, for example the
116/// goal's scoped folder, then the user's library, then `builtin()`.
117/// The first source holding `<name>.toml` wins.
118#[derive(Clone)]
119pub struct PersonaLoader {
120    sources: Vec<Arc<dyn PersonaSource>>,
121}
122
123impl PersonaLoader {
124    /// Builds a loader that tries `sources` first to last.
125    /// Put the most specific source first.
126    /// Returns the loader.
127    pub fn new(sources: Vec<Arc<dyn PersonaSource>>) -> Self {
128        Self { sources }
129    }
130
131    /// Loads and validates persona `name` from the first source that has it,
132    /// reading its `instructions_file` from the same source. Returns
133    /// `NotFound` when no source has it, or the validation error.
134    pub async fn load(&self, name: &str) -> Result<Persona, AgentError> {
135        if !valid_name(name) {
136            return Err(PersonaError::new(
137                name,
138                "name",
139                "must be 1 to 64 of [a-z0-9-], not starting with `-`",
140            )
141            .into());
142        }
143        let path = format!("{name}.toml");
144        for source in &self.sources {
145            let Some(text) = source.read(&path).await? else {
146                continue;
147            };
148            let file = format!("{}/{path}", source.label());
149            let persona = Persona::parse(&file, &text)?;
150            if persona.name != name {
151                return Err(PersonaError::new(
152                    &file,
153                    "name",
154                    format!("`{}` must equal the file name `{name}`", persona.name),
155                )
156                .into());
157            }
158            let Some(rel) = persona.instructions_file.clone() else {
159                return Ok(persona);
160            };
161            let text = source.read(&rel).await?.ok_or_else(|| {
162                PersonaError::new(&file, "instructions_file", format!("`{rel}` not found"))
163            })?;
164            return Ok(persona.with_instructions(text)?);
165        }
166        Err(AgentError::NotFound(name.to_string()))
167    }
168
169    /// Returns the trace settings of persona `name` from the first source
170    /// that has it, `None` when the file sets no tracing. Returns
171    /// `NotFound` when no source has it, or the trace key error.
172    pub async fn trace_spec(&self, name: &str) -> Result<Option<TraceSpec>, AgentError> {
173        if !valid_name(name) {
174            return Err(PersonaError::new(
175                name,
176                "name",
177                "must be 1 to 64 of [a-z0-9-], not starting with `-`",
178            )
179            .into());
180        }
181        let path = format!("{name}.toml");
182        for source in &self.sources {
183            if let Some(text) = source.read(&path).await? {
184                let file = format!("{}/{path}", source.label());
185                return Ok(crate::persona::trace_spec(&file, &text)?);
186            }
187        }
188        Err(AgentError::NotFound(name.to_string()))
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    fn persona(name: &str, role: &str) -> String {
197        format!("name = '{name}'\ndisplay_name = 'P'\nrole = '{role}'\ngoal = 'g'\ninstructions = 'i'\nmodel = 'fast'\n")
198    }
199
200    fn mem(label: &str, files: &[(&str, String)]) -> Arc<dyn PersonaSource> {
201        Arc::new(MemorySource::new(
202            label,
203            files.iter().map(|(p, t)| (p.to_string(), t.clone())),
204        ))
205    }
206
207    #[tokio::test]
208    async fn lookup_order_scoped_user_builtin() {
209        let scoped = mem("goal", &[("coach.toml", persona("coach", "scoped"))]);
210        let user = mem(
211            "user",
212            &[
213                ("coach.toml", persona("coach", "user")),
214                ("assistant.toml", persona("assistant", "mine")),
215            ],
216        );
217        let loader = PersonaLoader::new(vec![scoped, user, Arc::new(builtin())]);
218        let coach = loader.load("coach").await.unwrap();
219        assert_eq!(
220            (coach.role.as_str(), coach.source.as_str()),
221            ("scoped", "goal/coach.toml")
222        );
223        assert_eq!(loader.load("assistant").await.unwrap().role, "mine");
224        assert_eq!(
225            loader.load("researcher").await.unwrap().source,
226            "builtin/researcher.toml"
227        );
228        assert_eq!(
229            loader.load("nobody").await.unwrap_err(),
230            AgentError::NotFound("nobody".into())
231        );
232    }
233
234    #[tokio::test]
235    async fn rejects_unsafe_names_before_io() {
236        let loader = PersonaLoader::new(vec![Arc::new(DirSource::new("/nonexistent"))]);
237        for bad in ["../etc/passwd", "a/b", "", "Coach", "-x"] {
238            assert!(
239                matches!(loader.load(bad).await, Err(AgentError::Persona(ref e)) if e.field == "name"),
240                "{bad}"
241            );
242        }
243        let src = DirSource::new("/nonexistent");
244        assert!(src.read("../x.toml").await.is_err());
245        assert_eq!(src.read("x.toml").await.unwrap(), None);
246    }
247
248    #[tokio::test]
249    async fn name_must_equal_file_stem() {
250        let loader = PersonaLoader::new(vec![mem("lib", &[("coach.toml", persona("other", "r"))])]);
251        let err = loader.load("coach").await.unwrap_err();
252        assert_eq!(
253            err.to_string(),
254            "lib/coach.toml: name: `other` must equal the file name `coach`"
255        );
256    }
257
258    #[tokio::test]
259    async fn reads_instructions_file_from_same_source() {
260        let text = persona("coach", "r").replace(
261            "instructions = 'i'",
262            "instructions_file = 'prompts/coach.md'",
263        );
264        let ok = PersonaLoader::new(vec![mem(
265            "lib",
266            &[
267                ("coach.toml", text.clone()),
268                ("prompts/coach.md", "Plan well.".into()),
269            ],
270        )]);
271        assert_eq!(ok.load("coach").await.unwrap().instructions, "Plan well.");
272        let missing = PersonaLoader::new(vec![mem("lib", &[("coach.toml", text)])]);
273        assert!(
274            matches!(missing.load("coach").await, Err(AgentError::Persona(ref e)) if e.field == "instructions_file")
275        );
276    }
277
278    #[tokio::test]
279    async fn dir_source_reads_files() {
280        let dir = std::env::temp_dir().join(format!("tk-personas-{}", std::process::id()));
281        std::fs::create_dir_all(&dir).unwrap();
282        std::fs::write(dir.join("coach.toml"), persona("coach", "disk")).unwrap();
283        let loader = PersonaLoader::new(vec![Arc::new(DirSource::new(&dir))]);
284        assert_eq!(loader.load("coach").await.unwrap().role, "disk");
285        std::fs::remove_dir_all(&dir).unwrap();
286    }
287
288    #[tokio::test]
289    async fn builtin_personas_load() {
290        let loader = PersonaLoader::new(vec![Arc::new(builtin())]);
291        let assistant = loader.load("assistant").await.unwrap();
292        assert!(assistant.tools.is_empty());
293        let researcher = loader.load("researcher").await.unwrap();
294        assert_eq!(researcher.tools, ["web_search", "web_fetch"]);
295        assert!(researcher.output.is_some());
296    }
297}