troupekit_kit/agent/
from_toml.rs1use super::Agent;
2use crate::error::KitError;
3use crate::laws::read_checked;
4use std::io::ErrorKind;
5use std::path::{Component, Path, PathBuf};
6use toml::Value as Toml;
7use troupekit_agent::Persona;
8
9pub const MAX_PERSONA_BYTES: usize = 1024 * 1024;
13
14const TOML_NAME: &str = "toml";
15const TEXT_SOURCE: &str = "agent:toml";
16
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub(crate) enum PersonaSource {
19 Text(String),
20 File(PathBuf),
21}
22
23impl Agent {
24 pub fn from_toml(text: impl Into<String>) -> Agent {
29 let mut agent = Agent::new(TOML_NAME);
30 agent.persona_source = Some(PersonaSource::Text(text.into()));
31 agent
32 }
33
34 pub fn from_toml_file(path: impl AsRef<Path>) -> Agent {
40 let mut agent = Agent::new(TOML_NAME);
41 agent.persona_source = Some(PersonaSource::File(path.as_ref().to_path_buf()));
42 agent
43 }
44
45 pub(crate) fn toml_source(&self) -> Result<Option<(String, toml::Table)>, KitError> {
46 let Some(source) = &self.persona_source else {
47 return Ok(None);
48 };
49 let (name, text) = match source {
50 PersonaSource::Text(text) => {
51 if text.len() > MAX_PERSONA_BYTES {
52 return Err(KitError::config(TEXT_SOURCE, "persona TOML is over 1 MiB"));
53 }
54 (TEXT_SOURCE.to_string(), text.clone())
55 }
56 PersonaSource::File(path) => {
57 let shown = path.display().to_string();
58 let (_, text) = read_checked(path, "toml", MAX_PERSONA_BYTES as u64)
59 .map_err(|m| KitError::config(&shown, format!("persona file {m}")))?;
60 (shown, text)
61 }
62 };
63 assert!(text.len() <= MAX_PERSONA_BYTES);
64 match text.parse::<toml::Table>() {
65 Ok(table) => Ok(Some((name, table))),
66 Err(_) => Err(Persona::parse(&name, &text)
67 .expect_err("text that is not a TOML table is not a persona")
68 .into()),
69 }
70 }
71
72 pub(crate) fn persona_identity(&self) -> Result<(String, Option<toml::Table>), KitError> {
76 let Some((source, table)) = self.toml_source()? else {
77 return Ok((self.name.clone(), None));
78 };
79 let output = table.get("output").and_then(Toml::as_table).cloned();
80 match table.get("name").and_then(Toml::as_str) {
81 Some(name) if !name.trim().is_empty() => Ok((name.to_string(), output)),
82 _ => Err(KitError::config(&source, "persona needs name = \"...\"")),
83 }
84 }
85
86 pub(crate) fn toml_selector(&self) -> Option<String> {
87 let (_, table) = self.toml_source().ok()??;
88 table.get("model")?.as_str().map(str::to_string)
89 }
90
91 pub(crate) fn toml_persona(
92 &self,
93 source: &str,
94 mut table: toml::Table,
95 model_key: Option<&str>,
96 tools: &[String],
97 ) -> Result<(Persona, String, String), KitError> {
98 let text = |v: &str| Toml::String(v.to_string());
99 for (key, value) in [
100 ("model", &self.model),
101 ("display_name", &self.display_name),
102 ("role", &self.role),
103 ("goal", &self.goal),
104 ] {
105 if let Some(value) = value {
106 table.insert(key.into(), text(value));
107 }
108 }
109 if let Some(instructions) = &self.instructions {
110 table.remove("instructions_file");
111 table.insert("instructions".into(), text(instructions));
112 }
113 if !self.evals.is_empty() {
114 let evals = self.evals.iter().map(|e| text(e)).collect();
115 table.insert("evals".into(), Toml::Array(evals));
116 }
117 if let Some(turns) = self.max_turns {
118 table.insert("max_turns".into(), Toml::Integer(i64::from(turns)));
119 }
120 if let Some(tokens) = self.max_tokens {
121 table.insert("max_tokens".into(), Toml::Integer(i64::from(tokens)));
122 }
123 if let Some(Toml::Array(named)) = table.get_mut("tools") {
124 for tool in tools {
125 if !named.iter().any(|n| n.as_str() == Some(tool)) {
126 named.push(text(tool));
127 }
128 }
129 } else if !table.contains_key("tools") && !tools.is_empty() {
130 let named = tools.iter().map(|t| text(t)).collect();
131 table.insert("tools".into(), Toml::Array(named));
132 }
133 if table.contains_key("instructions_file") && !table.contains_key("instructions") {
134 let body = self.instructions_file(source, &table)?;
135 table.remove("instructions_file");
136 table.insert("instructions".into(), text(&body));
137 }
138 let selector = table
139 .get("model")
140 .and_then(Toml::as_str)
141 .map(str::to_string);
142 if let Some(key) = model_key {
143 table.insert("model".into(), text(key));
144 }
145 let persona_text = toml::to_string(&table)
146 .map_err(|e| KitError::config(source, format!("persona does not serialize: {e}")))?;
147 let persona = Persona::parse(source, &persona_text)?;
148 assert!(persona.instructions_file.is_none());
149 assert!(!persona.instructions.trim().is_empty());
150 let Some(selector) = selector else {
151 return Err(KitError::config(
152 source,
153 "needs a model: set model in the TOML or call .model(\"vendor/model\")",
154 ));
155 };
156 Ok((persona, persona_text, selector))
157 }
158
159 fn instructions_file(&self, source: &str, table: &toml::Table) -> Result<String, KitError> {
160 let Some(PersonaSource::File(persona)) = &self.persona_source else {
161 return Err(KitError::config(
162 source,
163 "instructions_file needs from_toml_file, or call .instructions(..)",
164 ));
165 };
166 let Some(relative) = table.get("instructions_file").and_then(Toml::as_str) else {
167 return Err(KitError::config(
168 source,
169 "instructions_file must be a string",
170 ));
171 };
172 let body = instructions_body(persona, relative)
173 .map_err(|m| KitError::config(source, format!("instructions_file {m}")))?;
174 assert!(body.len() <= MAX_PERSONA_BYTES);
175 assert!(!table.contains_key("instructions"));
176 Ok(body)
177 }
178}
179
180fn instructions_body(persona: &Path, relative: &str) -> Result<String, String> {
185 let relative = Path::new(relative);
186 if relative.is_absolute() || relative.components().any(|c| c == Component::ParentDir) {
187 return Err("must be a relative path without `..`".into());
188 }
189 let extension = match relative.extension().and_then(|e| e.to_str()) {
190 Some("md") => "md",
191 Some("txt") => "txt",
192 _ => return Err("must be a .md or .txt file".into()),
193 };
194 let persona = persona
195 .canonicalize()
196 .map_err(|e| format!("cannot be resolved: {e}"))?;
197 let directory = persona
198 .parent()
199 .expect("a canonical file path has a parent");
200 let joined = directory.join(relative);
201 match std::fs::symlink_metadata(&joined) {
202 Ok(meta) if meta.file_type().is_symlink() => return Err("must not be a symlink".into()),
203 Ok(_) => {}
204 Err(e) if e.kind() == ErrorKind::NotFound => return Err("does not exist".into()),
205 Err(e) => return Err(format!("cannot be read: {e}")),
206 }
207 let canonical = joined
208 .canonicalize()
209 .map_err(|e| format!("cannot be resolved: {e}"))?;
210 if !canonical.starts_with(directory) {
211 return Err("must stay under the persona file's directory".into());
212 }
213 let (read, body) = read_checked(&canonical, extension, MAX_PERSONA_BYTES as u64)?;
214 assert_eq!(read, canonical);
215 assert!(body.len() <= MAX_PERSONA_BYTES);
216 Ok(body)
217}