1use std::fmt;
4use std::fmt::Write as _;
5use std::path::PathBuf;
6
7#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
12pub struct TurnPromptAttachment {
13 pub local_image_path: PathBuf,
15 pub placeholder: String,
17}
18
19#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
21pub struct TurnPrompt {
22 pub attachments: Vec<TurnPromptAttachment>,
24 pub text: String,
26 #[serde(default)]
28 pub text_source: TurnPromptTextSource,
29}
30
31impl TurnPrompt {
32 #[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 #[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 #[must_use]
55 pub fn is_empty(&self) -> bool {
56 self.text.is_empty() && self.attachments.is_empty()
57 }
58
59 #[must_use]
61 pub fn has_attachments(&self) -> bool {
62 !self.attachments.is_empty()
63 }
64
65 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 #[must_use]
74 pub fn contains(&self, needle: &str) -> bool {
75 self.text.contains(needle)
76 }
77
78 #[must_use]
80 pub fn ends_with(&self, suffix: &str) -> bool {
81 self.text.ends_with(suffix)
82 }
83
84 #[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 #[must_use]
104 pub fn content_parts(&self) -> Vec<TurnPromptContentPart<'_>> {
105 split_turn_prompt_content(&self.text, &self.attachments)
106 }
107
108 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 #[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#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
208pub enum TurnPromptTextSource {
209 #[default]
212 UserPrompt,
213 AgentData,
216}
217
218#[derive(Debug, Clone, Copy, Eq, PartialEq)]
220pub enum TurnPromptContentPart<'prompt> {
221 Attachment(&'prompt TurnPromptAttachment),
223 OrphanAttachment(&'prompt TurnPromptAttachment),
225 Text(&'prompt str),
227}
228
229#[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#[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 .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
326fn 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
333fn is_at_mention_query_character(character: char) -> bool {
335 character.is_alphanumeric() || matches!(character, '/' | '.' | '_' | '-')
336}
337
338fn is_at_mention_opening_delimiter(character: char) -> bool {
340 matches!(character, '(' | '[' | '{')
341}
342
343#[cfg(test)]
344#[path = "prompt_test.rs"]
345mod tests;