pi-quiver 6.12.0 → 6.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -8,6 +8,14 @@ Published to npm as `pi-quiver` (`pi install npm:pi-quiver`). Pushing a
8
8
  via OIDC trusted publishing. The release helper at
9
9
  `.agents/skills/release/scripts/release.sh` cuts the tag; CI publishes.
10
10
 
11
+ ## v6.13.1 - 2026-10-08
12
+
13
+ - `pi-quiver` CLI: SIGTERM/SIGINT/SIGHUP now kill the detached doc-to-md converter group (python, raster worker, soffice) before exiting with 128+signo; before, a signal-killed CLI orphaned the converter because the `exit` hook does not run on signal death. Library behavior inside pi is unchanged.
14
+
15
+ ## v6.13.0 - 2026-10-06
16
+
17
+ - `doc_to_md` / `pi-quiver doc-to-md`: `quiver.docToMd.ocrMaxPages` (default 10, settings-only) caps the pages one call OCRs. `ocrMode: "all"` rejects a larger distinct-page selection before any work (CLI exit 2), counting merged ranges without expanding them; textless mode OCRs the first `ocrMaxPages` textless pages and lists the rest as `ceilingStopped` with the `pages` to rerun. Integer settings now require safe integers. (#29)
18
+
11
19
  ## v6.12.0 - 2026-10-06
12
20
 
13
21
  - `/rebase-worktree [base]` prompt template (pi only, `prompts/`): rebases the current worktree onto `origin/<base>` (default `main`), resolves conflicts inline, runs only the tests covering the resolved files, never pushes.
package/README.md CHANGED
@@ -311,8 +311,9 @@ Each setting can also be overridden per-process via `PI_QUIVER_SLACK_ENABLED`, `
311
311
  | `outlineMaxEntries` | `40` | Heading outline, TOC, or sheet inventory entries in the handle. |
312
312
  | `ocr` | `false` | Opt-in OCR for scanned pages and images when Tesseract language data is installed. |
313
313
  | `ocrLanguage` | `eng` | Plain `+`-joined Tesseract language codes for OCR. |
314
+ | `ocrMaxPages` | `10` | Most pages one call OCRs. Settings-only - no tool parameter or CLI flag, so an agent cannot raise it per call. `ocrMode: "all"` rejects a larger distinct-page selection before any work (CLI exit 2); textless mode OCRs the first `ocrMaxPages` textless pages in page order and the `OCR:` line names the rest with the `pages` to rerun. Must be a positive safe integer; an invalid value warns and the lower layer or the default applies. |
314
315
 
315
- `ocrMode` (`textless` | `all`) is a per-call parameter and `--ocr-mode` flag only; a `quiver.docToMd.ocrMode` key is reported as unknown and ignored, so persisted settings cannot enable forced OCR or bypass its explicit-pages guard.
316
+ `ocrMode` (`textless` | `all`) is a per-call parameter and `--ocr-mode` flag only; a `quiver.docToMd.ocrMode` key is reported as unknown and ignored, so persisted settings cannot enable forced OCR or bypass its explicit-pages guard. `ocrMaxPages` is the mirror image: settings-only, so a per-call argument cannot lift the ceiling. Convert without OCR first, read `Page-Stats` to find the scanned pages, and select only those; for more than `ocrMaxPages` pages run explicit sequential batches within the ceiling and inspect each result before the next.
316
317
 
317
318
  A bundle is `<outputDir>/<stem>.md` plus `<outputDir>/<stem>.pages.json` on Python PDF tiers, optional OCR sidecars under `<outputDir>/ocr/`, and `<outputDir>/images/` and, for spreadsheets with data, `<outputDir>/sheets/`; without `outputDir`, the tool creates a per-call temp root. A conversion owns `<stem>.md.lock` until it atomically publishes the Markdown. An existing `<stem>.md` fails the call unless `overwrite` is set; `overwrite` replaces that Markdown and the files it owns (`images/<stem>-p<N>-<n>.*`, `images/<stem>-s<idx>[-<n>].*`, `sheets/<stem>-s<idx>-<slug>.csv`, `<stem>.pages.json`, `ocr/<stem>-pNNN.md`), nothing else. Temp bundles are caller-owned - the tool never deletes a bundle it produced.
318
319
 
@@ -921,6 +921,11 @@ function ocrLine(ocr, type) {
921
921
  const r = compactRanges(ocr.budgetStopped, Number.POSITIVE_INFINITY).replaceAll(", ", ",");
922
922
  clauses.push(`time budget reached for pages=${r}; rerun with pages=${r} or raise primaryTimeoutMs`);
923
923
  }
924
+ if (ocr.ceilingStopped.length) {
925
+ const all = compactRanges(ocr.ceilingStopped, Number.POSITIVE_INFINITY).replaceAll(", ", ",");
926
+ const next = compactRanges(ocr.ceilingStopped.slice(0, ocr.ocrMaxPages), Number.POSITIVE_INFINITY).replaceAll(", ", ",");
927
+ clauses.push(type === "docx" ? `OCR page ceiling (${ocr.ocrMaxPages}) reached for rendered pages=${all}; export the document to PDF and rerun on it with pages=${next}, or raise quiver.docToMd.ocrMaxPages` : `OCR page ceiling (${ocr.ocrMaxPages}) reached for pages=${all}; rerun with pages=${next} or raise quiver.docToMd.ocrMaxPages`);
928
+ }
924
929
  return clauses.join("; ");
925
930
  }
926
931
  }
@@ -1046,6 +1051,7 @@ var DOC_TO_MD_OPTIONS = [
1046
1051
  { key: "outlineMaxEntries", flag: "--outline-max-entries", type: "int", default: 40, settable: true, help: "Heading outline / TOC / sheet inventory cap in the handle" },
1047
1052
  { key: "ocr", flag: "--ocr", type: "bool", default: false, settable: true, help: "Run OCR on pages without a text layer and on image inputs when Tesseract language data is installed; off by default (--no-ocr turns a settings-level true off)" },
1048
1053
  { key: "ocrLanguage", flag: "--ocr-language", type: "lang", default: "eng", settable: true, help: "Tesseract language code(s), +-joined, e.g. deu+eng" },
1054
+ { key: "ocrMaxPages", flag: null, type: "int", default: 10, settable: true, settingsOnly: true, help: "Most pages one invocation OCRs; ocrMode all rejects a larger distinct-page selection before any work, textless mode OCRs the first ocrMaxPages textless pages and names the rest in the OCR: line" },
1049
1055
  { key: "hideAnnotations", flag: "--hide-annotations", type: "bool", default: false, settable: true, help: "Render PDF pages without annotations (sticky notes, highlights, stamps - and form-field widgets, so filled form values disappear); default paints them, as PyMuPDF does. Applies to pages/ renders and textless-page renders, not to OCR text or embedded images; also lets an annotated scan be delivered as its embedded image." }
1050
1056
  ];
1051
1057
  var TUNABLE_DEFAULTS = Object.fromEntries(
@@ -1063,7 +1069,7 @@ function coerceValue(d, raw, fromString = false) {
1063
1069
  switch (d.type) {
1064
1070
  case "int": {
1065
1071
  const n = fromString && typeof raw === "string" ? Number(raw) : raw;
1066
- return typeof n === "number" && Number.isInteger(n) && n > 0 ? { ok: true, value: n } : { ok: false, reason: "must be a positive integer" };
1072
+ return typeof n === "number" && Number.isSafeInteger(n) && n > 0 ? { ok: true, value: n } : { ok: false, reason: "must be a positive integer" };
1067
1073
  }
1068
1074
  case "bool":
1069
1075
  return typeof raw === "boolean" ? { ok: true, value: raw } : { ok: false, reason: "must be true or false" };
@@ -1078,7 +1084,7 @@ function coerceValue(d, raw, fromString = false) {
1078
1084
  case "string":
1079
1085
  return typeof raw === "string" && raw.length > 0 ? { ok: true, value: raw } : { ok: false, reason: "must be a non-empty string" };
1080
1086
  case "pages":
1081
- return typeof raw === "string" ? { ok: true, value: parsePages(raw) } : { ok: false, reason: "must be a string" };
1087
+ return typeof raw === "string" ? { ok: true, value: pageIntervals(raw) } : { ok: false, reason: "must be a string" };
1082
1088
  }
1083
1089
  }
1084
1090
  function coerceDocToMdSettings(raw, warn = console.warn) {
@@ -1096,20 +1102,39 @@ function coerceDocToMdSettings(raw, warn = console.warn) {
1096
1102
  }
1097
1103
  return out;
1098
1104
  }
1099
- function parsePages(spec) {
1105
+ function pageIntervals(spec) {
1100
1106
  if (spec.trim() === "") return null;
1101
- const out = /* @__PURE__ */ new Set();
1107
+ const out = [];
1102
1108
  const parts = spec.split(",").map((s) => s.trim());
1103
1109
  if (parts.length === 0 || parts.some((p) => p === "")) throw new UsageError(`invalid --pages "${spec}": expected e.g. "12-15" or "3,7,10-12"`);
1104
1110
  for (const p of parts) {
1105
1111
  const m = p.match(/^(\d+)(?:-(\d+))?$/);
1106
1112
  if (!m) throw new UsageError(`invalid --pages "${spec}": bad token "${p}"`);
1107
1113
  const a = Number(m[1]), b = m[2] === void 0 ? a : Number(m[2]);
1114
+ if (!Number.isSafeInteger(a) || !Number.isSafeInteger(b)) throw new UsageError(`invalid --pages "${spec}": page numbers above ${Number.MAX_SAFE_INTEGER} are not supported`);
1108
1115
  if (a < 1 || b < a) throw new UsageError(`invalid --pages "${spec}": pages are 1-based and ranges ascend`);
1109
- for (let i = a; i <= b; i++) out.add(i);
1116
+ out.push([a, b]);
1110
1117
  }
1118
+ return out;
1119
+ }
1120
+ function countDistinctPages(intervals) {
1121
+ const sorted = [...intervals].sort((x, y) => x[0] - y[0]);
1122
+ let total = 0, start = sorted[0][0], end = sorted[0][1];
1123
+ for (const [a, b] of sorted.slice(1)) {
1124
+ if (a > end + 1) {
1125
+ total += end - start + 1;
1126
+ start = a;
1127
+ end = b;
1128
+ } else end = Math.max(end, b);
1129
+ }
1130
+ return total + end - start + 1;
1131
+ }
1132
+ function expandPages(intervals) {
1133
+ const out = /* @__PURE__ */ new Set();
1134
+ for (const [a, b] of intervals) for (let i = a; i <= b; i++) out.add(i);
1111
1135
  return [...out].sort((x, y) => x - y);
1112
1136
  }
1137
+ var ocrCeilingMessage = (count, ceiling, spec) => `ocrMode "all" selects ${count} distinct pages (pages=${spec.length > 80 ? `${spec.slice(0, 77)}...` : spec}); the OCR page ceiling is ${ceiling} (quiver.docToMd.ocrMaxPages). Broad OCR is slow and usually unnecessary: convert without OCR first, read Page-Stats to find the pages that need it, and select only those. For more than ${ceiling} pages, run explicit sequential batches within the ceiling and inspect each result before the next. The ceiling is settings-only; no tool or CLI argument raises it.`;
1113
1138
  function sanitizeStem(base) {
1114
1139
  const s = base.replace(/[^A-Za-z0-9._-]+/g, "_");
1115
1140
  return s.length ? s : "document";
@@ -1132,7 +1157,7 @@ function resolveOptions(perCall, settings, env) {
1132
1157
  value = c.value;
1133
1158
  }
1134
1159
  if (d.settable && settings[d.key] !== void 0) value = settings[d.key];
1135
- const pc = perCall[d.key];
1160
+ const pc = d.settingsOnly ? void 0 : perCall[d.key];
1136
1161
  if (pc !== void 0 && pc !== null) {
1137
1162
  const c = coerceValue(d, pc);
1138
1163
  if (!c.ok) throw new UsageError(`${d.flag} ${c.reason}`);
@@ -1141,6 +1166,12 @@ function resolveOptions(perCall, settings, env) {
1141
1166
  out[d.key] = value;
1142
1167
  }
1143
1168
  const o = out;
1169
+ const intervals = out.pages;
1170
+ if (intervals && o.ocrMode === "all") {
1171
+ const n = countDistinctPages(intervals);
1172
+ if (n > o.ocrMaxPages) throw new UsageError(ocrCeilingMessage(n, o.ocrMaxPages, perCall.pages));
1173
+ }
1174
+ o.pages = intervals && expandPages(intervals);
1144
1175
  if (o.info && (o.pages !== null || o.outputDir !== null || o.overwrite || o.pageImages || o.words || o.ocrMode === "all")) {
1145
1176
  throw new UsageError("--info cannot be combined with --pages, --output-dir, --overwrite, --page-images, --words or --ocr-mode all");
1146
1177
  }
@@ -1160,6 +1191,10 @@ var USAGE_PATTERNS = [
1160
1191
  " 3. --ocr-mode all refuses to run without --ocr and an explicit --pages.",
1161
1192
  ' The "ocr" object (OCR: line) names failed, budget-stopped, killed and',
1162
1193
  " not-attempted pages and the exact --pages to re-run.",
1194
+ " 4. OCR is capped at quiver.docToMd.ocrMaxPages pages per call (default 10,",
1195
+ " settings-only): --ocr-mode all refuses a larger distinct-page selection",
1196
+ " before any work; textless mode OCRs the first ocrMaxPages textless pages",
1197
+ " and the OCR: line names the rest with the exact --pages to re-run.",
1163
1198
  " Details: doc/doc-to-md.md (bundle contract, failure buckets)."
1164
1199
  ].join("\n");
1165
1200
  var usagePatterns = (cmd) => USAGE_PATTERNS.replaceAll("<cmd>", cmd);
@@ -1176,7 +1211,7 @@ var BUNDLE_LAYOUT = [
1176
1211
  ];
1177
1212
  var bundleLayoutText = () => BUNDLE_LAYOUT.map((r) => ` ${r.artifact.padEnd(28)} ${r.trigger}; ${r.content}; named by ${r.namedBy}`).join("\n");
1178
1213
  function renderHelp() {
1179
- const row = (d) => ` ${(d.flag ?? "<path>").padEnd(26)} ${d.help}${d.default !== null && d.key !== "info" && d.key !== "overwrite" ? ` (default ${d.default})` : ""}`;
1214
+ const row = (d) => ` ${(d.flag ?? (d.settingsOnly ? `quiver.docToMd.${d.key}` : "<path>")).padEnd(26)} ${d.help}${d.settingsOnly ? " (settings-only)" : ""}${d.default !== null && d.key !== "info" && d.key !== "overwrite" ? ` (default ${d.default})` : ""}`;
1180
1215
  return [
1181
1216
  "Usage: pi-quiver doc-to-md [flags] <path>",
1182
1217
  "",
@@ -1255,6 +1290,11 @@ function killTree(child) {
1255
1290
  process.on("exit", () => {
1256
1291
  for (const c of LIVE) killTree(c);
1257
1292
  });
1293
+ var SIGNAL_EXIT_CODES = { SIGHUP: 1, SIGINT: 2, SIGTERM: 15 };
1294
+ function exitOnSignalKillingChildren() {
1295
+ if (process.platform === "win32") return;
1296
+ for (const [sig, num] of Object.entries(SIGNAL_EXIT_CODES)) process.on(sig, () => process.exit(128 + num));
1297
+ }
1258
1298
  async function runCapped(cmd, args, opts) {
1259
1299
  return new Promise((resolveP) => {
1260
1300
  let settled = false;
@@ -1671,7 +1711,7 @@ function reconcileRenderMarkers(md, renderPages, fmt, sourceMap, reason) {
1671
1711
  if (/<!--rvs?:\d+-->/.test(md)) throw new Error("internal: unresolved render marker");
1672
1712
  return md;
1673
1713
  }
1674
- var emptyOcr = (lang) => ({ status: "off", lang, textless: [], pages: [], noText: [], ocrFailed: [], budgetStopped: [], reason: null, tesseract: null, mode: "textless", sidecars: {}, wordSidecars: {}, ocrErrors: {}, killed: null, notAttempted: [], childError: null });
1714
+ var emptyOcr = (o) => ({ status: "off", lang: o.ocrLanguage, textless: [], pages: [], noText: [], ocrFailed: [], budgetStopped: [], ceilingStopped: [], ocrMaxPages: o.ocrMaxPages, reason: null, tesseract: null, mode: "textless", sidecars: {}, wordSidecars: {}, ocrErrors: {}, killed: null, notAttempted: [], childError: null });
1675
1715
  var emptyOutcome = () => ({ written: [], noText: [], ocrFailed: [], ocrErrors: {}, budgetStopped: [], killed: null, notAttempted: [], childError: null });
1676
1716
  var ocrPagesTag = (n) => `p${String(n).padStart(3, "0")}`;
1677
1717
  var SIDE_MARKER_RE = /^--- end of page\.page_number=\d+ ---$/;
@@ -1711,10 +1751,10 @@ function resolveOcrLabels(md, sourceMap) {
1711
1751
  });
1712
1752
  }
1713
1753
  function handleOcr(tier, type, o, json) {
1714
- if (tier === "unpdf") return o.ocr ? { ...emptyOcr(o.ocrLanguage), status: "unavailable", reason: "no Python backend" } : null;
1754
+ if (tier === "unpdf") return o.ocr ? { ...emptyOcr(o), status: "unavailable", reason: "no Python backend" } : null;
1715
1755
  const x = json.ocr;
1716
1756
  if (!x || type !== "image" && !x.textless.length && !x.pages.length && !x.ocrFailed.length) return null;
1717
- return { ...emptyOcr(o.ocrLanguage), ...x };
1757
+ return { ...emptyOcr(o), ...x, ocrMaxPages: o.ocrMaxPages };
1718
1758
  }
1719
1759
  var nativeFromChild = (b, json, notes) => (json.nativeImages ?? []).flatMap((e) => {
1720
1760
  const file = b.sourceMap.get(`p${e.page}/${e.file}`);
@@ -1758,7 +1798,7 @@ async function convertDocument(o, signal, seams) {
1758
1798
  let office = null;
1759
1799
  try {
1760
1800
  let pdfPath = inputPath;
1761
- const base = { path: inputPath, pages: o.pages, ...o.words && (type === "pdf" || type === "image") ? { words: true } : {}, stagingDir: b.stagingDir, sheetsStagingDir: b.sheetsStagingDir, pageImages: o.pageImages, pagesStagingDir: b.pagesStagingDir, imageDpi: o.imageDpi, imageFormat: o.imageFormat, maxOutputBytes: o.maxOutputBytes, pymupdfVersion: o.pymupdfVersion, ocr: o.ocr && !forced, ocrLanguage: o.ocrLanguage, ocrBudgetMs: o.primaryTimeoutMs, hideAnnotations: o.hideAnnotations };
1801
+ const base = { path: inputPath, pages: o.pages, ...o.words && (type === "pdf" || type === "image") ? { words: true } : {}, stagingDir: b.stagingDir, sheetsStagingDir: b.sheetsStagingDir, pageImages: o.pageImages, pagesStagingDir: b.pagesStagingDir, imageDpi: o.imageDpi, imageFormat: o.imageFormat, maxOutputBytes: o.maxOutputBytes, pymupdfVersion: o.pymupdfVersion, ocr: o.ocr && !forced, ocrLanguage: o.ocrLanguage, ocrBudgetMs: o.primaryTimeoutMs, ocrMaxPages: o.ocrMaxPages, hideAnnotations: o.hideAnnotations };
1762
1802
  let tier, engine, json, degraded = null, fallbackReason = null;
1763
1803
  let explicitBreaks = null;
1764
1804
  let notes = [];
@@ -1815,7 +1855,7 @@ async function convertDocument(o, signal, seams) {
1815
1855
  tier = "image";
1816
1856
  engine = "copy";
1817
1857
  json = { markdown: `![${b.stem}](p1/${file})
1818
- `, pageCount: 1, notes: [], ocr: { ...emptyOcr(o.ocrLanguage), status: "unavailable", reason } };
1858
+ `, pageCount: 1, notes: [], ocr: { ...emptyOcr(o), status: "unavailable", reason } };
1819
1859
  }
