UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

272 lines (271 loc) • 16.9 kB
import { delimitUntrusted } from "../../core/untrusted-text.js"; import { resolveImageProcessor } from "../../core/image-downsample.js"; import { PDF_FALLBACK_RENDER_PAGES, PDF_INLINE_PAGE_THRESHOLD, PDF_MAX_EXTRACT_SIZE, PDF_MAX_PAGES_PER_READ, extractPdfPagesAsImages, extractPdfTextLayer, getPdfPageCount, parsePdfPageRange, pdfCutWords, } from "./pdf.js"; import { admitImageBytes, IMAGE_ADMISSION, PDF_TARGET_RAW_SIZE, pdfMagicMatches, unprocessedSizeClause } from "../../core/image-admission.js"; import { MAX_READ_BYTES } from "./fs-shared.js"; import { shellQuote } from "./search.js"; import { envErrorDetail } from "./env-error-detail.js"; import { readFloorSeat } from "./read-floor.js"; import { planReminderDisclosure, renderReminderDisclosureTrailer } from "../../core/reminder-disclosure.js"; import { MARKED_BLOCK_AFTER_DATA } from "../../core/reminder-mint.js"; function pdfDisclosureTrailer(body, d) { if (d === undefined) return ""; const plan = planReminderDisclosure({ segments: [body], mark: d.mark, outlet: "pdf", defuseExactMark: false, throttle: { key: d.key, windows: d.windows } }); d.effects.push(plan.effects); const trailer = renderReminderDisclosureTrailer(plan.verdict, d.mark); return trailer !== undefined ? `${MARKED_BLOCK_AFTER_DATA}${trailer}` : ""; } export { pdfModelCapabilitiesOf, servingModelPdfCapabilities } from "./pdf.js"; async function pdfPagesToImageBlocks(pages, path, imageProcessor) { const processor = await resolveImageProcessor(imageProcessor); const blocks = []; for (const p of pages) { const admitted = await admitImageBytes(p.jpeg, "image/jpeg", processor); if (!admitted.ok) { return `Error (Read): rendered page ${p.pageNumber} of "${path}" cannot be sent (${pageRefusal(admitted)}); narrow the range or extract text via Bash (e.g. \`pdftotext\`).`; } blocks.push(admitted.block); } return blocks; } function pageRefusal(a) { switch (a.reason) { case "mime_unsupported": case "magic_mismatch": return "the renderer's output is not a valid JPEG"; case "raw_too_large": return `${a.rawBytes} bytes, over the ${a.cap}-byte read cap`; case "dimensions_unreadable": case "dimensions_too_large": return unprocessedSizeClause(a); case "base64_too_large": return `base64 ${a.base64.length} chars exceeds the ${IMAGE_ADMISSION.hard.imageBase64Chars}-char / 5MB API image limit`; } } function pdftotextCommand(path, range) { return `pdftotext -layout ${range !== undefined ? `-f ${range.first} -l ${range.last} ` : ""}${shellQuote(path)} -`; } function pdfShellRoute(missing, path, range) { return `${missing ? "Install poppler-utils, or extract" : "Extract"} the text via Bash (e.g. \`${pdftotextCommand(path, range)}\`).`; } function pageRangeRoute(path, first, last) { return `Read the whole PDF without \`pages\` (works up to ${PDF_INLINE_PAGE_THRESHOLD} pages / 20 MB), or extract the text via Bash (e.g. \`${pdftotextCommand(path, { first, last })}\`).`; } function boundPdfExtractedText(text) { if (Buffer.byteLength(text, "utf8") <= MAX_READ_BYTES) return { body: text, truncated: false }; return { body: text.slice(0, MAX_READ_BYTES), truncated: true }; } export async function readPdfFile(env, path, pdf, pages, signal, imageProcessor, preRead, caps, readDeny, disclosure) { const cap = caps ?? { document: true, vision: true }; const readFloor = readFloorSeat(readDeny)?.(undefined); const judgedSize = preRead ? preRead.byteLength : pdf.size; if (judgedSize > PDF_MAX_EXTRACT_SIZE) { return `Error (Read): PDF "${path}" exceeds the maximum size for PDF reading (${judgedSize} bytes > ${PDF_MAX_EXTRACT_SIZE}-byte / 100 MB cap).`; } const byName = pdf.object.byName; const cannotRead = (bin) => `Error (Read): cannot read PDF "${path.slice(0, 300)}": ${envErrorDetail(bin.error.message)}`; let bytes = preRead; let input; if (byName === undefined) { if (bytes === undefined) { const bin = await pdf.object.readBytes(PDF_MAX_EXTRACT_SIZE, signal); if (!bin.ok) return cannotRead(bin); bytes = bin.value; } input = { held: bytes }; } else { if (bytes === undefined && judgedSize <= PDF_TARGET_RAW_SIZE) { const bin = await pdf.object.readBytes(PDF_TARGET_RAW_SIZE, signal); if (!bin.ok) return cannotRead(bin); bytes = bin.value; } input = { byName }; } const size = bytes?.byteLength ?? judgedSize; if (bytes !== undefined && !pdfMagicMatches(bytes)) { return `Error (Read): "${path}" has a .pdf extension but its content is not a valid PDF (no %PDF- header; empty, truncated, or mis-named). If it is text, rename it with a shell command (e.g. mv) to a name that is not .pdf and read it under that name.`; } if (pages !== undefined) { const range = parsePdfPageRange(pages); if (range === undefined) { return `Error (Read): Invalid pages parameter: "${pages}". Use formats like "1-5", "3", or "10-20". Pages are 1-indexed.`; } if (range.last !== Infinity && range.last - range.first + 1 > PDF_MAX_PAGES_PER_READ) { return `Error (Read): Page range "${pages}" exceeds maximum of ${PDF_MAX_PAGES_PER_READ} pages per request. Please use a smaller range.`; } const pageCount = await getPdfPageCount(env, input, bytes, signal, readFloor); if (pageCount !== undefined && range.first > pageCount) { return `Error (Read): page range "${pages}" starts past the end of the PDF (${pageCount} page${pageCount === 1 ? "" : "s"}).`; } let last = range.last === Infinity ? range.first + PDF_MAX_PAGES_PER_READ - 1 : range.last; if (pageCount !== undefined) last = Math.min(last, pageCount); if (!cap.document && !cap.vision) { const t = await extractPdfTextLayer(env, input, { first: range.first, last }, signal, readFloor); if (t.ok) { const { body, truncated } = boundPdfExtractedText(t.text); const words = t.cut !== undefined ? pdfCutWords(t.cut) : undefined; const timeoutNote = words !== undefined ? `; PARTIAL — pdftotext ${words.clause}, so the text below covers only what was extracted before the ${words.noun}; use a narrower pages range for the rest` : ""; return { content: [ { type: "text", text: `[PDF: ${path} — pages ${range.first}-${last}${pageCount !== undefined ? ` of ${pageCount}` : ""} extracted as text via pdftotext (the serving model does not support native PDF input)${timeoutNote}]` + `\n${delimitUntrusted("PDF text layer", body)}${truncated ? `\n[extracted text truncated at ${MAX_READ_BYTES} bytes; narrow the pages range]` : ""}${pdfDisclosureTrailer(body, disclosure)}`, }, ], details: { type: "document", file: { type: "application/pdf", originalSize: size, ...(pageCount !== undefined ? { pageCount } : {}), pages: `${range.first}-${last}`, ...(t.cut !== undefined ? { timedOut: true } : {}) }, fallback: { level: 1, reason: "model lacks document input; text layer extracted via pdftotext" }, }, }; } const why = t.toolMissing ? "the poppler utility `pdftotext` is not available in this environment" : `pdftotext failed: ${t.error}`; return { content: [ { type: "text", text: `[PDF pages ${range.first}-${last} of ${path} omitted: the serving model supports neither native PDF (document) input nor image input, and engine-side text extraction did not run (${why}). ` + `${pdfShellRoute(t.toolMissing, path, { first: range.first, last })}]`, }, ], details: { type: "document", file: { type: "application/pdf", originalSize: size, ...(pageCount !== undefined ? { pageCount } : {}), pages: `${range.first}-${last}` }, fallback: { level: 3, reason: why }, }, }; } const extract = await extractPdfPagesAsImages(env, input, range.first, last, signal, readFloor); if (!extract.ok) { if (extract.toolMissing) { return `Error (Read): reading a PDF page range requires the poppler utility \`pdftoppm\`, which is not available in this environment. ${pageRangeRoute(path, range.first, last)}`; } return `Error (Read): PDF page extraction failed for "${path}": ${extract.error.replace(/\.$/, "")}. ${pageRangeRoute(path, range.first, last)}`; } const blocks = await pdfPagesToImageBlocks(extract.pages, path, imageProcessor); if (typeof blocks === "string") return blocks; const requestedPages = last - range.first + 1; const renderedAll = extract.pages.length >= requestedPages; const words = extract.cut !== undefined ? pdfCutWords(extract.cut) : undefined; const header = words !== undefined ? renderedAll ? `[PDF: ${path} — pages ${range.first}-${last}${pageCount !== undefined ? ` of ${pageCount}` : ""}: pdftoppm ${words.clause}, but all ${requestedPages} requested page${requestedPages === 1 ? "" : "s"} were rendered before the ${words.noun} hit at teardown (100 dpi); nothing is missing.]` : `[PDF: ${path} — pages ${range.first}-${last}${pageCount !== undefined ? ` of ${pageCount}` : ""}: pdftoppm ${words.clause}; rendered ${extract.pages.length} of ${requestedPages} requested page${requestedPages === 1 ? "" : "s"} before the ${words.noun} (100 dpi). Read the remaining pages with a narrower range (e.g. pages: "${range.first + extract.pages.length}-${last}").]` : `[PDF: ${path} — pages ${range.first}-${last}${pageCount !== undefined ? ` of ${pageCount}` : ""} rendered as ${extract.pages.length} image${extract.pages.length === 1 ? "" : "s"} (100 dpi)]`; const content = [ { type: "text", text: header }, ...blocks, ]; return { content, details: { type: "document", file: { type: "application/pdf", originalSize: size, ...(pageCount !== undefined ? { pageCount } : {}), pages: `${range.first}-${last}`, renderedPages: extract.pages.length, ...(extract.cut !== undefined ? { requestedPages, timedOut: true } : {}), }, }, }; } const pageCount = await getPdfPageCount(env, input, bytes, signal, readFloor); if (pageCount !== undefined && pageCount > PDF_INLINE_PAGE_THRESHOLD) { return `Error (Read): This PDF has ${pageCount} pages, which is too many to read at once. Use the pages parameter to read specific page ranges (e.g., pages: "1-5"). Maximum ${PDF_MAX_PAGES_PER_READ} pages per request.`; } if (size > PDF_TARGET_RAW_SIZE || bytes === undefined) { return `Error (Read): PDF file exceeds maximum allowed size of 20.0 MB (${size} bytes). Use the pages parameter to read specific page ranges (e.g., pages: "1-5"), or extract text via Bash (e.g. \`pdftotext\`).`; } if (!cap.document) { const fileCard = { type: "application/pdf", originalSize: size, ...(pageCount !== undefined ? { pageCount } : {}) }; const t = await extractPdfTextLayer(env, input, undefined, signal, readFloor); if (t.ok) { const { body, truncated } = boundPdfExtractedText(t.text); const words = t.cut !== undefined ? pdfCutWords(t.cut) : undefined; const timeoutNote = words !== undefined ? `; PARTIAL — pdftotext ${words.clause}, so the text below covers only what was extracted before the ${words.noun}; use the pages parameter for the rest` : ""; return { content: [ { type: "text", text: `[PDF: ${path} — extracted text layer via pdftotext${pageCount !== undefined ? `; ${pageCount} page${pageCount === 1 ? "" : "s"}` : ""} (the serving model does not support native PDF input)${timeoutNote}]` + `\n${delimitUntrusted("PDF text layer", body)}${truncated ? `\n[extracted text truncated at ${MAX_READ_BYTES} bytes; use the pages parameter to read specific ranges]` : ""}${pdfDisclosureTrailer(body, disclosure)}`, }, ], details: { type: "document", file: { ...fileCard, ...(t.cut !== undefined ? { timedOut: true } : {}) }, fallback: { level: 1, reason: "model lacks document input; text layer extracted via pdftotext" }, }, }; } const textWhy = t.toolMissing ? "`pdftotext` is not available in this environment" : `pdftotext failed: ${t.error}`; let renderWhy; let renderMissing = false; if (cap.vision) { const n = Math.min(PDF_FALLBACK_RENDER_PAGES, pageCount ?? PDF_FALLBACK_RENDER_PAGES); const extract = await extractPdfPagesAsImages(env, input, 1, n, signal, readFloor); if (extract.ok) { const blocks = await pdfPagesToImageBlocks(extract.pages, path, imageProcessor); if (typeof blocks !== "string") { const renderTimeoutNote = extract.cut !== undefined ? ` pdftoppm ${pdfCutWords(extract.cut).clause} — only the pages that finished rendering are included.` : ""; return { content: [ { type: "text", text: `[PDF: ${path} — first ${extract.pages.length}${pageCount !== undefined ? ` of ${pageCount}` : ""} page${extract.pages.length === 1 ? "" : "s"} rendered as image${extract.pages.length === 1 ? "" : "s"} (100 dpi; ${textWhy}).${renderTimeoutNote} ` + `Use the pages parameter (e.g., pages: "${extract.pages.length + 1}-${extract.pages.length + PDF_FALLBACK_RENDER_PAGES}") to read more pages.]`, }, ...blocks, ], details: { type: "document", file: { ...fileCard, pages: `1-${extract.pages.length}`, renderedPages: extract.pages.length, ...(extract.cut !== undefined ? { timedOut: true } : {}) }, fallback: { level: 2, reason: `model lacks document input; ${textWhy}; rendered first ${extract.pages.length} page(s) via pdftoppm` }, }, }; } renderWhy = "a rendered page image exceeded the per-image API size limit"; } else { renderMissing = extract.toolMissing; renderWhy = extract.toolMissing ? "the poppler utility `pdftoppm` is not available in this environment" : `pdftoppm failed: ${extract.error}`; } } else { renderWhy = "the serving model does not support image input, so pages cannot be rendered"; } const why = `text extraction did not run (${textWhy}); page rendering did not run (${renderWhy})`; return { content: [ { type: "text", text: `[PDF document omitted: the serving model does not support native PDF (document) input, and engine-side fallbacks were unavailable — ${why}. ` + `${pdfShellRoute(t.toolMissing || renderMissing, path)}]`, }, ], details: { type: "document", file: fileCard, fallback: { level: 3, reason: why } }, }; } const base64 = Buffer.from(bytes).toString("base64"); return { content: [{ type: "document", data: base64, mimeType: "application/pdf" }], details: { type: "document", file: { ...(base64.length <= 48_000 ? { base64 } : {}), type: "application/pdf", originalSize: size, ...(pageCount !== undefined ? { pageCount } : {}) }, }, }; }