Skip to main content

aidaemon_tools/fs/
read.rs

1//! `read_file`: numbered lines with typed metadata, plus attachments for
2//! images and extraction hints for documents.
3
4use std::collections::VecDeque;
5use std::sync::Arc;
6
7use async_trait::async_trait;
8use serde_json::{Value, json};
9
10use aidaemon_core::{AccessManifest, ToolAnnotations};
11
12use super::{FilePolicy, SharedBackend, ToolText, path_arg, workspace_parts};
13use crate::backend::{BackendMetadata, BackendPath};
14use crate::outcome::{OutcomeTool, core_tool};
15use crate::semantics::{
16    AttachmentProvenance, MessageAttachment, ReadFileResultMetadata, ReadFileSelectionMetadata,
17    ToolCallContext, ToolCallMetadata, ToolCallOutcome, ToolCallSemantics, ToolCapabilities,
18    ToolRole, ToolTargetHintKind, ToolVerificationMode,
19};
20use crate::workspace::Workspace;
21
22/// Per-call cap on returned content (bytes of line text). Reads that would
23/// exceed it return the first lines that fit plus a continuation hint
24/// instead of an unbounded payload.
25pub const MAX_READ_CHARS: usize = 100 * 1024;
26/// Individual lines longer than this (minified JS, JSONL, ...) are truncated
27/// with a marker; line-based paging can't help inside a single line.
28const MAX_LINE_CHARS: usize = 2_000;
29
30pub struct ReadFile {
31    backend: SharedBackend,
32    policy: Arc<dyn FilePolicy>,
33    text: ToolText,
34}
35
36impl ReadFile {
37    /// A tool confined to `workspace`.
38    pub fn new(workspace: Workspace) -> Self {
39        let (backend, policy) = workspace_parts(workspace);
40        Self::on_backend(backend, policy)
41    }
42
43    /// A tool working through `backend` under an application's `policy`.
44    pub fn on_backend(backend: SharedBackend, policy: Arc<dyn FilePolicy>) -> Self {
45        Self {
46            backend,
47            policy,
48            text: ToolText {
49                short: "Read a text file with line numbers and metadata".into(),
50                schema: "Read a file with line numbers and metadata. Read a file in full once when it fits the limit; oversized reads return the first page plus an exact continuation call to follow.".into(),
51            },
52        }
53    }
54
55    /// Replace the model-facing descriptions.
56    pub fn with_text(mut self, text: ToolText) -> Self {
57        self.text = text;
58        self
59    }
60}
61
62#[async_trait]
63impl OutcomeTool for ReadFile {
64    fn name(&self) -> &str {
65        "read_file"
66    }
67
68    fn description(&self) -> &str {
69        &self.text.short
70    }
71
72    fn schema(&self) -> Value {
73        json!({
74            "name": "read_file",
75            "description": self.text.schema,
76            "parameters": {
77                "type": "object",
78                "properties": {
79                    "path": {
80                        "type": "string",
81                        "description": "Path to the file (supports ~ expansion)"
82                    },
83                    "start_line": {
84                        "type": "integer",
85                        "description": "Start line number (1-based, inclusive). Omit to start from beginning."
86                    },
87                    "end_line": {
88                        "type": "integer",
89                        "description": "End line number (1-based, inclusive). Omit to read to end."
90                    },
91                    "tail_lines": {
92                        "type": "integer",
93                        "minimum": 1,
94                        "description": "Read the last N lines of the file. Useful for large logs."
95                    }
96                },
97                "required": ["path"],
98                "additionalProperties": false
99            }
100        })
101    }
102
103    async fn execute(
104        &self,
105        arguments: &str,
106        facts: &ToolCallContext,
107    ) -> anyhow::Result<ToolCallOutcome> {
108        self.read_outcome(arguments, crate::semantics::file_fence(facts))
109            .await
110    }
111}
112
113core_tool!(
114    ReadFile,
115    annotations: ToolAnnotations::READ_ONLY,
116    access: |this, arguments| AccessManifest {
117        reads: path_arg(arguments)
118            .map(|path| vec![this.policy.declare_path(path)])
119            .unwrap_or_default(),
120        ..Default::default()
121    }
122);
123
124impl crate::semantics::ToolSemantics for ReadFile {
125    fn dispatch_facts(&self) -> crate::semantics::ToolDispatchFacts {
126        crate::semantics::ToolDispatchFacts {
127            offering: crate::semantics::Offering::Core,
128            same_tool_streak: crate::semantics::SameToolStreak::Versatile,
129            file_guard: crate::semantics::FileGuard::Reads,
130            recap: crate::semantics::RecapKind::FileRead,
131            activity: crate::semantics::ToolActivity::Fixed(
132                aidaemon_core::card::ActivityKind::Read,
133            ),
134            opens_project_instructions: true,
135            status_label: Some("reading a file"),
136            result_fit: crate::semantics::ResultFit {
137                pages_spilled_results: true,
138                ..Default::default()
139            },
140            evidence: crate::semantics::EvidenceSource::FileRead,
141            semantic_scope: Some(crate::semantics::ToolSemanticScope::LocalWorkspace),
142            ..Default::default()
143        }
144    }
145
146    fn tool_role(&self) -> ToolRole {
147        ToolRole::Action
148    }
149
150    fn capabilities(&self) -> ToolCapabilities {
151        ToolCapabilities::READ_ONLY
152    }
153
154    fn output_trust(
155        &self,
156        arguments: &str,
157        roots: &crate::semantics::TrustRoots<'_>,
158    ) -> aidaemon_core::SourceTrust {
159        crate::semantics::file_output_trust(
160            arguments,
161            &["path", "file_path", "file", "filename"],
162            roots,
163        )
164    }
165
166    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
167        let path = serde_json::from_str::<Value>(arguments)
168            .ok()
169            .and_then(|args| {
170                for key in ["path", "file_path", "file", "filename"] {
171                    if let Some(path) = args.get(key).and_then(|value| value.as_str()) {
172                        return Some(path.to_string());
173                    }
174                }
175                None
176            })
177            .unwrap_or_default();
178
179        ToolCallSemantics::observation()
180            .with_verification_mode(ToolVerificationMode::ResultContent)
181            .with_target_hint(ToolTargetHintKind::Path, path)
182    }
183}
184
185impl ReadFile {
186    pub(crate) async fn read_outcome(
187        &self,
188        arguments: &str,
189        fence: Option<&Arc<dyn crate::semantics::FileFence>>,
190    ) -> anyhow::Result<ToolCallOutcome> {
191        let args: Value = serde_json::from_str(arguments)?;
192        let path_str = super::path_arg(&args)
193            .ok_or_else(|| anyhow::anyhow!("Missing required parameter: path"))?;
194
195        let has_start = args.get("start_line").is_some_and(|value| !value.is_null());
196        let has_end = args.get("end_line").is_some_and(|value| !value.is_null());
197        let tail_value = args
198            .get("tail_lines")
199            .or_else(|| args.get("last_lines"))
200            .or_else(|| args.get("last_n_lines"));
201        // An explicit start/end range wins over tail_lines when a call sends
202        // both: the schema no longer states the exclusion, and rejecting the
203        // pair looped a live run on the same call (2026-11-18).
204        let tail_value = tail_value.filter(|_| !(has_start || has_end));
205        let requested_start = args.get("start_line").and_then(Value::as_u64);
206        let requested_end = args.get("end_line").and_then(Value::as_u64);
207
208        let backend = self.backend.clone();
209        let path = backend.resolve_path(path_str).await?;
210        let metadata = backend
211            .metadata(&path)
212            .await
213            .map_err(|_| crate::TargetNotFound(format!("File not found: {path_str}")))?;
214
215        if metadata.is_dir() {
216            anyhow::bail!("Path is a directory, not a file: {}", path_str);
217        }
218
219        let file_size = metadata.len;
220        let modified = format_modified_rfc3339(&metadata);
221        let bytes = backend.read(&path).await?;
222        if let Some(fence) = fence {
223            fence.observed(path_str, &bytes).await;
224        }
225
226        if let Some(mime_type) =
227            sniff_file_image_mime(&bytes).filter(|_| self.policy.attaches_images())
228        {
229            return image_file_outcome(
230                backend,
231                path_str,
232                &path,
233                file_size,
234                modified.as_deref(),
235                mime_type,
236            )
237            .await;
238        }
239
240        // Documents (PDF, Word) can't be decoded here, but dead-ending with
241        // "binary" makes models give up or ask the user to convert the file.
242        // Return an exact terminal extraction command instead. Checked before
243        // the NUL-byte binary test: small text-only PDFs contain no NUL bytes
244        // and would otherwise be dumped as raw PDF syntax.
245        if let Some(kind) = sniff_document_kind(&path, &bytes) {
246            return Ok(ToolCallOutcome::from_output(document_extraction_stub(
247                kind,
248                path_str,
249                file_size,
250                modified.as_deref(),
251                self.policy.shell_tool_name(),
252                // The commands run where the file is: macOS tools only on a
253                // local backend of a macOS daemon.
254                cfg!(target_os = "macos")
255                    && matches!(self.backend.kind(), crate::backend::BackendKind::Local),
256            )));
257        }
258
259        // Check for binary
260        if bytes.iter().take(8192).any(|byte| *byte == 0) {
261            let mut out = format!("Binary file: {}\nSize: {} bytes\n", path_str, file_size);
262            if let Some(modified) = &modified {
263                out.push_str(&format!("Modified: {}\n", modified));
264            }
265            out.push_str("Type: binary (cannot display contents).\n");
266            out.push_str(&format!(
267                "If you need its contents, run the {} tool with: file \"{}\" to identify the format, then choose a matching extraction command.",
268                self.policy.shell_tool_name(),
269                shell_safe_path(path_str)
270            ));
271            return Ok(ToolCallOutcome::from_output(out));
272        }
273
274        // Line ranges apply to text only: an image, document or binary file
275        // above ignores them, so a range sent with one is never an error
276        // (live 2026-11-18: a PNG read with a range was rejected nine times).
277        if requested_start.is_some_and(|line| line == 0)
278            || requested_end.is_some_and(|line| line == 0)
279        {
280            return Ok(ToolCallOutcome::contract_rejection(
281                "read_file line numbers are 1-based and must be positive",
282            ));
283        }
284        if matches!((requested_start, requested_end), (Some(start), Some(end)) if end < start) {
285            return Ok(ToolCallOutcome::contract_rejection(
286                "read_file end_line must be greater than or equal to start_line",
287            ));
288        }
289        let start = args["start_line"]
290            .as_u64()
291            .map(|n| (n as usize).saturating_sub(1))
292            .unwrap_or(0);
293
294        let end = args["end_line"]
295            .as_u64()
296            .map(|n| n as usize)
297            .unwrap_or(usize::MAX);
298
299        let tail_lines = tail_value
300            .and_then(Value::as_u64)
301            // Be tolerant of older/smaller models that emit zero to mean
302            // "no tail selection". The schema prevents new strict calls from
303            // doing so, while this fallback avoids a useless retry loop.
304            .filter(|n| *n > 0)
305            .map(|n| n as usize);
306
307        let uses_subset = start > 0 || end != usize::MAX || tail_lines.is_some();
308        // Oversized full reads no longer error: the per-call cap below
309        // returns the first page with an explicit continuation hint, which
310        // small-context models follow far more reliably than an error.
311
312        let selection = if let Some(count) = tail_lines {
313            ReadSelection::Tail { count }
314        } else if uses_subset {
315            ReadSelection::Range {
316                start,
317                end_exclusive: (end != usize::MAX).then_some(end),
318            }
319        } else {
320            ReadSelection::Full
321        };
322
323        let text = String::from_utf8(bytes)
324            .map_err(|_| anyhow::anyhow!("Cannot display non-UTF-8 file: {}", path_str))?;
325        let selected = read_selected_lines(&text, selection);
326        let total_lines = selected.total_lines;
327        let selection_metadata = match selection {
328            ReadSelection::Full => ReadFileSelectionMetadata::Full,
329            ReadSelection::Range {
330                start,
331                end_exclusive: Some(end),
332            } => ReadFileSelectionMetadata::BoundedRange {
333                start_line: start + 1,
334                end_line: end,
335            },
336            ReadSelection::Range {
337                start,
338                end_exclusive: None,
339            } => ReadFileSelectionMetadata::OpenEndedRange {
340                start_line: start + 1,
341            },
342            ReadSelection::Tail { count } => ReadFileSelectionMetadata::Tail {
343                requested_lines: count,
344            },
345        };
346        let canonical_path = backend
347            .canonicalize(&path)
348            .await
349            .unwrap_or_else(|_| path.clone())
350            .to_string();
351        let read_metadata = ReadFileResultMetadata {
352            display_path: path_str.to_string(),
353            canonical_path,
354            selection: selection_metadata,
355            returned_start_line: (!selected.lines.is_empty()).then_some(selected.start_index + 1),
356            returned_end_line: (!selected.lines.is_empty()).then_some(selected.end_display),
357            total_lines,
358            file_size,
359            modified: modified.clone(),
360            selected_lines: selected.lines.clone(),
361            truncated: selected.truncated,
362        };
363
364        if total_lines == 0 {
365            let header =
366                format_text_file_header(path_str, "0 lines, empty", file_size, modified.as_deref());
367            return Ok(ToolCallOutcome {
368                output: header.trim_end().to_string(),
369                metadata: ToolCallMetadata {
370                    read_file: Some(read_metadata),
371                    ..ToolCallMetadata::default()
372                },
373                finish: None,
374            });
375        }
376
377        if selected.start_index >= total_lines {
378            anyhow::bail!(
379                "start_line {} exceeds total lines {} in file",
380                selected.start_index + 1,
381                total_lines
382            );
383        }
384
385        Ok(ToolCallOutcome {
386            output: render_read_file_output(&read_metadata),
387            metadata: ToolCallMetadata {
388                read_file: Some(read_metadata),
389                ..ToolCallMetadata::default()
390            },
391            finish: None,
392        })
393    }
394}
395
396pub fn render_read_file_output(metadata: &ReadFileResultMetadata) -> String {
397    if metadata.total_lines == 0 {
398        return format_text_file_header(
399            &metadata.display_path,
400            "0 lines, empty",
401            metadata.file_size,
402            metadata.modified.as_deref(),
403        )
404        .trim_end()
405        .to_string();
406    }
407
408    let start_line = metadata.returned_start_line.unwrap_or(1);
409    let end_line = metadata.returned_end_line.unwrap_or(start_line);
410    let header_summary = match metadata.selection {
411        ReadFileSelectionMetadata::Full if !metadata.truncated => {
412            format!("{} lines", metadata.total_lines)
413        }
414        ReadFileSelectionMetadata::Full
415        | ReadFileSelectionMetadata::BoundedRange { .. }
416        | ReadFileSelectionMetadata::OpenEndedRange { .. } => {
417            format!(
418                "lines {}-{} of {}",
419                start_line, end_line, metadata.total_lines
420            )
421        }
422        ReadFileSelectionMetadata::Tail { .. } => format!(
423            "last {} lines of {}",
424            metadata.selected_lines.len(),
425            metadata.total_lines
426        ),
427    };
428    let header = format_text_file_header(
429        &metadata.display_path,
430        &header_summary,
431        metadata.file_size,
432        metadata.modified.as_deref(),
433    );
434    let selected_content = metadata.selected_lines.join("\n");
435    let formatted = super::format_with_line_numbers(&selected_content, start_line - 1);
436    match continuation_hint(metadata) {
437        Some(hint) => format!("{}{}\n{}", header, formatted, hint),
438        None => format!("{}{}", header, formatted),
439    }
440}
441
442/// Render a read result within a character budget, cutting on line
443/// boundaries and appending an explicit continuation hint when lines had to
444/// be dropped. Results that fit are rendered unchanged, so big-budget models
445/// see exactly what they do today.
446///
447/// For tail selections the most recent lines are kept (the end of a log is
448/// the signal); for everything else the first lines are kept so sequential
449/// paging works.
450pub fn render_read_file_output_within(
451    metadata: &ReadFileResultMetadata,
452    max_chars: usize,
453) -> String {
454    let full = render_read_file_output(metadata);
455    if full.chars().count() <= max_chars {
456        return full;
457    }
458
459    // Reserve room for the header and continuation hint, then keep whole
460    // numbered lines until the budget is spent.
461    const HINT_RESERVE: usize = 360;
462    let start_line = metadata.returned_start_line.unwrap_or(1);
463    let end_line = metadata.returned_end_line.unwrap_or(start_line);
464    let keep_from_end = matches!(metadata.selection, ReadFileSelectionMetadata::Tail { .. });
465    let number_width = end_line.to_string().len().max(3) + 3; // "NNN | "
466    let budget = max_chars.saturating_sub(HINT_RESERVE + 120);
467
468    let mut kept: Vec<String> = Vec::new();
469    let mut used = 0usize;
470    let lines: Box<dyn Iterator<Item = &String>> = if keep_from_end {
471        Box::new(metadata.selected_lines.iter().rev())
472    } else {
473        Box::new(metadata.selected_lines.iter())
474    };
475    for line in lines {
476        let cost = number_width + line.chars().count() + 1;
477        if !kept.is_empty() && used + cost > budget {
478            break;
479        }
480        used += cost;
481        kept.push(line.clone());
482    }
483    if keep_from_end {
484        kept.reverse();
485    }
486
487    let mut adjusted = metadata.clone();
488    adjusted.truncated = true;
489    if keep_from_end {
490        adjusted.returned_start_line = Some(end_line.saturating_sub(kept.len()).saturating_add(1));
491    } else {
492        adjusted.returned_end_line = Some(start_line + kept.len() - 1);
493    }
494    adjusted.selected_lines = kept;
495    render_read_file_output(&adjusted)
496}
497
498/// Build an explicit, copyable next-call instruction for truncated reads.
499/// Small-context models follow a literal tool-call template far more
500/// reliably than a generic "output was truncated" notice.
501pub(crate) fn continuation_hint(metadata: &ReadFileResultMetadata) -> Option<String> {
502    if !metadata.truncated {
503        return None;
504    }
505    let start_line = metadata.returned_start_line?;
506    let end_line = metadata.returned_end_line?;
507    if matches!(metadata.selection, ReadFileSelectionMetadata::Tail { .. }) {
508        return Some(format!(
509            "[NOTE: tail output truncated to fit the output limit — only the last {} lines were returned; lines before {} are NOT visible to you. Use start_line/end_line to read earlier sections.]",
510            metadata.selected_lines.len(),
511            start_line
512        ));
513    }
514    let shown = end_line
515        .saturating_sub(start_line)
516        .saturating_add(1)
517        .max(50);
518    let next_start = end_line + 1;
519    let next_end = end_line.saturating_add(shown).min(metadata.total_lines);
520    Some(format!(
521        "[NOTE: output truncated at line {} — lines {}-{} of {} were NOT returned and are NOT visible to you. Do not guess their content. To continue reading, call read_file with {{\"path\": \"{}\", \"start_line\": {}, \"end_line\": {}}}.]",
522        end_line,
523        next_start,
524        metadata.total_lines,
525        metadata.total_lines,
526        metadata.display_path,
527        next_start,
528        next_end
529    ))
530}
531
532#[derive(Clone, Copy)]
533enum ReadSelection {
534    Full,
535    Range {
536        start: usize,
537        end_exclusive: Option<usize>,
538    },
539    Tail {
540        count: usize,
541    },
542}
543
544struct SelectedLines {
545    lines: Vec<String>,
546    total_lines: usize,
547    start_index: usize,
548    end_display: usize,
549    /// True when the per-call output cap dropped lines the request asked for.
550    truncated: bool,
551}
552
553/// Truncate a single overlong line, keeping a marker so the model knows
554/// content is missing rather than absent.
555fn cap_line(line: String) -> String {
556    if line.len() <= MAX_LINE_CHARS {
557        return line;
558    }
559    let total_chars = line.chars().count();
560    if total_chars <= MAX_LINE_CHARS {
561        return line;
562    }
563    let mut kept: String = line.chars().take(MAX_LINE_CHARS).collect();
564    kept.push_str(&format!("… [line truncated; {} chars total]", total_chars));
565    kept
566}
567
568fn read_selected_lines(content: &str, selection: ReadSelection) -> SelectedLines {
569    match selection {
570        ReadSelection::Full | ReadSelection::Range { .. } => {
571            let (start, end_exclusive) = match selection {
572                ReadSelection::Range {
573                    start,
574                    end_exclusive,
575                } => (start, end_exclusive),
576                _ => (0, None),
577            };
578
579            let mut lines = Vec::new();
580            let mut total_lines: usize = 0;
581            let mut stored_bytes: usize = 0;
582            let mut capped = false;
583
584            for line in content.lines() {
585                total_lines += 1;
586                let zero_based_index = total_lines - 1;
587                let in_range = zero_based_index >= start
588                    && end_exclusive.is_none_or(|end| zero_based_index < end);
589                if in_range && !capped {
590                    let line = cap_line(line.to_string());
591                    if !lines.is_empty() && stored_bytes + line.len() > MAX_READ_CHARS {
592                        capped = true;
593                    } else {
594                        stored_bytes += line.len() + 1;
595                        lines.push(line);
596                    }
597                }
598                // Keep counting to EOF so total_lines (and the continuation
599                // hint) stay accurate even after the cap is hit.
600            }
601
602            let (end_display, truncated) = if capped {
603                (start + lines.len(), true)
604            } else {
605                (end_exclusive.unwrap_or(total_lines).min(total_lines), false)
606            };
607            SelectedLines {
608                lines,
609                total_lines,
610                start_index: start,
611                end_display,
612                truncated,
613            }
614        }
615        ReadSelection::Tail { count } => {
616            let mut lines: VecDeque<String> = VecDeque::new();
617            let mut total_lines: usize = 0;
618            let mut stored_bytes: usize = 0;
619
620            for line in content.lines() {
621                total_lines += 1;
622                if lines.len() == count
623                    && let Some(dropped) = lines.pop_front()
624                {
625                    stored_bytes = stored_bytes.saturating_sub(dropped.len() + 1);
626                }
627                let line = cap_line(line.to_string());
628                stored_bytes += line.len() + 1;
629                lines.push_back(line);
630                // Bound memory and output: keep only the most recent lines
631                // that fit the per-call cap.
632                while stored_bytes > MAX_READ_CHARS && lines.len() > 1 {
633                    if let Some(dropped) = lines.pop_front() {
634                        stored_bytes = stored_bytes.saturating_sub(dropped.len() + 1);
635                    }
636                }
637            }
638
639            let lines: Vec<String> = lines.into_iter().collect();
640            let start_index = total_lines.saturating_sub(lines.len());
641            let truncated = lines.len() < count.min(total_lines);
642            SelectedLines {
643                lines,
644                total_lines,
645                start_index,
646                end_display: total_lines,
647                truncated,
648            }
649        }
650    }
651}
652
653/// Document formats `read_file` cannot decode itself but whose text the
654/// model can extract with one terminal command.
655#[derive(Clone, Copy, Debug, PartialEq, Eq)]
656enum DocumentKind {
657    Pdf,
658    Word,
659}
660
661/// Detect PDF (magic bytes) and Word documents (zip/OLE magic + extension).
662fn sniff_document_kind(path: &BackendPath, bytes: &[u8]) -> Option<DocumentKind> {
663    let header = &bytes[..bytes.len().min(8)];
664    if header.starts_with(b"%PDF") {
665        return Some(DocumentKind::Pdf);
666    }
667
668    let extension = path.extension().map(|ext| ext.to_ascii_lowercase());
669    let is_zip = header.starts_with(b"PK\x03\x04");
670    let is_ole = header.starts_with(&[0xD0, 0xCF, 0x11, 0xE0]);
671    match extension.as_deref() {
672        Some("docx") if is_zip => Some(DocumentKind::Word),
673        Some("doc") if is_ole => Some(DocumentKind::Word),
674        _ => None,
675    }
676}
677
678/// Escape double quotes so the suggested command stays a single shell token
679/// even for paths with spaces or quotes.
680fn shell_safe_path(path: &str) -> String {
681    path.replace('"', "\\\"")
682}
683
684fn document_extraction_stub(
685    kind: DocumentKind,
686    display_path: &str,
687    file_size: u64,
688    modified: Option<&str>,
689    shell: &str,
690    macos: bool,
691) -> String {
692    let label = match kind {
693        DocumentKind::Pdf => "PDF document",
694        DocumentKind::Word => "Word document",
695    };
696    let mut out = format!("{}: {}\nSize: {} bytes\n", label, display_path, file_size);
697    if let Some(modified) = modified {
698        out.push_str(&format!("Modified: {}\n", modified));
699    }
700    let quoted = shell_safe_path(display_path);
701    match kind {
702        DocumentKind::Pdf => {
703            out.push_str(&format!(
704                "This tool cannot extract PDF text directly. Run the {shell} tool to extract it:\n"
705            ));
706            out.push_str(&format!("  pdftotext -layout \"{}\" -\n", quoted));
707            if macos {
708                out.push_str(&format!(
709                    "If pdftotext is not installed, use Spotlight's extracted text:\n  mdls -raw -name kMDItemTextContent \"{}\"\n",
710                    quoted
711                ));
712            } else {
713                out.push_str(
714                    "If pdftotext is not installed, install poppler-utils (e.g. apt install poppler-utils) or use pandoc.\n",
715                );
716            }
717        }
718        DocumentKind::Word => {
719            out.push_str(&format!(
720                "This tool cannot extract Word document text directly. Run the {shell} tool to extract it:\n"
721            ));
722            if macos {
723                out.push_str(&format!("  textutil -convert txt -stdout \"{}\"\n", quoted));
724            } else {
725                out.push_str(&format!("  pandoc -t plain \"{}\"\n", quoted));
726            }
727        }
728    }
729    out.push_str("Do not ask the user to convert the file — extract it yourself.");
730    out
731}
732
733fn sniff_file_image_mime(bytes: &[u8]) -> Option<&'static str> {
734    crate::util::sniff_image_mime(&bytes[..bytes.len().min(16)])
735}
736
737async fn image_file_outcome(
738    backend: SharedBackend,
739    display_path: &str,
740    path: &BackendPath,
741    file_size: u64,
742    modified: Option<&str>,
743    mime_type: &str,
744) -> anyhow::Result<ToolCallOutcome> {
745    let mut output = format!("Image file: {}\nSize: {} bytes\n", display_path, file_size);
746    if let Some(modified) = modified {
747        output.push_str(&format!("Modified: {}\n", modified));
748    }
749    output.push_str(&format!("Type: {mime_type}\n"));
750    output.push_str("Attached for vision analysis.");
751
752    let filename = path.file_name().unwrap_or("image").to_string();
753    let staging_dir = std::env::temp_dir().join("aidaemon-execution-observations");
754    tokio::fs::create_dir_all(&staging_dir).await?;
755    let local_path = staging_dir.join(format!("{}-{}", uuid::Uuid::new_v4(), filename));
756    backend.export_local_file(path, &local_path).await?;
757
758    Ok(ToolCallOutcome {
759        output,
760        metadata: ToolCallMetadata {
761            attachments: vec![MessageAttachment {
762                local_path: local_path.to_string_lossy().into_owned(),
763                filename,
764                mime_type: mime_type.to_string(),
765                size_bytes: file_size,
766                provenance: AttachmentProvenance::ToolObservation,
767                source_tool: Some("read_file".to_string()),
768                ..MessageAttachment::default()
769            }],
770            ..ToolCallMetadata::default()
771        },
772        finish: None,
773    })
774}
775
776fn format_modified_rfc3339(metadata: &BackendMetadata) -> Option<String> {
777    let modified = metadata.modified?;
778    let modified_utc: chrono::DateTime<chrono::Utc> = modified.into();
779    Some(modified_utc.to_rfc3339())
780}
781
782fn format_text_file_header(
783    path: &str,
784    line_summary: &str,
785    file_size: u64,
786    modified: Option<&str>,
787) -> String {
788    match modified {
789        Some(modified) => format!(
790            "File: {} ({}, {} bytes, modified {})\n",
791            path, line_summary, file_size, modified
792        ),
793        None => format!("File: {} ({}, {} bytes)\n", path, line_summary, file_size),
794    }
795}
796
797#[cfg(test)]
798mod document_stub_tests {
799    use super::*;
800
801    /// macOS-only extraction commands are suggested only where the file is
802    /// on a macOS machine; a remote or non-macOS backend gets portable ones.
803    #[test]
804    fn extraction_commands_follow_where_the_file_is() {
805        let remote = document_extraction_stub(
806            DocumentKind::Pdf,
807            "/workspace/report.pdf",
808            10,
809            None,
810            "terminal",
811            false,
812        );
813        assert!(
814            remote.contains("pdftotext") && !remote.contains("mdls"),
815            "{remote}"
816        );
817        let word = document_extraction_stub(
818            DocumentKind::Word,
819            "/workspace/notes.docx",
820            10,
821            None,
822            "terminal",
823            false,
824        );
825        assert!(
826            word.contains("pandoc") && !word.contains("textutil"),
827            "{word}"
828        );
829        let mac = document_extraction_stub(
830            DocumentKind::Pdf,
831            "/Users/synthetic/report.pdf",
832            10,
833            None,
834            "terminal",
835            true,
836        );
837        assert!(mac.contains("mdls"), "{mac}");
838    }
839}