Skip to main content

ag_protocol/
prompt.rs

1//! Transport-neutral prompt payloads shared by frontends and agent adapters.
2
3use std::fmt;
4use std::fmt::Write as _;
5use std::path::PathBuf;
6
7/// One local image attachment referenced from a prompt placeholder.
8///
9/// Serialized JSON consumers must match fields by name; object key order is
10/// not part of this transport contract.
11#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
12pub struct TurnPromptAttachment {
13    /// Local file path persisted for transport upload.
14    pub local_image_path: PathBuf,
15    /// Inline placeholder token such as `[Image #1]` used in prompt text.
16    pub placeholder: String,
17}
18
19/// Structured prompt payload for one agent turn.
20#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
21pub struct TurnPrompt {
22    /// Ordered local image attachments referenced by `text`.
23    pub attachments: Vec<TurnPromptAttachment>,
24    /// Prompt text payload, including inline placeholders when present.
25    pub text: String,
26    /// Source classification that controls prompt-only text rewrites.
27    #[serde(default)]
28    pub text_source: TurnPromptTextSource,
29}
30
31impl TurnPrompt {
32    /// Creates a text-only prompt payload.
33    #[must_use]
34    pub fn from_text(text: String) -> Self {
35        Self {
36            attachments: Vec::new(),
37            text,
38            text_source: TurnPromptTextSource::UserPrompt,
39        }
40    }
41
42    /// Creates a generated-data prompt payload that is sent to the agent
43    /// without user prompt `@path` lookup rewriting.
44    #[must_use]
45    pub fn from_agent_data(text: String) -> Self {
46        Self {
47            attachments: Vec::new(),
48            text,
49            text_source: TurnPromptTextSource::AgentData,
50        }
51    }
52
53    /// Returns whether the payload contains no text and no attachments.
54    #[must_use]
55    pub fn is_empty(&self) -> bool {
56        self.text.is_empty() && self.attachments.is_empty()
57    }
58
59    /// Returns whether the payload contains one or more image attachments.
60    #[must_use]
61    pub fn has_attachments(&self) -> bool {
62        !self.attachments.is_empty()
63    }
64
65    /// Returns the local image paths referenced by this prompt payload.
66    pub fn local_image_paths(&self) -> impl Iterator<Item = &PathBuf> {
67        self.attachments
68            .iter()
69            .map(|attachment| &attachment.local_image_path)
70    }
71
72    /// Returns whether the prompt text contains `needle`.
73    #[must_use]
74    pub fn contains(&self, needle: &str) -> bool {
75        self.text.contains(needle)
76    }
77
78    /// Returns whether the prompt text ends with `suffix`.
79    #[must_use]
80    pub fn ends_with(&self, suffix: &str) -> bool {
81        self.text.ends_with(suffix)
82    }
83
84    /// Returns the prompt text as it should be sent to an agent runtime.
85    ///
86    /// User-authored `@path` lookups are rewritten to quoted path tokens for
87    /// transport. Generated agent data is returned unchanged so source content
88    /// such as Python decorators keeps its leading `@`.
89    #[must_use]
90    pub fn agent_text(&self) -> String {
91        match self.text_source {
92            TurnPromptTextSource::UserPrompt => render_prompt_text_for_agent(&self.text),
93            TurnPromptTextSource::AgentData => self.text.clone(),
94        }
95    }
96
97    /// Returns prompt text spans and image attachments in transport order.
98    ///
99    /// Attachments are ordered by their placeholder position in `text`. Any
100    /// attachment whose placeholder no longer exists in the text is appended
101    /// after the trailing text so transports can still serialize the image
102    /// instead of dropping it silently.
103    #[must_use]
104    pub fn content_parts(&self) -> Vec<TurnPromptContentPart<'_>> {
105        split_turn_prompt_content(&self.text, &self.attachments)
106    }
107
108    /// Appends `attachments` after the current text under fresh placeholders.
109    ///
110    /// Structured prompts embed user text as data, so the original composer
111    /// placeholders such as `[Image #1]` may appear inside that data and may
112    /// repeat across replies. Each image therefore gets a numbered reference
113    /// line whose placeholder does not occur anywhere in the existing text.
114    pub fn append_trailing_attachments<'attachment>(
115        &mut self,
116        attachments: impl IntoIterator<Item = &'attachment TurnPromptAttachment>,
117    ) {
118        for (index, attachment) in attachments.into_iter().enumerate() {
119            let number = index + 1;
120            let mut placeholder = format!("[Task image #{number}]");
121            while self.text.contains(&placeholder) {
122                placeholder.insert(1, '#');
123            }
124            let _ = write!(
125                self.text,
126                "\n\nTask input attachment {number}: {placeholder}"
127            );
128            self.attachments.push(TurnPromptAttachment {
129                local_image_path: attachment.local_image_path.clone(),
130                placeholder,
131            });
132        }
133    }
134
135    /// Returns the prompt text as it should be written into persisted
136    /// transcripts.
137    ///
138    /// Inline `[Image #n]` markers are preserved verbatim. If attachment
139    /// metadata somehow survives without its placeholder still present in the
140    /// text, the missing placeholders are appended in attachment order so the
141    /// transcript does not silently become text-only.
142    #[must_use]
143    pub fn transcript_text(&self) -> String {
144        let mut transcript_text = self.text.clone();
145        let missing_placeholders = self
146            .attachments
147            .iter()
148            .filter(|attachment| !self.text.contains(&attachment.placeholder))
149            .map(|attachment| attachment.placeholder.as_str())
150            .collect::<Vec<_>>();
151
152        if missing_placeholders.is_empty() {
153            return transcript_text;
154        }
155
156        if transcript_text
157            .chars()
158            .last()
159            .is_some_and(|character| !character.is_whitespace())
160        {
161            transcript_text.push(' ');
162        }
163
164        transcript_text.push_str(&missing_placeholders.join(" "));
165
166        transcript_text
167    }
168}
169
170impl From<String> for TurnPrompt {
171    fn from(text: String) -> Self {
172        Self::from_text(text)
173    }
174}
175
176impl From<&str> for TurnPrompt {
177    fn from(text: &str) -> Self {
178        Self::from_text(text.to_string())
179    }
180}
181
182impl From<&TurnPrompt> for TurnPrompt {
183    fn from(prompt: &TurnPrompt) -> Self {
184        prompt.clone()
185    }
186}
187
188impl fmt::Display for TurnPrompt {
189    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
190        formatter.write_str(&self.text)
191    }
192}
193
194impl PartialEq<&str> for TurnPrompt {
195    fn eq(&self, other: &&str) -> bool {
196        self.text == *other
197    }
198}
199
200impl PartialEq<TurnPrompt> for &str {
201    fn eq(&self, other: &TurnPrompt) -> bool {
202        *self == other.text
203    }
204}
205
206/// Source classification for one turn prompt text payload.
207#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
208pub enum TurnPromptTextSource {
209    /// User-authored prompt text where `@path` lookup tokens should be
210    /// converted before transport delivery.
211    #[default]
212    UserPrompt,
213    /// Agent-facing generated data such as utility prompts, protocol repair
214    /// prompts, diffs, and transcript previews that must be sent unchanged.
215    AgentData,
216}
217
218/// Ordered content piece produced when serializing one turn prompt.
219#[derive(Debug, Clone, Copy, Eq, PartialEq)]
220pub enum TurnPromptContentPart<'prompt> {
221    /// One local image attachment referenced from the prompt text.
222    Attachment(&'prompt TurnPromptAttachment),
223    /// One attachment whose placeholder no longer appears in the prompt text.
224    OrphanAttachment(&'prompt TurnPromptAttachment),
225    /// One plain-text span from the prompt.
226    Text(&'prompt str),
227}
228
229/// Rewrites user-entered `@` lookups into quoted agent-facing path tokens.
230///
231/// File and directory lookups like `@path/to/file` are rewritten to
232/// `"path/to/file"`. Non-lookup uses of `@`, including email-like tokens and
233/// lone `@`, are preserved so frontends and persisted transcripts can continue
234/// storing the original user input unchanged.
235#[must_use]
236pub fn render_prompt_text_for_agent(text: &str) -> String {
237    let characters = text.chars().collect::<Vec<char>>();
238    let mut output = String::with_capacity(text.len());
239    let mut index = 0;
240
241    while let Some(&character) = characters.get(index) {
242        if character != '@'
243            || !is_at_mention_boundary(characters.get(index.wrapping_sub(1)).copied())
244            || index + 1 >= characters.len()
245        {
246            output.push(character);
247            index += 1;
248
249            continue;
250        }
251
252        let mut scan_index = index + 1;
253        while scan_index < characters.len() && is_at_mention_query_character(characters[scan_index])
254        {
255            scan_index += 1;
256        }
257
258        if scan_index == index + 1 {
259            output.push(character);
260            index += 1;
261
262            continue;
263        }
264
265        output.push('"');
266        output.extend(characters[index + 1..scan_index].iter());
267        output.push('"');
268        index = scan_index;
269    }
270
271    output
272}
273
274/// Splits prompt text into ordered text and attachment parts for transport
275/// serialization.
276#[must_use]
277pub fn split_turn_prompt_content<'prompt>(
278    text: &'prompt str,
279    attachments: &'prompt [TurnPromptAttachment],
280) -> Vec<TurnPromptContentPart<'prompt>> {
281    if attachments.is_empty() {
282        return vec![TurnPromptContentPart::Text(text)];
283    }
284
285    let mut ordered_attachments = attachments.iter().collect::<Vec<_>>();
286    ordered_attachments
287        // Attachments without an inline placeholder are appended after the
288        // text-bearing attachments so transcript order stays deterministic.
289        .sort_by_key(|attachment| text.find(&attachment.placeholder).unwrap_or(usize::MAX));
290
291    let mut content_parts = Vec::new();
292    let mut orphan_attachments = Vec::new();
293    let mut remaining_text = text;
294
295    for attachment in ordered_attachments {
296        if let Some(placeholder_index) = remaining_text.find(&attachment.placeholder) {
297            let (before_placeholder, after_placeholder) =
298                remaining_text.split_at(placeholder_index);
299
300            if !before_placeholder.is_empty() {
301                content_parts.push(TurnPromptContentPart::Text(before_placeholder));
302            }
303
304            content_parts.push(TurnPromptContentPart::Attachment(attachment));
305            remaining_text = &after_placeholder[attachment.placeholder.len()..];
306
307            continue;
308        }
309
310        orphan_attachments.push(attachment);
311    }
312
313    if !remaining_text.is_empty() {
314        content_parts.push(TurnPromptContentPart::Text(remaining_text));
315    }
316
317    content_parts.extend(
318        orphan_attachments
319            .into_iter()
320            .map(TurnPromptContentPart::OrphanAttachment),
321    );
322
323    content_parts
324}
325
326/// Returns whether the character before `@` starts a file lookup token.
327fn is_at_mention_boundary(previous_character: Option<char>) -> bool {
328    previous_character.is_none_or(|character| {
329        character.is_whitespace() || is_at_mention_opening_delimiter(character)
330    })
331}
332
333/// Returns whether `character` can appear inside an active `@` lookup token.
334fn is_at_mention_query_character(character: char) -> bool {
335    character.is_alphanumeric() || matches!(character, '/' | '.' | '_' | '-')
336}
337
338/// Returns whether `character` is an opening delimiter that can precede `@`.
339fn is_at_mention_opening_delimiter(character: char) -> bool {
340    matches!(character, '(' | '[' | '{')
341}
342
343#[cfg(test)]
344#[path = "prompt_test.rs"]
345mod tests;