1820
1860
  }
1821
1861
  if (type === "docx" && !lacksDocx(backend)) {
@@ -1967,7 +2007,7 @@ async function convertDocument(o, signal, seams) {
1967
2007
  if (r.ok && r.json.status === "unavailable") throw new Error(`OCR unavailable: ${r.json.reason} (install Tesseract; see doc/doc-to-md.md)`);
1968
2008
  const outcome = r.ok && r.json.status === "ran" ? outcomeFromChild(r.json) : recoverOcrPages(b.ocrStagingDir, o.pages, !r.ok ? "userError" in r ? r.userError : `${r.reason}${detailSuffix(r)}` : "malformed child output");
1969
2009
  const { sidecars, wordSidecars } = publishSidecars(b);
1970
- ocr = { ...emptyOcr(o.ocrLanguage), ...json.ocr, status: "ran", reason: null, mode: "all", pages: outcome.written, noText: outcome.noText, ocrFailed: outcome.ocrFailed, ocrErrors: outcome.ocrErrors, budgetStopped: outcome.budgetStopped, killed: outcome.killed, notAttempted: outcome.notAttempted, childError: outcome.childError, sidecars: Object.fromEntries(sidecars), wordSidecars: Object.fromEntries(wordSidecars) };
2010
+ ocr = { ...emptyOcr(o), ...json.ocr, ocrMaxPages: o.ocrMaxPages, status: "ran", reason: null, mode: "all", pages: outcome.written, noText: outcome.noText, ocrFailed: outcome.ocrFailed, ocrErrors: outcome.ocrErrors, budgetStopped: outcome.budgetStopped, killed: outcome.killed, notAttempted: outcome.notAttempted, childError: outcome.childError, sidecars: Object.fromEntries(sidecars), wordSidecars: Object.fromEntries(wordSidecars) };
1971
2011
  if (o.words && r.ok) takeWordsErrors(r.json);
1972
2012
  }
1973
2013
  if (!isExcel) notes = [...notes, ...json.notes ?? []];
@@ -2217,9 +2257,12 @@ function isMainEntry() {
2217
2257
  return false;
2218
2258
  }
2219
2259
  }
