merry-tools 0.1.2

Workspace file, search, patch, web fetch, and document tools for the Merry agent runtime.
Documentation
//! PDF file detection, response contract, and feature-gated `hayro` dispatch.

use std::{fs, path::Path};

use merry_runtime::ToolExecutionOutcome;
use serde::{Deserialize, Serialize};

#[cfg(not(feature = "pdf"))]
use crate::errors::{DomainError, ERROR_INVALID_DOCUMENT};
use crate::{
    config::WorkspaceToolLimits, errors::BlockingToolError, path::ValidatedToolPath,
    read::input::PdfReadFormat,
};

#[cfg(all(test, feature = "pdf"))]
pub(crate) use super::pdf_hayro::parse_page_range;

const PDF_MAGIC: &[u8; 5] = b"%PDF-";

/// Structured success envelope produced by `read_file` when rendering PDF pages as images.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkspaceReadPdfPagesSuccess {
    /// Always `true` for a successful PDF page render.
    pub ok: bool,
    /// Stable tool name (`read_file`).
    pub tool: String,
    /// Content kind discriminant (`pdf_pages`).
    pub kind: String,
    /// Normalized display path.
    pub path: String,
    /// Total number of pages in the PDF document.
    pub total_pages: usize,
    /// One-based page numbers rendered and attached in order.
    pub rendered_pages: Vec<usize>,
    /// Source PDF file size in bytes.
    pub source_bytes: usize,
    /// Combined PNG byte size of all attached page images.
    pub total_png_bytes: usize,
}

/// Detects whether a file should be handled as a PDF document.
pub(super) fn is_pdf_file(path: &Path, sniff_bytes: &[u8]) -> bool {
    sniff_bytes.starts_with(PDF_MAGIC) || super::has_extension(path, "pdf")
}

pub(super) struct PdfReadRequest<'a> {
    pub(super) pages: Option<&'a str>,
    pub(super) format: PdfReadFormat,
    pub(super) start_line: usize,
    pub(super) max_lines: usize,
}

pub(super) fn read_resolved_pdf(
    relative: &ValidatedToolPath,
    file: &mut fs::File,
    request: PdfReadRequest<'_>,
    limits: &WorkspaceToolLimits,
    is_cancelled: &dyn Fn() -> bool,
) -> Result<ToolExecutionOutcome, BlockingToolError> {
    #[cfg(feature = "pdf")]
    {
        super::pdf_hayro::read_resolved_pdf(relative, file, request, limits, is_cancelled)
    }
    #[cfg(not(feature = "pdf"))]
    {
        let _ = (
            relative,
            file,
            request.pages,
            request.format,
            request.start_line,
            request.max_lines,
            limits,
        );
        if is_cancelled() {
            return Err(BlockingToolError::Cancelled);
        }
        Err(DomainError::new(
            ERROR_INVALID_DOCUMENT,
            "PDF reading is disabled in this build (compiled without the `pdf` feature)",
        )
        .into())
    }
}