aidaemon-tools 0.21.0

Ready-made tools for aidaemon agents (files, search, sandboxed shell, web, checklist); implementation crate of the aidaemon SDK, no stability promise (use it through aidaemon-sdk)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
//! `read_file`: numbered lines with typed metadata, plus attachments for
//! images and extraction hints for documents.

use std::collections::VecDeque;
use std::sync::Arc;

use async_trait::async_trait;
use serde_json::{Value, json};

use aidaemon_core::{AccessManifest, ToolAnnotations};

use super::{FilePolicy, SharedBackend, ToolText, path_arg, workspace_parts};
use crate::backend::{BackendMetadata, BackendPath};
use crate::outcome::{OutcomeTool, core_tool};
use crate::semantics::{
    AttachmentProvenance, MessageAttachment, ReadFileResultMetadata, ReadFileSelectionMetadata,
    ToolCallContext, ToolCallMetadata, ToolCallOutcome, ToolCallSemantics, ToolCapabilities,
    ToolRole, ToolTargetHintKind, ToolVerificationMode,
};
use crate::workspace::Workspace;

/// Per-call cap on returned content (bytes of line text). Reads that would
/// exceed it return the first lines that fit plus a continuation hint
/// instead of an unbounded payload.
pub const MAX_READ_CHARS: usize = 100 * 1024;
/// Individual lines longer than this (minified JS, JSONL, ...) are truncated
/// with a marker; line-based paging can't help inside a single line.
const MAX_LINE_CHARS: usize = 2_000;

pub struct ReadFile {
    backend: SharedBackend,
    policy: Arc<dyn FilePolicy>,
    text: ToolText,
}

impl ReadFile {
    /// A tool confined to `workspace`.
    pub fn new(workspace: Workspace) -> Self {
        let (backend, policy) = workspace_parts(workspace);
        Self::on_backend(backend, policy)
    }

    /// A tool working through `backend` under an application's `policy`.
    pub fn on_backend(backend: SharedBackend, policy: Arc<dyn FilePolicy>) -> Self {
        Self {
            backend,
            policy,
            text: ToolText {
                short: "Read a text file with line numbers and metadata".into(),
                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(),
            },
        }
    }

    /// Replace the model-facing descriptions.
    pub fn with_text(mut self, text: ToolText) -> Self {
        self.text = text;
        self
    }
}

#[async_trait]
impl OutcomeTool for ReadFile {
    fn name(&self) -> &str {
        "read_file"
    }

    fn description(&self) -> &str {
        &self.text.short
    }

    fn schema(&self) -> Value {
        json!({
            "name": "read_file",
            "description": self.text.schema,
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Path to the file (supports ~ expansion)"
                    },
                    "start_line": {
                        "type": "integer",
                        "description": "Start line number (1-based, inclusive). Omit to start from beginning."
                    },
                    "end_line": {
                        "type": "integer",
                        "description": "End line number (1-based, inclusive). Omit to read to end."
                    },
                    "tail_lines": {
                        "type": "integer",
                        "minimum": 1,
                        "description": "Read the last N lines of the file. Useful for large logs."
                    }
                },
                "required": ["path"],
                "allOf": [
                    {"not": {"required": ["tail_lines", "start_line"]}},
                    {"not": {"required": ["tail_lines", "end_line"]}}
                ],
                "additionalProperties": false
            }
        })
    }

    async fn execute(
        &self,
        arguments: &str,
        facts: &ToolCallContext,
    ) -> anyhow::Result<ToolCallOutcome> {
        self.read_outcome(arguments, crate::semantics::file_fence(facts))
            .await
    }
}

core_tool!(
    ReadFile,
    annotations: ToolAnnotations::READ_ONLY,
    access: |this, arguments| AccessManifest {
        reads: path_arg(arguments)
            .map(|path| vec![this.policy.declare_path(path)])
            .unwrap_or_default(),
        ..Default::default()
    }
);