2220
- if (isMainEntry()) main().then((code) => {
2221
- process.exitCode = code;
2222
- });
2260
+ if (isMainEntry()) {
2261
+ exitOnSignalKillingChildren();
2262
+ main().then((code) => {
2263
+ process.exitCode = code;
2264
+ });
2265
+ }
2223
2266
  export {
2224
2267
  cliAgentDir,
2225
2268
  parseCliArgs,
@@ -26,7 +26,10 @@ function schemaFor(d: OptionDescriptor): TSchema {
26
26
 
27
27
  function buildSchema(): TObject {
28
28
  const props: Record<string, TSchema> = {};
29
- for (const d of DOC_TO_MD_OPTIONS) props[d.key] = d.key === "path" ? schemaFor(d) : Type.Optional(schemaFor(d));
29
+ for (const d of DOC_TO_MD_OPTIONS) {
30
+ if (d.settingsOnly) continue;
31
+ props[d.key] = d.key === "path" ? schemaFor(d) : Type.Optional(schemaFor(d));
32
+ }
30
33
  return Type.Object(props);
31
34
  }
32
35
 
@@ -35,7 +38,7 @@ export default function docToMdExtension(pi: ExtensionAPI) {
35
38
  name: "doc_to_md",
36
39
  label: "Convert doc to Markdown bundle",
37
40
  description:
38
- "Convert a local PDF/DOCX/DOC/PPTX/XLSX/XLSM/XLS, email (.msg/.eml), HTML (.html/.htm) or image (.png .jpg .jpeg .tif .tiff .bmp .gif) to a Markdown bundle on disk and return a handle (Saved-To, Images-Dir, Page-Count, Outline, diagnostics) - the Markdown itself is never inlined; read the Saved-To file (offset/limit) for content. `info: true` returns page count, metadata and TOC (or the sheet inventory) without converting - use it to pick `pages`. `pages` selects inclusive 1-based pages (PDF/PPTX) or explicit-page-break segments (DOCX; rejected when the file has none); every selected PDF/PPTX page or DOCX segment when `pageCount > 1` ends with `--- end of page.page_number=N ---`. Images are always extracted into images/ with relative links. Primary engine pymupdf4llm, fallback PyMuPDF text (degraded, marked), pure-JS unpdf only when no Python backend exists. Excel yields a sheet inventory (worksheets + chartsheets), a full CSV per non-empty worksheet under sheets/, a bounded preview with formulas and cached values, merged/hidden disclosure, and rendered chart views when LibreOffice is available. DOCX converts directly (mammoth; python-docx text fallback) and keeps heading styles, so the handle Outline lists `L<line>` and `p<segment>` per heading; LibreOffice (soffice) is optional for DOCX (fallback route, degraded) and Excel rendered views, and required for PPTX. Use `outputDir` for a durable bundle; without it the bundle lands in a per-call temp dir. Input must be a local file path (use fetch first for URLs). HTML converts without Readability (markdownify; Turndown fallback): local and data: images are copied into images/, remote images stay links. Pages without a text layer keep their picture in images/, or pages/ with `pageImages: true`; image inputs keep their picture in images/. `pageImages: true` writes page renders to pages/<stem>-pNNN, and email attachments are saved under attachments/. OCR is off by default: `ocr: true` adds recognized text (labeled as OCR) when Tesseract language data is installed; the handle's OCR: line says what ran. Two-pass OCR: read Page-Stats first, then re-run with ocr: true, ocrMode: \"all\" and an explicit pages selection to get ocr/ sidecars for the pages you name.",
41
+ "Convert a local PDF/DOCX/DOC/PPTX/XLSX/XLSM/XLS, email (.msg/.eml), HTML (.html/.htm) or image (.png .jpg .jpeg .tif .tiff .bmp .gif) to a Markdown bundle on disk and return a handle (Saved-To, Images-Dir, Page-Count, Outline, diagnostics) - the Markdown itself is never inlined; read the Saved-To file (offset/limit) for content. `info: true` returns page count, metadata and TOC (or the sheet inventory) without converting - use it to pick `pages`. `pages` selects inclusive 1-based pages (PDF/PPTX) or explicit-page-break segments (DOCX; rejected when the file has none); every selected PDF/PPTX page or DOCX segment when `pageCount > 1` ends with `--- end of page.page_number=N ---`. Images are always extracted into images/ with relative links. Primary engine pymupdf4llm, fallback PyMuPDF text (degraded, marked), pure-JS unpdf only when no Python backend exists. Excel yields a sheet inventory (worksheets + chartsheets), a full CSV per non-empty worksheet under sheets/, a bounded preview with formulas and cached values, merged/hidden disclosure, and rendered chart views when LibreOffice is available. DOCX converts directly (mammoth; python-docx text fallback) and keeps heading styles, so the handle Outline lists `L<line>` and `p<segment>` per heading; LibreOffice (soffice) is optional for DOCX (fallback route, degraded) and Excel rendered views, and required for PPTX. Use `outputDir` for a durable bundle; without it the bundle lands in a per-call temp dir. Input must be a local file path (use fetch first for URLs). HTML converts without Readability (markdownify; Turndown fallback): local and data: images are copied into images/, remote images stay links. Pages without a text layer keep their picture in images/, or pages/ with `pageImages: true`; image inputs keep their picture in images/. `pageImages: true` writes page renders to pages/<stem>-pNNN, and email attachments are saved under attachments/. OCR is off by default: `ocr: true` adds recognized text (labeled as OCR) when Tesseract language data is installed; the handle's OCR: line says what ran. Two-pass OCR: read Page-Stats first, then re-run with ocr: true, ocrMode: \"all\" and an explicit pages selection to get ocr/ sidecars for the pages you name. OCR is capped at quiver.docToMd.ocrMaxPages pages per call (default 10; settings-only, no tool parameter): ocrMode \"all\" rejects a larger distinct-page selection before any work, and textless mode OCRs the first ocrMaxPages textless pages and names the rest in the OCR: line with the pages to rerun.",
39
42
  promptSnippet: "Convert a local PDF/DOCX/DOC/PPTX/XLSX/XLSM/XLS/MSG/EML/HTML/image to a Markdown bundle (handle returned; read Saved-To)",
40
43
  parameters: buildSchema(),
41
44
 
@@ -81,6 +81,16 @@ function killTree(child: ChildProcess): void {
81
81
 
82
82
  process.on("exit", () => { for (const c of LIVE) killTree(c); });
83
83
 
84
+ // Children run detached (own process group) so killTree can take out python + raster
85
+ // worker + soffice at once; the flip side is that a signal that kills this process never
86
+ // reaches them, and the "exit" hook does not run on a signal death. The CLI opts in to
87
+ // turning TERM/INT/HUP into a normal exit so the hook fires; pi's own host keeps its handlers.
88
+ const SIGNAL_EXIT_CODES = { SIGHUP: 1, SIGINT: 2, SIGTERM: 15 } as const;
89
+ export function exitOnSignalKillingChildren(): void {
90
+ if (process.platform === "win32") return;
91
+ for (const [sig, num] of Object.entries(SIGNAL_EXIT_CODES)) process.on(sig as NodeJS.Signals, () => process.exit(128 + num));
92
+ }
93
+
84
94
  export async function runCapped(
85
95
  cmd: string,
86
96
  args: string[],
@@ -536,7 +546,7 @@ export function reconcileRenderMarkers(md: string, renderPages: number[], fmt: s
536
546
  return md;
537
547
  }
538
548
 
539
- export const emptyOcr = (lang: string): OcrInfo => ({ status: "off", lang, textless: [], pages: [], noText: [], ocrFailed: [], budgetStopped: [], reason: null, tesseract: null, mode: "textless", sidecars: {}, wordSidecars: {}, ocrErrors: {}, killed: null, notAttempted: [], childError: null });
549
+ export const emptyOcr = (o: Pick<DocToMdOptions, "ocrLanguage" | "ocrMaxPages">): OcrInfo => ({ status: "off", lang: o.ocrLanguage, textless: [], pages: [], noText: [], ocrFailed: [], budgetStopped: [], ceilingStopped: [], ocrMaxPages: o.ocrMaxPages, reason: null, tesseract: null, mode: "textless", sidecars: {}, wordSidecars: {}, ocrErrors: {}, killed: null, notAttempted: [], childError: null });
540
550
 
541
551
  export interface OcrPagesOutcome { written: number[]; noText: number[]; ocrFailed: number[]; ocrErrors: Record<number, string>; budgetStopped: number[]; killed: number | null; notAttempted: number[]; childError: string | null; }
542
552
  const emptyOutcome = (): OcrPagesOutcome => ({ written: [], noText: [], ocrFailed: [], ocrErrors: {}, budgetStopped: [], killed: null, notAttempted: [], childError: null });
@@ -580,10 +590,10 @@ export function resolveOcrLabels(md: string, sourceMap: Map<string, string>): st
580
590
  }
581
591
 
582
592
  function handleOcr(tier: Tier, type: InputType, o: DocToMdOptions, json: TierJson): OcrInfo | null {
583
- if (tier === "unpdf") return o.ocr ? { ...emptyOcr(o.ocrLanguage), status: "unavailable", reason: "no Python backend" } : null;
593
+ if (tier === "unpdf") return o.ocr ? { ...emptyOcr(o), status: "unavailable", reason: "no Python backend" } : null;
584
594
  const x = json.ocr;
585
595
  if (!x || (type !== "image" && !x.textless.length && !x.pages.length && !x.ocrFailed.length)) return null;
586
- return { ...emptyOcr(o.ocrLanguage), ...x };
596
+ return { ...emptyOcr(o), ...x, ocrMaxPages: o.ocrMaxPages };
587
597
  }
588
598
 
589
599
  const nativeFromChild = (b: Bundle, json: TierJson, notes: string[]): NativeImage[] => (json.nativeImages ?? []).flatMap((e) => {
@@ -631,7 +641,7 @@ export async function convertDocument(o: DocToMdOptions, signal?: AbortSignal, s
631
641
  let office: { pdfPath: string; cleanup: () => void } | null = null;
632
642
  try {
633
643
  let pdfPath = inputPath;
634
- const base = { path: inputPath, pages: o.pages, ...(o.words && (type === "pdf" || type === "image") ? { words: true } : {}), stagingDir: b.stagingDir, sheetsStagingDir: b.sheetsStagingDir, pageImages: o.pageImages, pagesStagingDir: b.pagesStagingDir, imageDpi: o.imageDpi, imageFormat: o.imageFormat, maxOutputBytes: o.maxOutputBytes, pymupdfVersion: o.pymupdfVersion, ocr: o.ocr && !forced, ocrLanguage: o.ocrLanguage, ocrBudgetMs: o.primaryTimeoutMs, hideAnnotations: o.hideAnnotations };
644
+ const base = { path: inputPath, pages: o.pages, ...(o.words && (type === "pdf" || type === "image") ? { words: true } : {}), stagingDir: b.stagingDir, sheetsStagingDir: b.sheetsStagingDir, pageImages: o.pageImages, pagesStagingDir: b.pagesStagingDir, imageDpi: o.imageDpi, imageFormat: o.imageFormat, maxOutputBytes: o.maxOutputBytes, pymupdfVersion: o.pymupdfVersion, ocr: o.ocr && !forced, ocrLanguage: o.ocrLanguage, ocrBudgetMs: o.primaryTimeoutMs, ocrMaxPages: o.ocrMaxPages, hideAnnotations: o.hideAnnotations };
635
645
  let tier: Tier | undefined, engine: Engine | undefined, json: TierJson | undefined, degraded: string | null = null, fallbackReason: string | null = null;
636
646
  let explicitBreaks: number | null = null;
637
647
  let notes: string[] = [];
@@ -672,7 +682,7 @@ export async function convertDocument(o: DocToMdOptions, signal?: AbortSignal, s
672
682
  writeFileSync(join(dir, ".done"), "");
673
683
  publishStaged(b);
674
684
  tier = "image"; engine = "copy";
675
- json = { markdown: `![${b.stem}](p1/${file})\n`, pageCount: 1, notes: [], ocr: { ...emptyOcr(o.ocrLanguage), status: "unavailable", reason } };
685
+ json = { markdown: `![${b.stem}](p1/${file})\n`, pageCount: 1, notes: [], ocr: { ...emptyOcr(o), status: "unavailable", reason } };
676
686
  }
677
687
  }
678
688
  if (type === "docx" && !lacksDocx(backend)) {
@@ -792,7 +802,7 @@ export async function convertDocument(o: DocToMdOptions, signal?: AbortSignal, s
792
802
  const outcome = r.ok && r.json.status === "ran" ? outcomeFromChild(r.json)
793
803
  : recoverOcrPages(b.ocrStagingDir, o.pages!, !r.ok ? ("userError" in r ? r.userError : `${r.reason}${detailSuffix(r)}`) : "malformed child output");
794
804
  const { sidecars, wordSidecars } = publishSidecars(b);
795
- ocr = { ...emptyOcr(o.ocrLanguage), ...json.ocr, status: "ran", reason: null, mode: "all", pages: outcome.written, noText: outcome.noText, ocrFailed: outcome.ocrFailed, ocrErrors: outcome.ocrErrors, budgetStopped: outcome.budgetStopped, killed: outcome.killed, notAttempted: outcome.notAttempted, childError: outcome.childError, sidecars: Object.fromEntries(sidecars), wordSidecars: Object.fromEntries(wordSidecars) };
805
+ ocr = { ...emptyOcr(o), ...json.ocr, ocrMaxPages: o.ocrMaxPages, status: "ran", reason: null, mode: "all", pages: outcome.written, noText: outcome.noText, ocrFailed: outcome.ocrFailed, ocrErrors: outcome.ocrErrors, budgetStopped: outcome.budgetStopped, killed: outcome.killed, notAttempted: outcome.notAttempted, childError: outcome.childError, sidecars: Object.fromEntries(sidecars), wordSidecars: Object.fromEntries(wordSidecars) };
796
806
  if (o.words && r.ok) takeWordsErrors(r.json);
797
807
  }
798
808
  if (!isExcel) notes = [...notes, ...(json.notes ?? [])];
@@ -28,6 +28,8 @@ export interface OcrInfo {
28
28
  noText: number[];
29
29
  ocrFailed: number[];
30
30
  budgetStopped: number[];
31
+ ceilingStopped: number[];
32
+ ocrMaxPages: number;
31
33
  reason: string | null;
32
34
  tesseract: boolean | null;
33
35
  mode: OcrMode;
@@ -121,6 +123,13 @@ export function ocrLine(ocr: OcrInfo, type: InputType): string {
121
123
  const r = compactRanges(ocr.budgetStopped, Number.POSITIVE_INFINITY).replaceAll(", ", ",");
122
124
  clauses.push(`time budget reached for pages=${r}; rerun with pages=${r} or raise primaryTimeoutMs`);
123
125
  }
126
+ if (ocr.ceilingStopped.length) {
127
+ const all = compactRanges(ocr.ceilingStopped, Number.POSITIVE_INFINITY).replaceAll(", ", ",");
128
+ const next = compactRanges(ocr.ceilingStopped.slice(0, ocr.ocrMaxPages), Number.POSITIVE_INFINITY).replaceAll(", ", ",");
129
+ clauses.push(type === "docx"
130
+ ? `OCR page ceiling (${ocr.ocrMaxPages}) reached for rendered pages=${all}; export the document to PDF and rerun on it with pages=${next}, or raise quiver.docToMd.ocrMaxPages`
131
+ : `OCR page ceiling (${ocr.ocrMaxPages}) reached for pages=${all}; rerun with pages=${next} or raise quiver.docToMd.ocrMaxPages`);
132
+ }
124
133
  return clauses.join("; ");
125
134
  }
126
135
  }
@@ -21,6 +21,7 @@ export interface Tunables {
21
21
  outlineMaxEntries: number;
22
22
  ocr: boolean;
23
23
  ocrLanguage: string;
24
+ ocrMaxPages: number;
24
25
  hideAnnotations: boolean;
25
26
  }
26
27
 
@@ -56,6 +57,7 @@ export interface OptionDescriptor {
56
57
  default: string | number | boolean | null;
57
58
  settable: boolean;
58
59
  env?: string;
60
+ settingsOnly?: boolean;
59
61
  enumValues?: readonly string[];
60
62
  help: string;
61
63
  }
@@ -88,6 +90,7 @@ export const DOC_TO_MD_OPTIONS: readonly OptionDescriptor[] = [
88
90
  { key: "outlineMaxEntries", flag: "--outline-max-entries", type: "int", default: 40, settable: true, help: "Heading outline / TOC / sheet inventory cap in the handle" },
89
91
  { key: "ocr", flag: "--ocr", type: "bool", default: false, settable: true, help: "Run OCR on pages without a text layer and on image inputs when Tesseract language data is installed; off by default (--no-ocr turns a settings-level true off)" },
90
92
  { key: "ocrLanguage", flag: "--ocr-language", type: "lang", default: "eng", settable: true, help: "Tesseract language code(s), +-joined, e.g. deu+eng" },
93
+ { key: "ocrMaxPages", flag: null, type: "int", default: 10, settable: true, settingsOnly: true, help: "Most pages one invocation OCRs; ocrMode all rejects a larger distinct-page selection before any work, textless mode OCRs the first ocrMaxPages textless pages and names the rest in the OCR: line" },
91
94
  { key: "hideAnnotations", flag: "--hide-annotations", type: "bool", default: false, settable: true, help: "Render PDF pages without annotations (sticky notes, highlights, stamps - and form-field widgets, so filled form values disappear); default paints them, as PyMuPDF does. Applies to pages/ renders and textless-page renders, not to OCR text or embedded images; also lets an annotated scan be delivered as its embedded image." },
92
95
  ];
93
96
 
@@ -108,7 +111,7 @@ function coerceValue(d: OptionDescriptor, raw: unknown, fromString = false): { o
108
111
  switch (d.type) {
109
112
  case "int": {
110
113
  const n = fromString && typeof raw === "string" ? Number(raw) : raw;
111
- return typeof n === "number" && Number.isInteger(n) && n > 0 ? { ok: true, value: n } : { ok: false, reason: "must be a positive integer" };
114
+ return typeof n === "number" && Number.isSafeInteger(n) && n > 0 ? { ok: true, value: n } : { ok: false, reason: "must be a positive integer" };
112
115
  }
113
116
  case "bool": return typeof raw === "boolean" ? { ok: true, value: raw } : { ok: false, reason: "must be true or false" };
114
117
  case "enum": return typeof raw === "string" && d.enumValues!.includes(raw) ? { ok: true, value: raw } : { ok: false, reason: `must be one of ${d.enumValues!.join(", ")}` };
@@ -118,7 +121,7 @@ function coerceValue(d: OptionDescriptor, raw: unknown, fromString = false): { o
118
121
  return { ok: true, value: raw };
119
122
  case "lang": return typeof raw === "string" && OCR_LANGUAGE_RE.test(raw) ? { ok: true, value: raw } : { ok: false, reason: "must be Tesseract language codes joined by + (e.g. eng, deu+eng)" };
120
123
  case "string": return typeof raw === "string" && raw.length > 0 ? { ok: true, value: raw } : { ok: false, reason: "must be a non-empty string" };
121
- case "pages": return typeof raw === "string" ? { ok: true, value: parsePages(raw) } : { ok: false, reason: "must be a string" };
124
+ case "pages": return typeof raw === "string" ? { ok: true, value: pageIntervals(raw) } : { ok: false, reason: "must be a string" };
122
125
  }
123
126
  }
124
127
 
@@ -136,21 +139,43 @@ export function coerceDocToMdSettings(raw: unknown, warn: (message: string) => v
136
139
  return out as Partial<Tunables>;
137
140
  }
138
141
 
139
- export function parsePages(spec: string): number[] | null {
142
+ export type PageInterval = [number, number];
143
+
144
+ export function pageIntervals(spec: string): PageInterval[] | null {
140
145
  if (spec.trim() === "") return null;
141
- const out = new Set<number>();
146
+ const out: PageInterval[] = [];
142
147
  const parts = spec.split(",").map((s) => s.trim());
143
148
  if (parts.length === 0 || parts.some((p) => p === "")) throw new UsageError(`invalid --pages "${spec}": expected e.g. "12-15" or "3,7,10-12"`);
144
149
  for (const p of parts) {
145
150
  const m = p.match(/^(\d+)(?:-(\d+))?$/);
146
151
  if (!m) throw new UsageError(`invalid --pages "${spec}": bad token "${p}"`);
147
152
  const a = Number(m[1]), b = m[2] === undefined ? a : Number(m[2]);
153
+ if (!Number.isSafeInteger(a) || !Number.isSafeInteger(b)) throw new UsageError(`invalid --pages "${spec}": page numbers above ${Number.MAX_SAFE_INTEGER} are not supported`);
148
154
  if (a < 1 || b < a) throw new UsageError(`invalid --pages "${spec}": pages are 1-based and ranges ascend`);
149
- for (let i = a; i <= b; i++) out.add(i);
155
+ out.push([a, b]);
156
+ }
157
+ return out;
158
+ }
159
+
160
+ export function countDistinctPages(intervals: PageInterval[]): number {
161
+ const sorted = [...intervals].sort((x, y) => x[0] - y[0]);
162
+ let total = 0, start = sorted[0][0], end = sorted[0][1];
163
+ for (const [a, b] of sorted.slice(1)) {
164
+ if (a > end + 1) { total += end - start + 1; start = a; end = b; }
165
+ else end = Math.max(end, b);
150
166
  }
167
+ return total + end - start + 1;
168
+ }
169
+
170
+ function expandPages(intervals: PageInterval[]): number[] {
171
+ const out = new Set<number>();
172
+ for (const [a, b] of intervals) for (let i = a; i <= b; i++) out.add(i);
151
173
  return [...out].sort((x, y) => x - y);
152
174
  }
153
175
 
176
+ export const ocrCeilingMessage = (count: number, ceiling: number, spec: string): string =>
177
+ `ocrMode "all" selects ${count} distinct pages (pages=${spec.length > 80 ? `${spec.slice(0, 77)}...` : spec}); the OCR page ceiling is ${ceiling} (quiver.docToMd.ocrMaxPages). Broad OCR is slow and usually unnecessary: convert without OCR first, read Page-Stats to find the pages that need it, and select only those. For more than ${ceiling} pages, run explicit sequential batches within the ceiling and inspect each result before the next. The ceiling is settings-only; no tool or CLI argument raises it.`;
178
+
154
179
  export function sanitizeStem(base: string): string {
155
180
  const s = base.replace(/[^A-Za-z0-9._-]+/g, "_");
156
181
  return s.length ? s : "document";
@@ -165,7 +190,7 @@ export function classifyInput(filePath: string): InputType {
165
190
  return t;
166
191
  }
167
192
 
168
- /** per-call > settings > deprecated env > default. Throws UsageError for bad per-call values or info + bundle option. */
193
+ /** per-call > settings > deprecated env > default. Throws UsageError for bad per-call values, an over-ceiling forced selection, or info + bundle option. */
169
194
  export function resolveOptions(perCall: PerCallInput, settings: Partial<Tunables>, env: NodeJS.ProcessEnv): DocToMdOptions {
170
195
  const out: Record<string, unknown> = { path: perCall.path };
171
196
  for (const d of DOC_TO_MD_OPTIONS) {
@@ -177,7 +202,7 @@ export function resolveOptions(perCall: PerCallInput, settings: Partial<Tunables
177
202
  value = c.value;
178
203
  }
179
204
  if (d.settable && (settings as Record<string, unknown>)[d.key] !== undefined) value = (settings as Record<string, unknown>)[d.key];
180
- const pc = (perCall as unknown as Record<string, unknown>)[d.key];
205
+ const pc = d.settingsOnly ? undefined : (perCall as unknown as Record<string, unknown>)[d.key];
181
206
  if (pc !== undefined && pc !== null) {
182
207
  const c = coerceValue(d, pc);
183
208
  if (!c.ok) throw new UsageError(`${d.flag} ${c.reason}`);
@@ -186,6 +211,12 @@ export function resolveOptions(perCall: PerCallInput, settings: Partial<Tunables
186
211
  out[d.key] = value;
187
212
  }
188
213
  const o = out as unknown as DocToMdOptions;
214
+ const intervals = out.pages as PageInterval[] | null;
215
+ if (intervals && o.ocrMode === "all") {
216
+ const n = countDistinctPages(intervals);
217
+ if (n > o.ocrMaxPages) throw new UsageError(ocrCeilingMessage(n, o.ocrMaxPages, perCall.pages!));
218
+ }
219
+ o.pages = intervals && expandPages(intervals);
189
220
  if (o.info && (o.pages !== null || o.outputDir !== null || o.overwrite || o.pageImages || o.words || o.ocrMode === "all")) {
190
221
  throw new UsageError("--info cannot be combined with --pages, --output-dir, --overwrite, --page-images, --words or --ocr-mode all");
191
222
  }
@@ -207,6 +238,10 @@ export const USAGE_PATTERNS = [
207
238
  " 3. --ocr-mode all refuses to run without --ocr and an explicit --pages.",
208
239
  ' The "ocr" object (OCR: line) names failed, budget-stopped, killed and',
209
240
  " not-attempted pages and the exact --pages to re-run.",
241
+ " 4. OCR is capped at quiver.docToMd.ocrMaxPages pages per call (default 10,",
242
+ " settings-only): --ocr-mode all refuses a larger distinct-page selection",
243
+ " before any work; textless mode OCRs the first ocrMaxPages textless pages",
244
+ " and the OCR: line names the rest with the exact --pages to re-run.",
210
245
  " Details: doc/doc-to-md.md (bundle contract, failure buckets).",
211
246
  ].join("\n");
212
247
 
@@ -228,7 +263,7 @@ export const BUNDLE_LAYOUT: readonly { artifact: string; trigger: string; conten
228
263
  const bundleLayoutText = (): string => BUNDLE_LAYOUT.map((r) => ` ${r.artifact.padEnd(28)} ${r.trigger}; ${r.content}; named by ${r.namedBy}`).join("\n");
229
264
 
230
265
  export function renderHelp(): string {
231
- const row = (d: OptionDescriptor) => ` ${(d.flag ?? "<path>").padEnd(26)} ${d.help}${d.default !== null && d.key !== "info" && d.key !== "overwrite" ? ` (default ${d.default})` : ""}`;
266
+ const row = (d: OptionDescriptor) => ` ${(d.flag ?? (d.settingsOnly ? `quiver.docToMd.${d.key}` : "<path>")).padEnd(26)} ${d.help}${d.settingsOnly ? " (settings-only)" : ""}${d.default !== null && d.key !== "info" && d.key !== "overwrite" ? ` (default ${d.default})` : ""}`;
232
267
  return [
233
268
  "Usage: pi-quiver doc-to-md [flags] <path>",
234
269
  "", "Per-call:", ...DOC_TO_MD_OPTIONS.filter((d) => !d.settable).map(row),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-quiver",
3
- "version": "6.12.0",
3
+ "version": "6.13.1",
4
4
  "description": "Personal pack of Pi coding-agent extensions: context-safe fetch, doc_to_md PDF/DOCX/PPTX-to-Markdown conversion, session naming, a themed ASCII startup header, Opus 4.8 fast mode, and a provider-stall watchdog.",
5
5
  "author": "Jacek Juraszek",
6
6
  "license": "MIT",
@@ -102,7 +102,7 @@ OCR_BUDGET_RESERVE_MS, OCR_EST_INITIAL_MS, PAGE_EST_INITIAL_MS = 5000, 4000, 250
102
102
 
103
103
  def new_ocr(lang):
104
104
  return {"status": "off", "lang": lang, "textless": [], "pages": [], "noText": [], "ocrFailed": [],
105
- "budgetStopped": [], "reason": None, "tesseract": None}
105
+ "budgetStopped": [], "ceilingStopped": [], "reason": None, "tesseract": None}
106
106
 
107
107
 
108
108
  def apply_status(info, st):
@@ -585,7 +585,8 @@ def mode_pdf_primary(o):
585
585
  native_images = []
586
586
  worker = RasterWorker(o["path"], doc)
587
587
  stats = []
588
- lang, budget = o.get("ocrLanguage", "eng"), o.get("ocrBudgetMs", 60000)
588
+ lang, budget, max_pages = o.get("ocrLanguage", "eng"), o.get("ocrBudgetMs", 60000), o.get("ocrMaxPages", 10)
589
+ ocr_count = 0
589
590
  info = new_ocr(lang)
590
591
  status = ocr_status(True, lang) if o.get("ocr") else None
591
592
  ocr_ms, plain_ms = [], []
@@ -604,12 +605,16 @@ def mode_pdf_primary(o):
604
605
  status = ocr_status(False, lang)
605
606
  kw = page_ocr_kwargs(textless, lang) if status and status["status"] == "ready" else {"use_ocr": False}
606
607
  if kw["use_ocr"]:
607
- elapsed = (time.monotonic() - start) * 1000
608
- est_ocr = max(ocr_ms) if ocr_ms else OCR_EST_INITIAL_MS
609
- est_page = sum(plain_ms) / len(plain_ms) if plain_ms else PAGE_EST_INITIAL_MS
610
- if not ocr_admit(elapsed, est_ocr, len(pages) - i - 1, est_page, budget):
611
- info["budgetStopped"].append(n)
608
+ if ocr_count >= max_pages:
609
+ info["ceilingStopped"].append(n)
612
610
  kw = {"use_ocr": False}
611
+ else:
612
+ elapsed = (time.monotonic() - start) * 1000
613
+ est_ocr = max(ocr_ms) if ocr_ms else OCR_EST_INITIAL_MS
614
+ est_page = sum(plain_ms) / len(plain_ms) if plain_ms else PAGE_EST_INITIAL_MS
615
+ if not ocr_admit(elapsed, est_ocr, len(pages) - i - 1, est_page, budget):
616
+ info["budgetStopped"].append(n)
617
+ kw = {"use_ocr": False}
613
618
  text, meta = "", {}
614
619
  ocr_words = None
615
620
  if textless:
@@ -623,6 +628,7 @@ def mode_pdf_primary(o):
623
628
  else:
624
629
  ocr_dpi = clamped_dpi(page.rect.width, page.rect.height, OCR_DPI)
625
630
  words_snapshot = os.path.join(staging, f".ocr-words-p{n}.pdf") if o.get("words") else None
631
+ ocr_count += 1
626
632
  try:
627
633
  r = worker.run({"kind": "ocr", "page": n, "lang": lang, "ocrDpi": ocr_dpi, **({"wordsSnapshot": words_snapshot} if words_snapshot else {})}, min(raster_budget(OCR_JOB_BUDGET_S), remaining)) if ocr_dpi is not None else {"ok": False}
628
634
  if words_snapshot and r["ok"]: