Skip to main content

merry_tools/read/
pdf.rs

1//! PDF file detection, response contract, and feature-gated `hayro` dispatch.
2
3use std::{fs, path::Path};
4
5use merry_runtime::ToolExecutionOutcome;
6use serde::{Deserialize, Serialize};
7
8#[cfg(not(feature = "pdf"))]
9use crate::errors::{DomainError, ERROR_INVALID_DOCUMENT};
10use crate::{
11    config::WorkspaceToolLimits, errors::BlockingToolError, path::ValidatedToolPath,
12    read::input::PdfReadFormat,
13};
14
15#[cfg(all(test, feature = "pdf"))]
16pub(crate) use super::pdf_hayro::parse_page_range;
17
18const PDF_MAGIC: &[u8; 5] = b"%PDF-";
19
20/// Structured success envelope produced by `read_file` when rendering PDF pages as images.
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
22pub struct WorkspaceReadPdfPagesSuccess {
23    /// Always `true` for a successful PDF page render.
24    pub ok: bool,
25    /// Stable tool name (`read_file`).
26    pub tool: String,
27    /// Content kind discriminant (`pdf_pages`).
28    pub kind: String,
29    /// Normalized display path.
30    pub path: String,
31    /// Total number of pages in the PDF document.
32    pub total_pages: usize,
33    /// One-based page numbers rendered and attached in order.
34    pub rendered_pages: Vec<usize>,
35    /// Source PDF file size in bytes.
36    pub source_bytes: usize,
37    /// Combined PNG byte size of all attached page images.
38    pub total_png_bytes: usize,
39}
40
41/// Detects whether a file should be handled as a PDF document.
42pub(super) fn is_pdf_file(path: &Path, sniff_bytes: &[u8]) -> bool {
43    sniff_bytes.starts_with(PDF_MAGIC) || super::has_extension(path, "pdf")
44}
45
46pub(super) struct PdfReadRequest<'a> {
47    pub(super) pages: Option<&'a str>,
48    pub(super) format: PdfReadFormat,
49    pub(super) start_line: usize,
50    pub(super) max_lines: usize,
51}
52
53pub(super) fn read_resolved_pdf(
54    relative: &ValidatedToolPath,
55    file: &mut fs::File,
56    request: PdfReadRequest<'_>,
57    limits: &WorkspaceToolLimits,
58    is_cancelled: &dyn Fn() -> bool,
59) -> Result<ToolExecutionOutcome, BlockingToolError> {
60    #[cfg(feature = "pdf")]
61    {
62        super::pdf_hayro::read_resolved_pdf(relative, file, request, limits, is_cancelled)
63    }
64    #[cfg(not(feature = "pdf"))]
65    {
66        let _ = (
67            relative,
68            file,
69            request.pages,
70            request.format,
71            request.start_line,
72            request.max_lines,
73            limits,
74        );
75        if is_cancelled() {
76            return Err(BlockingToolError::Cancelled);
77        }
78        Err(DomainError::new(
79            ERROR_INVALID_DOCUMENT,
80            "PDF reading is disabled in this build (compiled without the `pdf` feature)",
81        )
82        .into())
83    }
84}