Skip to main content

vtcode_core/utils/at_pattern/
mod.rs

1//! # @ Pattern Parsing Utilities
2//!
3//! This module provides utilities for parsing @ symbol patterns in user input
4//! to automatically load and embed image files as base64-encoded content
5//! for LLM processing.
6
7use anyhow::Result;
8use regex::Regex;
9use std::path::{Path, PathBuf};
10use std::sync::LazyLock;
11
12use crate::llm::provider::{ContentPart, MessageContent};
13use crate::utils::file_input::read_input_file_any_path;
14use crate::utils::image_processing::{read_image_file_any_path, read_image_from_url};
15use vtcode_commons::fs::{is_windows_absolute_path, trim_trailing_image_path_str, unescape_whitespace};
16use vtcode_commons::paths::is_safe_relative_path;
17
18#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
19pub struct AtPatternOptions {
20    pub allow_local_non_image_file_inputs: bool,
21    pub allow_remote_non_image_file_inputs: bool,
22}
23
24/// Parse the @ pattern in text and replace image file paths/URLs with base64 content
25///
26/// The function looks for patterns like `@./path/to/image.png`, `@image.jpg`, or `@https://example.com/image.png`
27/// and replaces them with base64 encoded content that can be processed by LLMs
28///
29/// # Arguments
30///
31/// * `input` - The user input text that may contain @ patterns
32/// * `base_dir` - The base directory to resolve relative paths from
33///
34/// # Returns
35///
36/// * `MessageContent` - Either a single text string or multiple content parts
37///   containing both text and base64-encoded images
38pub async fn parse_at_patterns(input: &str, base_dir: &Path) -> Result<MessageContent> {
39    parse_at_patterns_with_options(input, base_dir, AtPatternOptions::default()).await
40}
41
42/// Parse the @ pattern in text with provider-specific input options.
43pub async fn parse_at_patterns_with_options(
44    input: &str,
45    base_dir: &Path,
46    options: AtPatternOptions,
47) -> Result<MessageContent> {
48    let at_matches = vtcode_commons::at_pattern::find_at_patterns(input);
49    let protected_ranges: Vec<(usize, usize)> = at_matches.iter().map(|m| (m.start, m.end)).collect();
50    let raw_matches = find_raw_image_path_matches(input, &protected_ranges);
51    let data_url_matches = find_data_url_matches(input, &protected_ranges);
52
53    if at_matches.is_empty() && raw_matches.is_empty() && data_url_matches.is_empty() {
54        return Ok(MessageContent::text(input.to_string()));
55    }
56
57    let mut matches: Vec<PathMatch> = Vec::new();
58    for m in at_matches {
59        matches.push(PathMatch::At {
60            start: m.start,
61            end: m.end,
62            full_match: m.full_match.to_string(),
63            path: m.path.to_string(),
64        });
65    }
66    for m in raw_matches {
67        matches.push(PathMatch::Raw { start: m.start, end: m.end, raw: m.raw });
68    }
69    for m in data_url_matches {
70        matches.push(PathMatch::DataUrl {
71            start: m.start,
72            end: m.end,
73            mime_type: m.mime_type,
74            data: m.data,
75        });
76    }
77    matches.sort_by_key(|m| m.start());
78
79    let mut parts = Vec::with_capacity(matches.len());
80    let mut last_end = 0;
81
82    for m in matches {
83        let match_start = m.start();
84        let match_end = m.end();
85
86        if match_start < last_end {
87            continue;
88        }
89
90        if match_start > last_end {
91            let text_before = &input[last_end..match_start];
92            if !text_before.trim().is_empty() {
93                parts.push(ContentPart::text(text_before.to_string()));
94            }
95        }
96
97        match m {
98            PathMatch::At { full_match, path, .. } => {
99                let is_url = path.starts_with("http://") || path.starts_with("https://");
100                if is_url {
101                    if looks_like_image_url(&path) {
102                        match read_image_from_url(&path).await {
103                            Ok(image_data) => {
104                                parts.push(ContentPart::Image {
105                                    data: image_data.base64_data,
106                                    mime_type: image_data.mime_type,
107                                    content_type: "image".to_owned(),
108                                    detail: None,
109                                    image_url: None,
110                                });
111                            }
112                            Err(e) => {
113                                tracing::warn!("Failed to load image from URL {}: {}", path, e);
114                                parts.push(ContentPart::text(full_match));
115                            }
116                        }
117                    } else if options.allow_remote_non_image_file_inputs {
118                        parts.push(ContentPart::file_from_url(path));
119                    } else {
120                        parts.push(ContentPart::text(full_match));
121                    }
122                } else if let Some(file_path) = resolve_image_path(&path, base_dir) {
123                    if crate::utils::image_processing::has_supported_image_extension(&file_path) {
124                        match read_image_file_any_path(&file_path).await {
125                            Ok(image_data) => {
126                                parts.push(ContentPart::Image {
127                                    data: image_data.base64_data,
128                                    mime_type: image_data.mime_type,
129                                    content_type: "image".to_owned(),
130                                    detail: None,
131                                    image_url: None,
132                                });
133                            }
134                            Err(_) => {
135                                parts.push(ContentPart::text(full_match));
136                            }
137                        }
138                    } else if options.allow_local_non_image_file_inputs {
139                        match read_input_file_any_path(&file_path).await {
140                            Ok(file_data) => {
141                                parts.push(ContentPart::file_from_data(file_data.filename, file_data.base64_data));
142                            }
143                            Err(_) => {
144                                parts.push(ContentPart::text(full_match));
145                            }
146                        }
147                    } else {
148                        parts.push(ContentPart::text(full_match));
149                    }
150                } else {
151                    parts.push(ContentPart::text(full_match));
152                }
153            }
154            PathMatch::Raw { raw, .. } => {
155                if let Some(image_path) = resolve_image_path(&raw, base_dir) {
156                    if !image_path.exists() {
157                        parts.push(ContentPart::text(raw));
158                        continue;
159                    }
160                    match read_image_file_any_path(&image_path).await {
161                        Ok(image_data) => {
162                            parts.push(ContentPart::Image {
163                                data: image_data.base64_data,
164                                mime_type: image_data.mime_type,
165                                content_type: "image".to_owned(),
166                                detail: None,
167                                image_url: None,
168                            });
169                        }
170                        Err(_) => {
171                            parts.push(ContentPart::text(raw));
172                        }
173                    }
174                } else {
175                    parts.push(ContentPart::text(raw));
176                }
177            }
178            PathMatch::DataUrl { mime_type, data, .. } => {
179                parts.push(ContentPart::Image {
180                    data,
181                    mime_type,
182                    content_type: "image".to_owned(),
183                    detail: None,
184                    image_url: None,
185                });
186            }
187        }
188
189        last_end = match_end;
190    }
191
192    if last_end < input.len() {
193        let text_after = &input[last_end..];
194        if !text_after.trim().is_empty() {
195            parts.push(ContentPart::text(text_after.to_string()));
196        }
197    }
198
199    if parts.is_empty() {
200        return Ok(MessageContent::text(input.to_string()));
201    }
202
203    if parts.iter().all(|part| matches!(part, ContentPart::Text { .. })) {
204        let text = parts.iter().filter_map(ContentPart::as_text).collect::<String>();
205        return Ok(MessageContent::text(text));
206    }
207
208    Ok(MessageContent::parts(parts))
209}
210
211/// Returns true when `input` contains an image reference that this parser would
212/// attempt to turn into an image content part.
213pub fn input_may_parse_image_parts(input: &str, base_dir: &Path) -> bool {
214    let at_matches = vtcode_commons::at_pattern::find_at_patterns(input);
215    let protected_ranges: Vec<(usize, usize)> = at_matches.iter().map(|m| (m.start, m.end)).collect();
216
217    if at_matches.iter().any(|m| {
218        let path = m.path;
219        if path.starts_with("http://") || path.starts_with("https://") {
220            looks_like_image_url(path)
221        } else {
222            resolve_image_path(path, base_dir).is_some_and(|file_path| {
223                crate::utils::image_processing::has_supported_image_extension(&file_path) && file_path.exists()
224            })
225        }
226    }) {
227        return true;
228    }
229
230    if find_raw_image_path_matches(input, &protected_ranges)
231        .iter()
232        .any(|m| resolve_image_path(&m.raw, base_dir).is_some_and(|image_path| image_path.exists()))
233    {
234        return true;
235    }
236
237    !find_data_url_matches(input, &protected_ranges).is_empty()
238}
239
240#[derive(Debug)]
241struct RawPathMatch {
242    start: usize,
243    end: usize,
244    raw: String,
245}
246
247#[derive(Debug)]
248struct DataUrlMatch {
249    start: usize,
250    end: usize,
251    mime_type: String,
252    data: String,
253}
254
255#[derive(Debug)]
256enum PathMatch {
257    At {
258        start: usize,
259        end: usize,
260        full_match: String,
261        path: String,
262    },
263    Raw {
264        start: usize,
265        end: usize,
266        raw: String,
267    },
268    DataUrl {
269        start: usize,
270        end: usize,
271        mime_type: String,
272        data: String,
273    },
274}
275
276impl PathMatch {
277    fn start(&self) -> usize {
278        match self {
279            PathMatch::At { start, .. } | PathMatch::Raw { start, .. } => *start,
280            PathMatch::DataUrl { start, .. } => *start,
281        }
282    }
283
284    fn end(&self) -> usize {
285        match self {
286            PathMatch::At { end, .. } | PathMatch::Raw { end, .. } => *end,
287            PathMatch::DataUrl { end, .. } => *end,
288        }
289    }
290}
291
292fn find_raw_image_path_matches(input: &str, protected_ranges: &[(usize, usize)]) -> Vec<RawPathMatch> {
293    let mut matches = Vec::new();
294    let mut quote_ranges = Vec::new();
295    let mut active_quote: Option<(char, usize)> = None;
296
297    for (idx, ch) in input.char_indices() {
298        match active_quote {
299            Some((quote, start)) => {
300                if ch == quote {
301                    let end = idx + ch.len_utf8();
302                    quote_ranges.push((start, end));
303                    let inner_start = start + quote.len_utf8();
304                    let inner_end = idx;
305                    if inner_end > inner_start && !overlaps_range(inner_start, inner_end, protected_ranges) {
306                        let inner = &input[inner_start..inner_end];
307                        if looks_like_image_path(inner) {
308                            matches.push(RawPathMatch {
309                                start: inner_start,
310                                end: inner_end,
311                                raw: inner.to_string(),
312                            });
313                        }
314                    }
315                    active_quote = None;
316                }
317            }
318            None => {
319                if ch == '"' || ch == '\'' {
320                    active_quote = Some((ch, idx));
321                }
322            }
323        }
324    }
325
326    add_spacey_absolute_path_matches(input, protected_ranges, &quote_ranges, &mut matches);
327
328    let mut quote_idx = 0usize;
329    let mut token_start: Option<usize> = None;
330    let mut pos = 0usize;
331    while pos < input.len() {
332        if let Some((range_start, range_end)) = quote_ranges.get(quote_idx).copied() {
333            if pos >= range_end {
334                quote_idx += 1;
335                continue;
336            }
337            if pos >= range_start {
338                if let Some(start) = token_start.take() {
339                    collect_unquoted_match(input, start, range_start, protected_ranges, &mut matches);
340                }
341                pos = range_end;
342                continue;
343            }
344        }
345
346        let Some(ch) = input[pos..].chars().next() else {
347            break;
348        };
349        if ch.is_ascii_whitespace() {
350            if let Some(start) = token_start.take() {
351                collect_unquoted_match(input, start, pos, protected_ranges, &mut matches);
352            }
353            pos += ch.len_utf8();
354            continue;
355        }
356
357        if ch == '\\'
358            && let Some(next) = input[pos + ch.len_utf8()..].chars().next()
359            && next.is_ascii_whitespace()
360        {
361            if token_start.is_none() {
362                token_start = Some(pos);
363            }
364            pos += ch.len_utf8() + next.len_utf8();
365            continue;
366        }
367
368        if token_start.is_none() {
369            token_start = Some(pos);
370        }
371        pos += ch.len_utf8();
372    }
373
374    if let Some(start) = token_start.take() {
375        collect_unquoted_match(input, start, input.len(), protected_ranges, &mut matches);
376    }
377
378    matches
379}
380
381static DATA_IMAGE_URL_REGEX: LazyLock<Regex> = LazyLock::new(|| {
382    match Regex::new(
383        r#"(?ix)
384        (?:^|[\s\(\[\{<\"'`])
385        (
386            data:image/[a-z0-9+\-\.]+;base64,[a-z0-9+/=]+
387        )"#,
388    ) {
389        Ok(regex) => regex,
390        Err(error) => panic!("Failed to compile data image regex: {error}"),
391    }
392});
393
394fn find_data_url_matches(input: &str, protected_ranges: &[(usize, usize)]) -> Vec<DataUrlMatch> {
395    DATA_IMAGE_URL_REGEX
396        .captures_iter(input)
397        .filter_map(|capture| {
398            let data_match = capture.get(1)?;
399            let start = data_match.start();
400            let end = data_match.end();
401            if overlaps_range(start, end, protected_ranges) {
402                return None;
403            }
404            let raw = data_match.as_str();
405            let (mime_type, data) = parse_data_image_url(raw)?;
406            Some(DataUrlMatch { start, end, mime_type, data })
407        })
408        .collect()
409}
410
411static ABSOLUTE_IMAGE_PATH_REGEX: LazyLock<Regex> = LazyLock::new(|| {
412    match Regex::new(
413        r#"(?ix)
414        (?:^|[\s\(\[\{<\"'`])
415        (
416            (?:file://)?(?:~/|[A-Za-z]:[\\/]|/)
417            [^\n]+?
418            \.(?:png|jpe?g|gif|webp)
419        )"#,
420    ) {
421        Ok(regex) => regex,
422        Err(error) => panic!("Failed to compile absolute image path regex: {error}"),
423    }
424});
425
426fn add_spacey_absolute_path_matches(
427    input: &str,
428    protected_ranges: &[(usize, usize)],
429    quote_ranges: &[(usize, usize)],
430    matches: &mut Vec<RawPathMatch>,
431) {
432    for capture in ABSOLUTE_IMAGE_PATH_REGEX.captures_iter(input) {
433        let Some(path_match) = capture.get(1) else {
434            continue;
435        };
436        let start = path_match.start();
437        let full_end = path_match.end();
438        if overlaps_range(start, full_end, protected_ranges) {
439            continue;
440        }
441        if overlaps_range(start, full_end, quote_ranges) {
442            continue;
443        }
444        if matches
445            .iter()
446            .any(|existing| ranges_overlap(start, full_end, existing.start, existing.end))
447        {
448            continue;
449        }
450
451        // The regex may greedily consume trailing text after the image extension.
452        // Try progressively shorter suffixes to find the actual image path.
453        let raw = path_match.as_str();
454        let trimmed = trim_trailing_image_path_str(raw);
455        let end = start + trimmed.len();
456
457        matches.push(RawPathMatch { start, end, raw: trimmed.to_string() });
458    }
459}
460
461fn ranges_overlap(start: usize, end: usize, other_start: usize, other_end: usize) -> bool {
462    start < other_end && end > other_start
463}
464
465fn collect_unquoted_match(
466    input: &str,
467    start: usize,
468    end: usize,
469    protected_ranges: &[(usize, usize)],
470    matches: &mut Vec<RawPathMatch>,
471) {
472    let Some((trim_start, trim_end)) = trim_token_bounds(input, start, end) else {
473        return;
474    };
475    if overlaps_range(trim_start, trim_end, protected_ranges) {
476        return;
477    }
478
479    let token = &input[trim_start..trim_end];
480    if token.starts_with('@') {
481        return;
482    }
483    if looks_like_image_path(token) {
484        matches.push(RawPathMatch {
485            start: trim_start,
486            end: trim_end,
487            raw: token.to_string(),
488        });
489    }
490}
491
492fn trim_token_bounds(input: &str, start: usize, end: usize) -> Option<(usize, usize)> {
493    if start >= end || end > input.len() {
494        return None;
495    }
496    let slice = &input[start..end];
497    let mut first_non_punct: Option<usize> = None;
498    let mut last_non_punct_end: Option<usize> = None;
499
500    for (idx, ch) in slice.char_indices() {
501        if first_non_punct.is_none() && !is_leading_punct(ch) {
502            first_non_punct = Some(idx);
503        }
504        if first_non_punct.is_some() && !is_trailing_punct(ch) {
505            last_non_punct_end = Some(idx + ch.len_utf8());
506        }
507    }
508
509    let first = first_non_punct?;
510    let last_end = last_non_punct_end?;
511
512    if first >= last_end {
513        return None;
514    }
515
516    Some((start + first, start + last_end))
517}
518
519fn is_leading_punct(ch: char) -> bool {
520    matches!(ch, '(' | '[' | '{' | '<' | '"' | '\'' | '`')
521}
522
523fn is_trailing_punct(ch: char) -> bool {
524    matches!(ch, ')' | ']' | '}' | '>' | '"' | '\'' | '`' | ',' | '.' | ';' | ':' | '!' | '?')
525}
526
527fn looks_like_image_path(token: &str) -> bool {
528    let trimmed = token.trim();
529    if trimmed.is_empty() {
530        return false;
531    }
532    if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
533        return false;
534    }
535
536    let unescaped = unescape_whitespace(trimmed);
537    let mut candidate = unescaped.as_str();
538    if let Some(rest) = candidate.strip_prefix("file://") {
539        candidate = rest;
540    }
541    if let Some(rest) = candidate.strip_prefix("~/") {
542        candidate = rest;
543    }
544
545    if candidate.is_empty() {
546        return false;
547    }
548
549    crate::utils::image_processing::has_supported_image_extension(Path::new(candidate))
550}
551
552fn parse_data_image_url(raw: &str) -> Option<(String, String)> {
553    let trimmed = raw.trim_matches(|ch: char| matches!(ch, '"' | '\''));
554    let rest = trimmed.strip_prefix("data:")?;
555    let (mime_type, data) = rest.split_once(";base64,")?;
556    if !mime_type.starts_with("image/") {
557        return None;
558    }
559    // Providers accept only JPEG/PNG/GIF/WebP; anything else (notably SVG)
560    // fails the whole request with 400, so leave it as plain text.
561    if !crate::utils::image_processing::is_supported_image_mime_type(mime_type) {
562        return None;
563    }
564    let data = data.trim();
565    if data.is_empty() {
566        return None;
567    }
568    Some((mime_type.to_string(), data.to_string()))
569}
570
571fn looks_like_image_url(url: &str) -> bool {
572    let without_query = url.split(['?', '#']).next().map(str::trim).unwrap_or(url);
573    crate::utils::image_processing::has_supported_image_extension(Path::new(without_query))
574}
575
576fn resolve_image_path(token: &str, base_dir: &Path) -> Option<PathBuf> {
577    let unescaped = unescape_whitespace(token.trim());
578    if unescaped.is_empty() {
579        return None;
580    }
581
582    let mut candidate = unescaped.as_str();
583    if let Some(rest) = candidate.strip_prefix("file://") {
584        candidate = rest;
585    }
586
587    if let Some(rest) = candidate.strip_prefix("~/") {
588        if let Some(home) = dirs::home_dir() {
589            return Some(home.join(rest));
590        }
591        return None;
592    }
593
594    if Path::new(candidate).is_absolute() || is_windows_absolute_path(candidate) {
595        return Some(PathBuf::from(candidate));
596    }
597
598    if !is_safe_relative_path(candidate) {
599        return None;
600    }
601
602    Some(base_dir.join(candidate))
603}
604
605fn overlaps_range(start: usize, end: usize, ranges: &[(usize, usize)]) -> bool {
606    ranges
607        .iter()
608        .any(|(range_start, range_end)| start < *range_end && end > *range_start)
609}
610
611#[cfg(test)]
612mod tests;