Skip to main content

ag_session/
personality.rs

1//! Workspace personality definitions parsed from `.agents/agents/*/agent.md`.
2
3/// Maximum UTF-8 byte length retained for one personality prompt.
4pub const PERSONALITY_PROMPT_MAX_BYTES: usize = 16 * 1024;
5
6/// One enabled personality loaded from a workspace agent definition.
7#[derive(Clone, Debug, Eq, PartialEq)]
8pub struct Personality {
9    /// Short explanation shown beside the personality name.
10    pub description: String,
11    /// Stable identifier persisted on the owning session.
12    pub id: String,
13    /// Human-readable picker label.
14    pub name: String,
15    /// Behavioral preamble injected into agent turns.
16    pub prompt: String,
17}
18
19impl Personality {
20    /// Returns lightweight picker metadata without retaining the prompt body.
21    #[must_use]
22    pub fn summary(&self) -> PersonalitySummary {
23        PersonalitySummary {
24            description: self.description.clone(),
25            id: self.id.clone(),
26            name: self.name.clone(),
27        }
28    }
29
30    /// Returns a deterministic fingerprint for the selected ID and prompt.
31    ///
32    /// Fingerprints only detect changes; they are not used for cryptographic
33    /// verification. The versioned FNV-1a encoding is stable across processes,
34    /// platforms, and Rust toolchain upgrades.
35    #[must_use]
36    pub fn fingerprint(&self) -> String {
37        let mut fingerprint =
38            Self::update_fnv_1a_fingerprint(FNV_1A_OFFSET_BASIS, PERSONALITY_FINGERPRINT_DOMAIN);
39        for component in [&self.id, &self.prompt] {
40            let byte_length = (component.len() as u128).to_le_bytes();
41            fingerprint = Self::update_fnv_1a_fingerprint(fingerprint, &byte_length);
42            fingerprint = Self::update_fnv_1a_fingerprint(fingerprint, component.as_bytes());
43        }
44
45        format!("{fingerprint:016x}")
46    }
47
48    /// Updates one FNV-1a fingerprint with the supplied bytes.
49    fn update_fnv_1a_fingerprint(mut fingerprint: u64, bytes: &[u8]) -> u64 {
50        for byte in bytes {
51            fingerprint ^= u64::from(*byte);
52            fingerprint = fingerprint.wrapping_mul(FNV_1A_PRIME);
53        }
54
55        fingerprint
56    }
57}
58
59/// Lightweight personality metadata stored in prompt-composer state.
60#[derive(Clone, Debug, Eq, PartialEq)]
61pub struct PersonalitySummary {
62    /// Short explanation shown beside the personality name.
63    pub description: String,
64    /// Stable identifier persisted on the owning session.
65    pub id: String,
66    /// Human-readable picker label.
67    pub name: String,
68}
69
70/// Error returned when one agent definition cannot be parsed safely.
71#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
72pub enum PersonalityParseError {
73    /// The definition does not contain a complete frontmatter block.
74    #[error("missing or incomplete frontmatter")]
75    MissingFrontmatter,
76    /// The simple `key: value` frontmatter is malformed.
77    #[error("invalid frontmatter: {0}")]
78    InvalidFrontmatter(String),
79    /// A required frontmatter value is absent or blank.
80    #[error("missing required `{0}` frontmatter value")]
81    MissingField(&'static str),
82}
83
84/// Parses one `.agents` agent definition.
85///
86/// `directory_id` is used when the optional frontmatter `id` is absent.
87/// Disabled definitions return `Ok(None)` so callers can omit them without
88/// treating intentional configuration as a parse failure.
89///
90/// # Errors
91/// Returns [`PersonalityParseError`] when frontmatter is malformed or a
92/// required name, description, directory fallback ID, or prompt is missing.
93pub fn parse_agent_definition(
94    directory_id: &str,
95    contents: &str,
96) -> Result<Option<Personality>, PersonalityParseError> {
97    let (frontmatter, body) = split_agent_definition(contents)?;
98    let Some(summary) = parse_agent_summary_parts(directory_id, frontmatter)? else {
99        return Ok(None);
100    };
101
102    let prompt = required_value(body, "prompt")?;
103
104    Ok(Some(Personality {
105        description: summary.description,
106        id: summary.id,
107        name: summary.name,
108        prompt: truncate_personality_prompt(prompt),
109    }))
110}
111
112/// Parses lightweight picker metadata from one `.agents` agent definition.
113///
114/// Callers may supply a body reduced to any non-empty placeholder because the
115/// returned value does not retain prompt text. Disabled definitions return
116/// `Ok(None)`.
117///
118/// # Errors
119/// Returns [`PersonalityParseError`] under the same validation rules as
120/// [`parse_agent_definition`].
121pub fn parse_agent_summary(
122    directory_id: &str,
123    contents: &str,
124) -> Result<Option<PersonalitySummary>, PersonalityParseError> {
125    let (frontmatter, body) = split_agent_definition(contents)?;
126    let Some(summary) = parse_agent_summary_parts(directory_id, frontmatter)? else {
127        return Ok(None);
128    };
129    required_value(body, "prompt")?;
130
131    Ok(Some(summary))
132}
133
134/// FNV-1a domain separator for the stable personality fingerprint encoding.
135const PERSONALITY_FINGERPRINT_DOMAIN: &[u8] = b"agentty-personality-v1";
136
137/// FNV-1a 64-bit offset basis.
138const FNV_1A_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
139
140/// FNV-1a 64-bit prime.
141const FNV_1A_PRIME: u64 = 0x0000_0100_0000_01b3;
142
143/// Marker appended when a personality prompt exceeds the supported budget.
144const PERSONALITY_PROMPT_TRUNCATION_MARKER: &str = "\n\n[Personality prompt truncated at 16 KiB.]";
145
146/// Supported fields decoded from one `.agents` frontmatter block.
147#[derive(Default)]
148struct AgentFrontmatter {
149    description: Option<String>,
150    enabled: Option<bool>,
151    id: Option<String>,
152    name: Option<String>,
153}
154
155impl AgentFrontmatter {
156    /// Parses the protocol's simple line-oriented `key: value` frontmatter.
157    fn parse(frontmatter: &str) -> Result<Self, PersonalityParseError> {
158        let mut parsed = Self::default();
159
160        for (line_index, line) in frontmatter.lines().enumerate() {
161            let line_number = line_index.saturating_add(1);
162            let line = line.trim();
163            if line.is_empty() {
164                continue;
165            }
166
167            let Some((key, value)) = line.split_once(':') else {
168                return Err(Self::invalid_frontmatter_line(
169                    line_number,
170                    "expected `key: value`",
171                ));
172            };
173            let key = key.trim();
174            if key.is_empty() {
175                return Err(Self::invalid_frontmatter_line(line_number, "key is empty"));
176            }
177
178            let value = Self::parse_frontmatter_value(value.trim(), line_number)?;
179
180            match key {
181                "description" => {
182                    Self::set_frontmatter_string(&mut parsed.description, key, value, line_number)?;
183                }
184                "enabled" => {
185                    if parsed.enabled.is_some() {
186                        return Err(Self::invalid_frontmatter_line(
187                            line_number,
188                            "duplicate `enabled` field",
189                        ));
190                    }
191                    parsed.enabled = Some(match value {
192                        "true" => true,
193                        "false" => false,
194                        _ => {
195                            return Err(Self::invalid_frontmatter_line(
196                                line_number,
197                                "`enabled` must be `true` or `false`",
198                            ));
199                        }
200                    });
201                }
202                "id" => {
203                    Self::set_frontmatter_string(&mut parsed.id, key, value, line_number)?;
204                }
205                "name" => {
206                    Self::set_frontmatter_string(&mut parsed.name, key, value, line_number)?;
207                }
208                _ => {}
209            }
210        }
211
212        Ok(parsed)
213    }
214
215    /// Builds one line-numbered frontmatter parsing error.
216    fn invalid_frontmatter_line(line_number: usize, message: &str) -> PersonalityParseError {
217        PersonalityParseError::InvalidFrontmatter(format!("line {line_number}: {message}"))
218    }
219
220    /// Removes matching single or double quotes from one frontmatter value.
221    fn parse_frontmatter_value(
222        value: &str,
223        line_number: usize,
224    ) -> Result<&str, PersonalityParseError> {
225        let Some(quote) = value
226            .chars()
227            .next()
228            .filter(|quote| matches!(quote, '\'' | '"'))
229        else {
230            return Ok(value);
231        };
232        if value.len() < 2 || !value.ends_with(quote) {
233            return Err(Self::invalid_frontmatter_line(
234                line_number,
235                "quoted value is not terminated",
236            ));
237        }
238
239        Ok(&value[quote.len_utf8()..value.len().saturating_sub(quote.len_utf8())])
240    }
241
242    /// Assigns one supported string field and rejects duplicates.
243    fn set_frontmatter_string(
244        target: &mut Option<String>,
245        key: &str,
246        value: &str,
247        line_number: usize,
248    ) -> Result<(), PersonalityParseError> {
249        if target.is_some() {
250            return Err(Self::invalid_frontmatter_line(
251                line_number,
252                &format!("duplicate `{key}` field"),
253            ));
254        }
255
256        *target = Some(value.to_string());
257
258        Ok(())
259    }
260}
261
262/// Splits an agent definition into simple frontmatter and Markdown body.
263fn split_agent_definition(contents: &str) -> Result<(&str, &str), PersonalityParseError> {
264    let mut lines = contents.split_inclusive('\n');
265    let first_line = lines
266        .next()
267        .ok_or(PersonalityParseError::MissingFrontmatter)?;
268    if first_line.trim() != "---" {
269        return Err(PersonalityParseError::MissingFrontmatter);
270    }
271
272    let frontmatter_start = first_line.len();
273    let mut line_start = frontmatter_start;
274
275    for line in lines {
276        if line.trim() == "---" {
277            let body_start = line_start.saturating_add(line.len());
278
279            return Ok((
280                &contents[frontmatter_start..line_start],
281                &contents[body_start..],
282            ));
283        }
284
285        line_start = line_start.saturating_add(line.len());
286    }
287
288    Err(PersonalityParseError::MissingFrontmatter)
289}
290
291/// Validates frontmatter and builds lightweight picker metadata.
292fn parse_agent_summary_parts(
293    directory_id: &str,
294    frontmatter: &str,
295) -> Result<Option<PersonalitySummary>, PersonalityParseError> {
296    let frontmatter = AgentFrontmatter::parse(frontmatter)?;
297    if frontmatter.enabled == Some(false) {
298        return Ok(None);
299    }
300
301    let id = required_value(frontmatter.id.as_deref().unwrap_or(directory_id), "id")?;
302    let name = required_value(frontmatter.name.as_deref().unwrap_or_default(), "name")?;
303    let description = required_value(
304        frontmatter.description.as_deref().unwrap_or_default(),
305        "description",
306    )?;
307
308    Ok(Some(PersonalitySummary {
309        description: description.to_string(),
310        id: id.to_string(),
311        name: name.to_string(),
312    }))
313}
314
315/// Returns one non-empty required value.
316fn required_value<'a>(
317    value: &'a str,
318    field: &'static str,
319) -> Result<&'a str, PersonalityParseError> {
320    let value = value.trim();
321    if value.is_empty() {
322        return Err(PersonalityParseError::MissingField(field));
323    }
324
325    Ok(value)
326}
327
328/// Truncates a prompt at a UTF-8 boundary while retaining the marker budget.
329fn truncate_personality_prompt(prompt: &str) -> String {
330    if prompt.len() <= PERSONALITY_PROMPT_MAX_BYTES {
331        return prompt.to_string();
332    }
333
334    let content_budget =
335        PERSONALITY_PROMPT_MAX_BYTES.saturating_sub(PERSONALITY_PROMPT_TRUNCATION_MARKER.len());
336    let mut boundary = content_budget.min(prompt.len());
337    while !prompt.is_char_boundary(boundary) {
338        boundary = boundary.saturating_sub(1);
339    }
340
341    format!(
342        "{}{}",
343        prompt[..boundary].trim_end(),
344        PERSONALITY_PROMPT_TRUNCATION_MARKER
345    )
346}
347
348#[cfg(test)]
349#[path = "personality_test.rs"]
350mod tests;