impl crate::semantics::ToolSemantics for ReadFile {
    fn dispatch_facts(&self) -> crate::semantics::ToolDispatchFacts {
        crate::semantics::ToolDispatchFacts {
            offering: crate::semantics::Offering::Core,
            same_tool_streak: crate::semantics::SameToolStreak::Versatile,
            file_guard: crate::semantics::FileGuard::Reads,
            recap: crate::semantics::RecapKind::FileRead,
            activity: crate::semantics::ToolActivity::Fixed(
                aidaemon_core::card::ActivityKind::Read,
            ),
            opens_project_instructions: true,
            status_label: Some("reading a file"),
            result_fit: crate::semantics::ResultFit {
                pages_spilled_results: true,
                ..Default::default()
            },
            evidence: crate::semantics::EvidenceSource::FileRead,
            semantic_scope: Some(crate::semantics::ToolSemanticScope::LocalWorkspace),
            ..Default::default()
        }
    }

    fn tool_role(&self) -> ToolRole {
        ToolRole::Action
    }

    fn capabilities(&self) -> ToolCapabilities {
        ToolCapabilities {
            read_only: true,
            external_side_effect: false,
            needs_approval: false,
            idempotent: true,
            high_impact_write: false,
        }
    }

    fn output_trust(
        &self,
        arguments: &str,
        roots: &crate::semantics::TrustRoots<'_>,
    ) -> aidaemon_core::SourceTrust {
        crate::semantics::file_output_trust(
            arguments,
            &["path", "file_path", "file", "filename"],
            roots,
        )
    }

    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
        let path = serde_json::from_str::<Value>(arguments)
            .ok()
            .and_then(|args| {
                for key in ["path", "file_path", "file", "filename"] {
                    if let Some(path) = args.get(key).and_then(|value| value.as_str()) {
                        return Some(path.to_string());
                    }
                }
                None
            })
            .unwrap_or_default();

        ToolCallSemantics::observation()
            .with_verification_mode(ToolVerificationMode::ResultContent)
            .with_target_hint(ToolTargetHintKind::Path, path)
    }
}

