pi-quiver 6.11.0 → 6.13.0
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 +8 -0
- package/README.md +5 -3
- package/dist/bin/pi-quiver.js +48 -13
- package/extensions/doc_to_md.ts +5 -2
- package/lib/doc-to-md-core.ts +6 -6
- package/lib/doc-to-md-handle.ts +9 -0
- package/lib/doc-to-md-options.ts +43 -8
- package/package.json +5 -1
- package/prompts/rebase-worktree.md +11 -0
- package/scripts/doc_to_md.py +13 -7
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.0 - 2026-10-06
|
|
12
|
+
|
|
13
|
+
- `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)
|
|
14
|
+
|
|
15
|
+
## v6.12.0 - 2026-10-06
|
|
16
|
+
|
|
17
|
+
- `/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.
|
|
18
|
+
|
|
11
19
|
## v6.11.0 - 2026-10-02
|
|
12
20
|
|
|
13
21
|
- `doc_to_md`: textless PDF pages holding one eligible full-page image deliver the embedded stream without re-encoding; the handle prints `Native-Images:` and tool details / CLI JSON carry `nativeImages` (#27).
|
package/README.md
CHANGED
|
@@ -71,6 +71,7 @@ A 300 KB changelog page never touches your context window - you get a preview an
|
|
|
71
71
|
| `extensions/fast-mode.ts` | `/fast` | Inject Anthropic fast-mode (`speed: "fast"` + `anthropic-beta: fast-mode-2026-02-01`) into every Claude Opus 4.8 / Opus 5 request, any thinking level. `--fast` flag + `/fast [on\|off\|status]`. OFF by default. |
|
|
72
72
|
| `extensions/provider-stall-watchdog.ts` | - | Opt-in provider-stall recovery, in two tiers: a pre-first-event deadline (`firstEventMs`, 20s) on every provider request in every mode, and the mid-stream pair (warn at 2 min, recover at 4 min) in TUI runs only. Each stall is aborted; while pi's `retry.enabled` is true and the stall retry budget (`maxStallRetries`, default = `retry.maxRetries`) remains, its aborted attempt is hidden from the model and re-driven by the watchdog after pi's backoff; behavior guide: [doc/provider-stall-watchdog.md](doc/provider-stall-watchdog.md). OFF by default. |
|
|
73
73
|
| `extensions/slack.ts` | `slack_search`, `slack_thread`, `slack_post`, `slack_update`, `slack_delete`, `slack_pin`, `slack_upload`, `slack_cache_refresh` | Context-safe Slack search/threads/posting with dual `user`/`bot` token identities, Block Kit flattening and optional raw JSON output for threads, a workspace-keyed channel/user name->ID cache, DM targets by `@name` / user ID, fetch-style output size gating, and a transactional headline+detail-thread announce protocol with a documented recovery path. OFF by default. Behavior lives in `lib/slack-core.ts` and `lib/slack-cache.ts`. |
|
|
74
|
+
| `prompts/rebase-worktree.md` | `/rebase-worktree [base]` | Prompt template, pi only. Rebases the current worktree onto `origin/<base>` (default `main`), resolves conflicts inline with the authorization stated in the prompt, runs only the tests that cover the resolved files, and reports the resolutions and fix commits. Never pushes; it syncs the branch so a later CI run or `/skill:gatekeep-pr` sees current `main`. |
|
|
74
75
|
|
|
75
76
|
Full routing rules, size-gate mechanics, and config: [doc/fetch.md](doc/fetch.md), [doc/doc-to-md.md](doc/doc-to-md.md), [doc/slack.md](doc/slack.md).
|
|
76
77
|
|
|
@@ -310,8 +311,9 @@ Each setting can also be overridden per-process via `PI_QUIVER_SLACK_ENABLED`, `
|
|
|
310
311
|
| `outlineMaxEntries` | `40` | Heading outline, TOC, or sheet inventory entries in the handle. |
|
|
311
312
|
| `ocr` | `false` | Opt-in OCR for scanned pages and images when Tesseract language data is installed. |
|
|
312
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. |
|
|
313
315
|
|
|
314
|
-
`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.
|
|
315
317
|
|
|
316
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.
|
|
317
319
|
|
|
@@ -397,8 +399,8 @@ Published to npm by CI. Pushing a `vX.Y.Z` tag triggers
|
|
|
397
399
|
`npm run test:all`, and publishes with `npm publish --provenance --access
|
|
398
400
|
public` via OIDC trusted publishing. **Never run `npm publish` by hand.**
|
|
399
401
|
|
|
400
|
-
Cut a release with the helper script (also exposed as the
|
|
401
|
-
the `release` skill at `.agents/skills/release/`):
|
|
402
|
+
Cut a release with the helper script (also exposed as the project-local
|
|
403
|
+
`/release` prompt in `.pi/prompts/` + the `release` skill at `.agents/skills/release/`):
|
|
402
404
|
|
|
403
405
|
```bash
|
|
404
406
|
bash .agents/skills/release/scripts/release.sh propose # suggest a level
|
package/dist/bin/pi-quiver.js
CHANGED
|
@@ -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.
|
|
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:
|
|
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
|
|
1105
|
+
function pageIntervals(spec) {
|
|
1100
1106
|
if (spec.trim() === "") return null;
|
|
1101
|
-
const out =
|
|
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
|
-
|
|
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
|
"",
|
|
@@ -1671,7 +1706,7 @@ function reconcileRenderMarkers(md, renderPages, fmt, sourceMap, reason) {
|
|
|
1671
1706
|
if (/<!--rvs?:\d+-->/.test(md)) throw new Error("internal: unresolved render marker");
|
|
1672
1707
|
return md;
|
|
1673
1708
|
}
|
|
1674
|
-
var emptyOcr = (
|
|
1709
|
+
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
1710
|
var emptyOutcome = () => ({ written: [], noText: [], ocrFailed: [], ocrErrors: {}, budgetStopped: [], killed: null, notAttempted: [], childError: null });
|
|
1676
1711
|
var ocrPagesTag = (n) => `p${String(n).padStart(3, "0")}`;
|
|
1677
1712
|
var SIDE_MARKER_RE = /^--- end of page\.page_number=\d+ ---$/;
|
|
@@ -1711,10 +1746,10 @@ function resolveOcrLabels(md, sourceMap) {
|
|
|
1711
1746
|
});
|
|
1712
1747
|
}
|
|
1713
1748
|
function handleOcr(tier, type, o, json) {
|
|
1714
|
-
if (tier === "unpdf") return o.ocr ? { ...emptyOcr(o
|
|
1749
|
+
if (tier === "unpdf") return o.ocr ? { ...emptyOcr(o), status: "unavailable", reason: "no Python backend" } : null;
|
|
1715
1750
|
const x = json.ocr;
|
|
1716
1751
|
if (!x || type !== "image" && !x.textless.length && !x.pages.length && !x.ocrFailed.length) return null;
|
|
1717
|
-
return { ...emptyOcr(o
|
|
1752
|
+
return { ...emptyOcr(o), ...x, ocrMaxPages: o.ocrMaxPages };
|
|
1718
1753
|
}
|
|
1719
1754
|
var nativeFromChild = (b, json, notes) => (json.nativeImages ?? []).flatMap((e) => {
|
|
1720
1755
|
const file = b.sourceMap.get(`p${e.page}/${e.file}`);
|
|
@@ -1758,7 +1793,7 @@ async function convertDocument(o, signal, seams) {
|
|
|
1758
1793
|
let office = null;
|
|
1759
1794
|
try {
|
|
1760
1795
|
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 };
|
|
1796
|
+
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
1797
|
let tier, engine, json, degraded = null, fallbackReason = null;
|
|
1763
1798
|
let explicitBreaks = null;
|
|
1764
1799
|
let notes = [];
|
|
@@ -1815,7 +1850,7 @@ async function convertDocument(o, signal, seams) {
|
|
|
1815
1850
|
tier = "image";
|
|
1816
1851
|
engine = "copy";
|
|
1817
1852
|
json = { markdown: `
|
|
1818
|
-
`, pageCount: 1, notes: [], ocr: { ...emptyOcr(o
|
|
1853
|
+
`, pageCount: 1, notes: [], ocr: { ...emptyOcr(o), status: "unavailable", reason } };
|
|
1819
1854
|
}
|
|
1820
1855
|
}
|
|
1821
1856
|
if (type === "docx" && !lacksDocx(backend)) {
|
|
@@ -1967,7 +2002,7 @@ async function convertDocument(o, signal, seams) {
|
|
|
1967
2002
|
if (r.ok && r.json.status === "unavailable") throw new Error(`OCR unavailable: ${r.json.reason} (install Tesseract; see doc/doc-to-md.md)`);
|
|
1968
2003
|
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
2004
|
const { sidecars, wordSidecars } = publishSidecars(b);
|
|
1970
|
-
ocr = { ...emptyOcr(o
|
|
2005
|
+
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
2006
|
if (o.words && r.ok) takeWordsErrors(r.json);
|
|
1972
2007
|
}
|
|
1973
2008
|
if (!isExcel) notes = [...notes, ...json.notes ?? []];
|
package/extensions/doc_to_md.ts
CHANGED
|
@@ -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)
|
|
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
|
|
package/lib/doc-to-md-core.ts
CHANGED
|
@@ -536,7 +536,7 @@ export function reconcileRenderMarkers(md: string, renderPages: number[], fmt: s
|
|
|
536
536
|
return md;
|
|
537
537
|
}
|
|
538
538
|
|
|
539
|
-
export const emptyOcr = (
|
|
539
|
+
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
540
|
|
|
541
541
|
export interface OcrPagesOutcome { written: number[]; noText: number[]; ocrFailed: number[]; ocrErrors: Record<number, string>; budgetStopped: number[]; killed: number | null; notAttempted: number[]; childError: string | null; }
|
|
542
542
|
const emptyOutcome = (): OcrPagesOutcome => ({ written: [], noText: [], ocrFailed: [], ocrErrors: {}, budgetStopped: [], killed: null, notAttempted: [], childError: null });
|
|
@@ -580,10 +580,10 @@ export function resolveOcrLabels(md: string, sourceMap: Map<string, string>): st
|
|
|
580
580
|
}
|
|
581
581
|
|
|
582
582
|
function handleOcr(tier: Tier, type: InputType, o: DocToMdOptions, json: TierJson): OcrInfo | null {
|
|
583
|
-
if (tier === "unpdf") return o.ocr ? { ...emptyOcr(o
|
|
583
|
+
if (tier === "unpdf") return o.ocr ? { ...emptyOcr(o), status: "unavailable", reason: "no Python backend" } : null;
|
|
584
584
|
const x = json.ocr;
|
|
585
585
|
if (!x || (type !== "image" && !x.textless.length && !x.pages.length && !x.ocrFailed.length)) return null;
|
|
586
|
-
return { ...emptyOcr(o
|
|
586
|
+
return { ...emptyOcr(o), ...x, ocrMaxPages: o.ocrMaxPages };
|
|
587
587
|
}
|
|
588
588
|
|
|
589
589
|
const nativeFromChild = (b: Bundle, json: TierJson, notes: string[]): NativeImage[] => (json.nativeImages ?? []).flatMap((e) => {
|
|
@@ -631,7 +631,7 @@ export async function convertDocument(o: DocToMdOptions, signal?: AbortSignal, s
|
|
|
631
631
|
let office: { pdfPath: string; cleanup: () => void } | null = null;
|
|
632
632
|
try {
|
|
633
633
|
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 };
|
|
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, ocrMaxPages: o.ocrMaxPages, hideAnnotations: o.hideAnnotations };
|
|
635
635
|
let tier: Tier | undefined, engine: Engine | undefined, json: TierJson | undefined, degraded: string | null = null, fallbackReason: string | null = null;
|
|
636
636
|
let explicitBreaks: number | null = null;
|
|
637
637
|
let notes: string[] = [];
|
|
@@ -672,7 +672,7 @@ export async function convertDocument(o: DocToMdOptions, signal?: AbortSignal, s
|
|
|
672
672
|
writeFileSync(join(dir, ".done"), "");
|
|
673
673
|
publishStaged(b);
|
|
674
674
|
tier = "image"; engine = "copy";
|
|
675
|
-
json = { markdown: `\n`, pageCount: 1, notes: [], ocr: { ...emptyOcr(o
|
|
675
|
+
json = { markdown: `\n`, pageCount: 1, notes: [], ocr: { ...emptyOcr(o), status: "unavailable", reason } };
|
|
676
676
|
}
|
|
677
677
|
}
|
|
678
678
|
if (type === "docx" && !lacksDocx(backend)) {
|
|
@@ -792,7 +792,7 @@ export async function convertDocument(o: DocToMdOptions, signal?: AbortSignal, s
|
|
|
792
792
|
const outcome = r.ok && r.json.status === "ran" ? outcomeFromChild(r.json)
|
|
793
793
|
: recoverOcrPages(b.ocrStagingDir, o.pages!, !r.ok ? ("userError" in r ? r.userError : `${r.reason}${detailSuffix(r)}`) : "malformed child output");
|
|
794
794
|
const { sidecars, wordSidecars } = publishSidecars(b);
|
|
795
|
-
ocr = { ...emptyOcr(o
|
|
795
|
+
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
796
|
if (o.words && r.ok) takeWordsErrors(r.json);
|
|
797
797
|
}
|
|
798
798
|
if (!isExcel) notes = [...notes, ...(json.notes ?? [])];
|
package/lib/doc-to-md-handle.ts
CHANGED
|
@@ -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
|
}
|
package/lib/doc-to-md-options.ts
CHANGED
|
@@ -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.
|
|
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:
|
|
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
|
|
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 =
|
|
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
|
-
|
|
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.
|
|
3
|
+
"version": "6.13.0",
|
|
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",
|
|
@@ -34,6 +34,7 @@
|
|
|
34
34
|
},
|
|
35
35
|
"files": [
|
|
36
36
|
"extensions",
|
|
37
|
+
"prompts",
|
|
37
38
|
"lib",
|
|
38
39
|
"dist",
|
|
39
40
|
"scripts/doc_to_md.py",
|
|
@@ -54,6 +55,9 @@
|
|
|
54
55
|
"extensions": [
|
|
55
56
|
"./extensions"
|
|
56
57
|
],
|
|
58
|
+
"prompts": [
|
|
59
|
+
"./prompts/rebase-worktree.md"
|
|
60
|
+
],
|
|
57
61
|
"image": "https://raw.githubusercontent.com/jjuraszek/pi-quiver/main/pi-quiver.png"
|
|
58
62
|
},
|
|
59
63
|
"funding": {
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: Rebase this worktree onto the remote base branch, resolve conflicts, and test only what the resolution touched
|
|
3
|
+
argument-hint: "[base]"
|
|
4
|
+
---
|
|
5
|
+
Rebase this worktree onto `origin/${1:-main}`. This instruction is the authorization to resolve conflicts yourself and to rewrite the branch; do not push.
|
|
6
|
+
|
|
7
|
+
1. Record `git rev-parse HEAD` as the pre-rebase head. A dirty tree (`git status --porcelain` non-empty) stops the run: print the porcelain output and ask whether to commit or stash.
|
|
8
|
+
2. `git fetch origin ${1:-main}` then `git rebase origin/${1:-main}`.
|
|
9
|
+
3. Resolve each conflicted file so both sides' intent survives. A generated file (lockfile, schema dump, changelog section) is regenerated or re-appended on top of the base version, never hand-merged hunk by hunk. Stage it and `git rebase --continue` until the rebase completes.
|
|
10
|
+
4. Run only the tests that cover the files you resolved: the test file that names each resolved source file, else the smallest suite that imports it. Never the full verification command. A failing scoped test is fixed in one new commit on the branch and the test re-run; stop after 3 fix rounds and report the failure verbatim.
|
|
11
|
+
5. Report in one paragraph: the pre-rebase and new head, the conflicted files with one sentence per resolution, the scoped tests that ran with their result, and the fix commits if any.
|
package/scripts/doc_to_md.py
CHANGED
|
@@ -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
|
-
|
|
608
|
-
|
|
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"]:
|