1use std::fmt;
6use std::io;
7use std::path::{Path, PathBuf};
8
9use base64::Engine;
10use rig_core::completion::Message;
11use rig_core::conversation::{Conversation, EntryRef, FILE_CLOSE, FILE_OPEN, attached_file};
12use rig_core::message::{ImageMediaType, UserContent};
13
14use crate::workspace::{Stat, Workspace, home_path};
15use crate::{MAX_LINES, show_lines};
16
17pub(crate) const MOST_BYTES: u64 = 5 * 1024 * 1024 / 4 * 3;
20
21const MOST_TEXT_BYTES: usize = 32 * 1024;
23
24const EXTENSIONS: [&str; 5] = ["png", "jpg", "jpeg", "gif", "webp"];
26
27pub fn is_image_path(path: &Path) -> bool {
29 path.extension()
30 .and_then(|extension| extension.to_str())
31 .is_some_and(|extension| {
32 EXTENSIONS
33 .iter()
34 .any(|known| extension.eq_ignore_ascii_case(known))
35 })
36}
37
38#[derive(Clone, Debug, Default, PartialEq)]
40pub struct Attached {
41 pub files: Vec<(String, UserContent)>,
44 pub notes: Vec<String>,
47 pub missing: Vec<String>,
50}
51
52pub fn attachments(text: &str, base: &Path, workspace: &dyn Workspace) -> Attached {
64 let mut attached = Attached::default();
65 let mut seen: Vec<PathBuf> = Vec::new();
66 for token in text.split_whitespace() {
67 let Some(reference) = token.strip_prefix('@') else {
68 continue;
69 };
70 let trimmed = reference.trim_end_matches([',', '.', ';', ':', '!', '?', ')', '"', '\'']);
71 if Path::new(trimmed).starts_with("~") && workspace.host().is_some() {
72 attached.notes.push(format!(
73 "{trimmed} is not attached: home paths are this machine's."
74 ));
75 continue;
76 }
77 let found = [reference, trimmed].into_iter().find_map(|named| {
78 let label = home_path(Path::new(named)).unwrap_or_else(|| PathBuf::from(named));
79 let path = base.join(&label);
80 matches!(workspace.stat(&path), Ok(Stat::File { .. }))
81 .then(|| (label.display().to_string(), path))
82 });
83 let Some((label, path)) = found else {
84 if is_path_reference(trimmed) && !attached.missing.iter().any(|seen| seen == trimmed) {
85 attached.missing.push(trimmed.to_owned());
86 }
87 continue;
88 };
89 if seen.contains(&path) {
90 continue;
91 }
92 let read = if is_image_path(&path) {
93 read_image(workspace, &path)
94 } else {
95 read_file(workspace, &path, &label)
96 };
97 match read {
98 Ok(content) => attached.files.push((label, content)),
99 Err(why) => attached
100 .notes
101 .push(format!("{label} is not attached: {why}.")),
102 }
103 seen.push(path);
104 }
105 attached
106}
107
108pub fn is_path_reference(reference: &str) -> bool {
123 reference.contains('/')
124 || reference.rsplit_once('.').is_some_and(|(name, extension)| {
125 !name.is_empty()
126 && (1..=4).contains(&extension.len())
127 && extension.chars().all(|c| c.is_ascii_alphanumeric())
128 })
129}
130
131pub fn read_image(workspace: &dyn Workspace, path: &Path) -> Result<UserContent, String> {
135 let image = image(workspace, path).map_err(|failure| failure.to_string())?;
136 Ok(UserContent::image_base64(
137 image.base64(),
138 Some(image.media_type),
139 None,
140 ))
141}
142
143pub(crate) struct Image {
145 pub bytes: Vec<u8>,
147 pub media_type: ImageMediaType,
149}
150
151impl Image {
152 pub fn base64(&self) -> String {
154 base64::engine::general_purpose::STANDARD.encode(&self.bytes)
155 }
156}
157
158#[derive(Debug)]
160pub(crate) enum NoImage {
161 Read(io::Error),
163 Other,
165 TooLarge(u64),
167}
168
169impl fmt::Display for NoImage {
170 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
171 match self {
172 Self::Read(failure) => write!(formatter, "{failure}"),
173 Self::Other => write!(formatter, "it is not a PNG, JPEG, GIF or WebP image"),
174 Self::TooLarge(size) => write!(
175 formatter,
176 "it is an image of {} KB, more than the {} KB a provider takes",
177 size.div_ceil(1024),
178 MOST_BYTES / 1024
179 ),
180 }
181 }
182}
183
184pub(crate) fn image(workspace: &dyn Workspace, path: &Path) -> Result<Image, NoImage> {
186 let contents = workspace.read(path, MOST_BYTES).map_err(NoImage::Read)?;
187 let media_type = ImageMediaType::sniff(&contents.bytes).ok_or(NoImage::Other)?;
188 if contents.size > MOST_BYTES {
189 return Err(NoImage::TooLarge(contents.size));
190 }
191 Ok(Image {
192 bytes: contents.bytes,
193 media_type,
194 })
195}
196
197fn read_file(workspace: &dyn Workspace, path: &Path, label: &str) -> Result<UserContent, String> {
201 let text = workspace
202 .read_text(path)
203 .map_err(|failure| failure.to_string())?;
204 if text.contains('\0') {
205 return Err("it is not a text file".to_owned());
206 }
207 let lines = show_lines(&text, 1, MAX_LINES, MOST_TEXT_BYTES);
208 Ok(UserContent::text(format!(
209 "{FILE_OPEN}{label}\">\n{lines}{FILE_CLOSE}"
210 )))
211}
212
213pub fn typed(conversation: &Conversation, at: usize) -> Option<String> {
220 typed_in(conversation.entries().nth(at)?)
221}
222
223pub fn typed_prompts(conversation: &Conversation) -> impl Iterator<Item = String> + '_ {
226 conversation.entries().filter_map(typed_in)
227}
228
229fn typed_in(entry: EntryRef<'_>) -> Option<String> {
231 let Message::User { content } = entry.message else {
232 return None;
233 };
234 if !entry.is_users_own() {
235 return None;
236 }
237 let typed: Vec<&str> = content
238 .iter()
239 .filter_map(|content| match content {
240 UserContent::Text(text) if attached_file(&text.text).is_none() => {
241 Some(text.text.trim())
242 }
243 _ => None,
244 })
245 .filter(|text| !text.is_empty())
246 .collect();
247 (!typed.is_empty()).then(|| typed.join("\n\n"))
248}
249
250pub fn first_typed(conversation: &Conversation) -> Option<String> {
252 (0..conversation.messages().len()).find_map(|at| typed(conversation, at))
253}
254
255#[cfg(test)]
256mod tests;