impl ReadFile {
    pub(crate) async fn read_outcome(
        &self,
        arguments: &str,
        fence: Option<&Arc<dyn crate::semantics::FileFence>>,
    ) -> anyhow::Result<ToolCallOutcome> {
        let args: Value = serde_json::from_str(arguments)?;
        // Parameter aliasing: models often use "file_path" or "file" instead of "path"
        let path_str = args["path"]
            .as_str()
            .or_else(|| args["file_path"].as_str())
            .or_else(|| args["file"].as_str())
            .or_else(|| args["filename"].as_str())
            .ok_or_else(|| anyhow::anyhow!("Missing required parameter: path"))?;

        let has_start = args.get("start_line").is_some_and(|value| !value.is_null());
        let has_end = args.get("end_line").is_some_and(|value| !value.is_null());
        let tail_value = args
            .get("tail_lines")
            .or_else(|| args.get("last_lines"))
            .or_else(|| args.get("last_n_lines"));
        // An explicit start/end range wins over tail_lines when a call sends
        // both: the schema no longer states the exclusion, and rejecting the
        // pair looped a live run on the same call (2026-11-18).
        let tail_value = tail_value.filter(|_| !(has_start || has_end));
        let requested_start = args.get("start_line").and_then(Value::as_u64);
        let requested_end = args.get("end_line").and_then(Value::as_u64);
        if requested_start.is_some_and(|line| line == 0)
            || requested_end.is_some_and(|line| line == 0)
        {
            return Ok(ToolCallOutcome::contract_rejection(
                "read_file line numbers are 1-based and must be positive",
            ));
        }
        if matches!((requested_start, requested_end), (Some(start), Some(end)) if end < start) {
            return Ok(ToolCallOutcome::contract_rejection(
                "read_file end_line must be greater than or equal to start_line",
            ));
        }

        let backend = self.backend.clone();
        let path = backend.resolve_path(path_str).await?;
        let metadata = backend
            .metadata(&path)
            .await
            .map_err(|_| crate::TargetNotFound(format!("File not found: {path_str}")))?;

        if metadata.is_dir() {
            anyhow::bail!("Path is a directory, not a file: {}", path_str);
        }

        let file_size = metadata.len;
        let modified = format_modified_rfc3339(&metadata);
        let bytes = backend.read(&path).await?;
        if let Some(fence) = fence {
            fence.observed(path_str, &bytes).await;
        }

        if let Some(mime_type) =
            sniff_file_image_mime(&bytes).filter(|_| self.policy.attaches_images())
        {
            return image_file_outcome(
                backend,
                path_str,
                &path,
                file_size,
                modified.as_deref(),
                mime_type,
            )
            .await;
        }

        // Documents (PDF, Word) can't be decoded here, but dead-ending with
        // "binary" makes models give up or ask the user to convert the file.
        // Return an exact terminal extraction command instead. Checked before
        // the NUL-byte binary test: small text-only PDFs contain no NUL bytes
        // and would otherwise be dumped as raw PDF syntax.
        if let Some(kind) = sniff_document_kind(&path, &bytes) {
            return Ok(ToolCallOutcome::from_output(document_extraction_stub(
                kind,
                path_str,
                file_size,
                modified.as_deref(),
                self.policy.shell_tool_name(),
                // The commands run where the file is: macOS tools only on a
                // local backend of a macOS daemon.
                cfg!(target_os = "macos")
                    && matches!(self.backend.kind(), crate::backend::BackendKind::Local),
            )));
        }

        // Check for binary
        if bytes.iter().take(8192).any(|byte| *byte == 0) {
            let mut out = format!("Binary file: {}\nSize: {} bytes\n", path_str, file_size);
            if let Some(modified) = &modified {
                out.push_str(&format!("Modified: {}\n", modified));
            }
            out.push_str("Type: binary (cannot display contents).\n");
            out.push_str(&format!(
                "If you need its contents, run the {} tool with: file \"{}\" to identify the format, then choose a matching extraction command.",
                self.policy.shell_tool_name(),
                shell_safe_path(path_str)
            ));
            return Ok(ToolCallOutcome::from_output(out));
        }

        let start = args["start_line"]
            .as_u64()
            .map(|n| (n as usize).saturating_sub(1))
            .unwrap_or(0);

        let end = args["end_line"]
            .as_u64()
            .map(|n| n as usize)
            .unwrap_or(usize::MAX);

        let tail_lines = tail_value
            .and_then(Value::as_u64)
            // Be tolerant of older/smaller models that emit zero to mean
            // "no tail selection". The schema prevents new strict calls from
            // doing so, while this fallback avoids a useless retry loop.
            .filter(|n| *n > 0)
            .map(|n| n as usize);

        let uses_subset = start > 0 || end != usize::MAX || tail_lines.is_some();
        // Oversized full reads no longer error: the per-call cap below
        // returns the first page with an explicit continuation hint, which
        // small-context models follow far more reliably than an error.

        let selection = if let Some(count) = tail_lines {
            ReadSelection::Tail { count }
        } else if uses_subset {
            ReadSelection::Range {
                start,
                end_exclusive: (end != usize::MAX).then_some(end),
            }
        } else {
            ReadSelection::Full
        };

        let text = String::from_utf8(bytes)
            .map_err(|_| anyhow::anyhow!("Cannot display non-UTF-8 file: {}", path_str))?;
        let selected = read_selected_lines(&text, selection);
        let total_lines = selected.total_lines;
        let selection_metadata = match selection {
            ReadSelection::Full => ReadFileSelectionMetadata::Full,
            ReadSelection::Range {
                start,
                end_exclusive: Some(end),
            } => ReadFileSelectionMetadata::BoundedRange {
                start_line: start + 1,
                end_line: end,
            },
            ReadSelection::Range {
                start,
                end_exclusive: None,
            } => ReadFileSelectionMetadata::OpenEndedRange {
                start_line: start + 1,
            },
            ReadSelection::Tail { count } => ReadFileSelectionMetadata::Tail {
                requested_lines: count,
            },
        };
        let canonical_path = backend
            .canonicalize(&path)
            .await
            .unwrap_or_else(|_| path.clone())
            .to_string();
        let read_metadata = ReadFileResultMetadata {
            display_path: path_str.to_string(),
            canonical_path,
            selection: selection_metadata,
            returned_start_line: (!selected.lines.is_empty()).then_some(selected.start_index + 1),
            returned_end_line: (!selected.lines.is_empty()).then_some(selected.end_display),
            total_lines,
            file_size,
            modified: modified.clone(),
            selected_lines: selected.lines.clone(),
            truncated: selected.truncated,
        };

        if total_lines == 0 {
            let header =
                format_text_file_header(path_str, "0 lines, empty", file_size, modified.as_deref());
            return Ok(ToolCallOutcome {
                output: header.trim_end().to_string(),
                metadata: ToolCallMetadata {
                    read_file: Some(read_metadata),
                    ..ToolCallMetadata::default()
                },
                finish: None,
            });
        }

        if selected.start_index >= total_lines {
            anyhow::bail!(
                "start_line {} exceeds total lines {} in file",
                selected.start_index + 1,
                total_lines
            );
        }

        Ok(ToolCallOutcome {
            output: render_read_file_output(&read_metadata),
            metadata: ToolCallMetadata {
                read_file: Some(read_metadata),
                ..ToolCallMetadata::default()
            },
            finish: None,
        })
    }
}

pub fn render_read_file_output(metadata: &ReadFileResultMetadata) -> String {
    if metadata.total_lines == 0 {
        return format_text_file_header(
            &metadata.display_path,
            "0 lines, empty",
            metadata.file_size,
            metadata.modified.as_deref(),
        )
        .trim_end()
        .to_string();
    }

    let start_line = metadata.returned_start_line.unwrap_or(1);
    let end_line = metadata.returned_end_line.unwrap_or(start_line);
    let header_summary = match metadata.selection {
        ReadFileSelectionMetadata::Full if !metadata.truncated => {
            format!("{} lines", metadata.total_lines)
        }
        ReadFileSelectionMetadata::Full
        | ReadFileSelectionMetadata::BoundedRange { .. }
        | ReadFileSelectionMetadata::OpenEndedRange { .. } => {
            format!(
                "lines {}-{} of {}",
                start_line, end_line, metadata.total_lines
            )
        }
        ReadFileSelectionMetadata::Tail { .. } => format!(
            "last {} lines of {}",
            metadata.selected_lines.len(),
            metadata.total_lines
        ),
    };
    let header = format_text_file_header(
        &metadata.display_path,
        &header_summary,
        metadata.file_size,
        metadata.modified.as_deref(),
    );
    let selected_content = metadata.selected_lines.join("\n");
    let formatted = super::format_with_line_numbers(&selected_content, start_line - 1);
    match continuation_hint(metadata) {
        Some(hint) => format!("{}{}\n{}", header, formatted, hint),
        None => format!("{}{}", header, formatted),
    }
}

/// Render a read result within a character budget, cutting on line
/// boundaries and appending an explicit continuation hint when lines had to
/// be dropped. Results that fit are rendered unchanged, so big-budget models
/// see exactly what they do today.
///
/// For tail selections the most recent lines are kept (the end of a log is
/// the signal); for everything else the first lines are kept so sequential
/// paging works.
pub fn render_read_file_output_within(
    metadata: &ReadFileResultMetadata,
    max_chars: usize,
) -> String {
    let full = render_read_file_output(metadata);
    if full.chars().count() <= max_chars {
        return full;
    }

    // Reserve room for the header and continuation hint, then keep whole
    // numbered lines until the budget is spent.
    const HINT_RESERVE: usize = 360;
    let start_line = metadata.returned_start_line.unwrap_or(1);
    let end_line = metadata.returned_end_line.unwrap_or(start_line);
    let keep_from_end = matches!(metadata.selection, ReadFileSelectionMetadata::Tail { .. });
    let number_width = end_line.to_string().len().max(3) + 3; // "NNN | "
    let budget = max_chars.saturating_sub(HINT_RESERVE + 120);

    let mut kept: Vec<String> = Vec::new();
    let mut used = 0usize;
    let lines: Box<dyn Iterator<Item = &String>> = if keep_from_end {
        Box::new(metadata.selected_lines.iter().rev())
    } else {
        Box::new(metadata.selected_lines.iter())
    };
    for line in lines {
        let cost = number_width + line.chars().count() + 1;
        if !kept.is_empty() && used + cost > budget {
            break;
        }
        used += cost;
        kept.push(line.clone());
    }
    if keep_from_end {
        kept.reverse();
    }

    let mut adjusted = metadata.clone();
    adjusted.truncated = true;
    if keep_from_end {
        adjusted.returned_start_line = Some(end_line.saturating_sub(kept.len()).saturating_add(1));
    } else {
        adjusted.returned_end_line = Some(start_line + kept.len() - 1);
    }
    adjusted.selected_lines = kept;
    render_read_file_output(&adjusted)
}

/// Build an explicit, copyable next-call instruction for truncated reads.
/// Small-context models follow a literal tool-call template far more
/// reliably than a generic "output was truncated" notice.
pub(crate) fn continuation_hint(metadata: &ReadFileResultMetadata) -> Option<String> {
    if !metadata.truncated {
        return None;
    }
    let start_line = metadata.returned_start_line?;
    let end_line = metadata.returned_end_line?;
    if matches!(metadata.selection, ReadFileSelectionMetadata::Tail { .. }) {
        return Some(format!(
            "[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.]",
            metadata.selected_lines.len(),
            start_line
        ));
    }
    let shown = end_line
        .saturating_sub(start_line)
        .saturating_add(1)
        .max(50);
    let next_start = end_line + 1;
    let next_end = end_line.saturating_add(shown).min(metadata.total_lines);
    Some(format!(
        "[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\": {}}}.]",
        end_line,
        next_start,
        metadata.total_lines,
        metadata.total_lines,
        metadata.display_path,
        next_start,
        next_end
    ))
}

#[derive(Clone, Copy)]
enum ReadSelection {
    Full,
    Range {
        start: usize,
        end_exclusive: Option<usize>,
    },
    Tail {
        count: usize,
    },
}

struct SelectedLines {
    lines: Vec<String>,
    total_lines: usize,
    start_index: usize,
    end_display: usize,
    /// True when the per-call output cap dropped lines the request asked for.
    truncated: bool,
}

/// Truncate a single overlong line, keeping a marker so the model knows
/// content is missing rather than absent.
fn cap_line(line: String) -> String {
    if line.len() <= MAX_LINE_CHARS {
        return line;
    }
    let total_chars = line.chars().count();
    if total_chars <= MAX_LINE_CHARS {
        return line;
    }
    let mut kept: String = line.chars().take(MAX_LINE_CHARS).collect();
    kept.push_str(&format!("… [line truncated; {} chars total]", total_chars));
    kept
}

fn read_selected_lines(content: &str, selection: ReadSelection) -> SelectedLines {
    match selection {
        ReadSelection::Full | ReadSelection::Range { .. } => {
            let (start, end_exclusive) = match selection {
                ReadSelection::Range {
                    start,
                    end_exclusive,
                } => (start, end_exclusive),
                _ => (0, None),
            };

            let mut lines = Vec::new();
            let mut total_lines: usize = 0;
            let mut stored_bytes: usize = 0;
            let mut capped = false;

            for line in content.lines() {
                total_lines += 1;
                let zero_based_index = total_lines - 1;
                let in_range = zero_based_index >= start
                    && end_exclusive.is_none_or(|end| zero_based_index < end);
                if in_range && !capped {
                    let line = cap_line(line.to_string());
                    if !lines.is_empty() && stored_bytes + line.len() > MAX_READ_CHARS {
                        capped = true;
                    } else {
                        stored_bytes += line.len() + 1;
                        lines.push(line);
                    }
                }
                // Keep counting to EOF so total_lines (and the continuation
                // hint) stay accurate even after the cap is hit.
            }

            let (end_display, truncated) = if capped {
                (start + lines.len(), true)
            } else {
                (end_exclusive.unwrap_or(total_lines).min(total_lines), false)
            };
            SelectedLines {
                lines,
                total_lines,
                start_index: start,
                end_display,
                truncated,
            }
        }
        ReadSelection::Tail { count } => {
            let mut lines: VecDeque<String> = VecDeque::new();
            let mut total_lines: usize = 0;
            let mut stored_bytes: usize = 0;

            for line in content.lines() {
                total_lines += 1;
                if lines.len() == count
                    && let Some(dropped) = lines.pop_front()
                {
                    stored_bytes = stored_bytes.saturating_sub(dropped.len() + 1);
                }
                let line = cap_line(line.to_string());
                stored_bytes += line.len() + 1;
                lines.push_back(line);
                // Bound memory and output: keep only the most recent lines
                // that fit the per-call cap.
                while stored_bytes > MAX_READ_CHARS && lines.len() > 1 {
                    if let Some(dropped) = lines.pop_front() {
                        stored_bytes = stored_bytes.saturating_sub(dropped.len() + 1);
                    }
                }
            }

            let lines: Vec<String> = lines.into_iter().collect();
            let start_index = total_lines.saturating_sub(lines.len());
            let truncated = lines.len() < count.min(total_lines);
            SelectedLines {
                lines,
                total_lines,
                start_index,
                end_display: total_lines,
                truncated,
            }
        }
    }
}

/// Document formats `read_file` cannot decode itself but whose text the
/// model can extract with one terminal command.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum DocumentKind {
    Pdf,
    Word,
}

/// Detect PDF (magic bytes) and Word documents (zip/OLE magic + extension).
fn sniff_document_kind(path: &BackendPath, bytes: &[u8]) -> Option<DocumentKind> {
    let header = &bytes[..bytes.len().min(8)];
    if header.starts_with(b"%PDF") {
        return Some(DocumentKind::Pdf);
    }

    let extension = path.extension().map(|ext| ext.to_ascii_lowercase());
    let is_zip = header.starts_with(b"PK\x03\x04");
    let is_ole = header.starts_with(&[0xD0, 0xCF, 0x11, 0xE0]);
    match extension.as_deref() {
        Some("docx") if is_zip => Some(DocumentKind::Word),
        Some("doc") if is_ole => Some(DocumentKind::Word),
        _ => None,
    }
}

/// Escape double quotes so the suggested command stays a single shell token
/// even for paths with spaces or quotes.
fn shell_safe_path(path: &str) -> String {
    path.replace('"', "\\\"")
}

fn document_extraction_stub(
    kind: DocumentKind,
    display_path: &str,
    file_size: u64,
    modified: Option<&str>,
    shell: &str,
    macos: bool,
) -> String {
    let label = match kind {
        DocumentKind::Pdf => "PDF document",
        DocumentKind::Word => "Word document",
    };
    let mut out = format!("{}: {}\nSize: {} bytes\n", label, display_path, file_size);
    if let Some(modified) = modified {
        out.push_str(&format!("Modified: {}\n", modified));
    }
    let quoted = shell_safe_path(display_path);
    match kind {
        DocumentKind::Pdf => {
            out.push_str(&format!(
                "This tool cannot extract PDF text directly. Run the {shell} tool to extract it:\n"
            ));
            out.push_str(&format!("  pdftotext -layout \"{}\" -\n", quoted));
            if macos {
                out.push_str(&format!(
                    "If pdftotext is not installed, use Spotlight's extracted text:\n  mdls -raw -name kMDItemTextContent \"{}\"\n",
                    quoted
                ));
            } else {
                out.push_str(
                    "If pdftotext is not installed, install poppler-utils (e.g. apt install poppler-utils) or use pandoc.\n",
                );
            }
        }
        DocumentKind::Word => {
            out.push_str(&format!(
                "This tool cannot extract Word document text directly. Run the {shell} tool to extract it:\n"
            ));
            if macos {
                out.push_str(&format!("  textutil -convert txt -stdout \"{}\"\n", quoted));
            } else {
                out.push_str(&format!("  pandoc -t plain \"{}\"\n", quoted));
            }
        }
    }
    out.push_str("Do not ask the user to convert the file — extract it yourself.");
    out
}

fn sniff_file_image_mime(bytes: &[u8]) -> Option<&'static str> {
    crate::util::sniff_image_mime(&bytes[..bytes.len().min(16)])
}

async fn image_file_outcome(
    backend: SharedBackend,
    display_path: &str,
    path: &BackendPath,
    file_size: u64,
    modified: Option<&str>,
    mime_type: &str,
) -> anyhow::Result<ToolCallOutcome> {
    let mut output = format!("Image file: {}\nSize: {} bytes\n", display_path, file_size);
    if let Some(modified) = modified {
        output.push_str(&format!("Modified: {}\n", modified));
    }
    output.push_str(&format!("Type: {mime_type}\n"));
    output.push_str("Attached for vision analysis.");

    let filename = path.file_name().unwrap_or("image").to_string();
    let staging_dir = std::env::temp_dir().join("aidaemon-execution-observations");
    tokio::fs::create_dir_all(&staging_dir).await?;
    let local_path = staging_dir.join(format!("{}-{}", uuid::Uuid::new_v4(), filename));
    backend.export_local_file(path, &local_path).await?;

    Ok(ToolCallOutcome {
        output,
        metadata: ToolCallMetadata {
            attachments: vec![MessageAttachment {
                local_path: local_path.to_string_lossy().into_owned(),
                filename,
                mime_type: mime_type.to_string(),
                size_bytes: file_size,
                provenance: AttachmentProvenance::ToolObservation,
                source_tool: Some("read_file".to_string()),
                ..MessageAttachment::default()
            }],
            ..ToolCallMetadata::default()
        },
        finish: None,
    })
}

fn format_modified_rfc3339(metadata: &BackendMetadata) -> Option<String> {
    let modified = metadata.modified?;
    let modified_utc: chrono::DateTime<chrono::Utc> = modified.into();
    Some(modified_utc.to_rfc3339())
}

fn format_text_file_header(
    path: &str,
    line_summary: &str,
    file_size: u64,
    modified: Option<&str>,
) -> String {
    match modified {
        Some(modified) => format!(
            "File: {} ({}, {} bytes, modified {})\n",
            path, line_summary, file_size, modified
        ),
        None => format!("File: {} ({}, {} bytes)\n", path, line_summary, file_size),
    }
}

#[cfg(test)]
mod document_stub_tests {
    use super::*;

    /// macOS-only extraction commands are suggested only where the file is
    /// on a macOS machine; a remote or non-macOS backend gets portable ones.
    #[test]
    fn extraction_commands_follow_where_the_file_is() {
        let remote = document_extraction_stub(
            DocumentKind::Pdf,
            "/workspace/report.pdf",
            10,
            None,
            "terminal",
            false,
        );
        assert!(
            remote.contains("pdftotext") && !remote.contains("mdls"),
            "{remote}"
        );
        let word = document_extraction_stub(
            DocumentKind::Word,
            "/workspace/notes.docx",
            10,
            None,
            "terminal",
            false,
        );
        assert!(
            word.contains("pandoc") && !word.contains("textutil"),
            "{word}"
        );
        let mac = document_extraction_stub(
            DocumentKind::Pdf,
            "/Users/synthetic/report.pdf",
            10,
            None,
            "terminal",
            true,
        );
        assert!(mac.contains("mdls"), "{mac}");
    }
}