@blackbelt-technology/pi-dashboard-document-converter 0.8.0 → 0.10.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/.pi/skills/doc-summarizer/SKILL.md +6 -2
- package/.pi/skills/document-converter/SKILL.md +13 -4
- package/README.md +28 -5
- package/engine/Dockerfile +37 -10
- package/engine/IMAGE_VERSION +1 -1
- package/engine/README.md +13 -2
- package/engine/VENDOR.md +13 -1
- package/engine/build-image.sh +11 -4
- package/engine/engine_cli.py +64 -12
- package/package.json +8 -2
- package/src/engine.ts +156 -16
- package/src/errors.ts +2 -0
- package/src/index.ts +16 -12
- package/src/schema.ts +1 -1
|
@@ -24,7 +24,11 @@ Call the facade; never invoke Python, docling, or pdftotext directly.
|
|
|
24
24
|
|
|
25
25
|
```ts
|
|
26
26
|
import { createDocumentConverter } from "@blackbelt-technology/pi-dashboard-document-converter";
|
|
27
|
-
const dc = createDocumentConverter({
|
|
27
|
+
const dc = createDocumentConverter({
|
|
28
|
+
image: "pi-doc-engine:0.2.0",
|
|
29
|
+
stagingDir: "/abs/staging",
|
|
30
|
+
mounts: ["/docs"], // files outside cwd need a root (mounts or workspaceRoot), else PATH_NOT_ALLOWED
|
|
31
|
+
});
|
|
28
32
|
|
|
29
33
|
const { output } = await dc.convertToMarkdown("<file_path>"); // digital PDF/DOCX/…
|
|
30
34
|
// scanned PDF: pass OCR explicitly
|
|
@@ -33,7 +37,7 @@ await dc.convertToMarkdown("<file_path>", { ocr: { mode: "force", lang: ["englis
|
|
|
33
37
|
|
|
34
38
|
The result is a provenance-stamped `.md` in `stagingDir`. Read that file to get
|
|
35
39
|
the document text. On failure the call rejects with `DocConverterError`
|
|
36
|
-
(`.code`, `.stderr`) — surface `UNSUPPORTED_FORMAT`, `OCR_LANG_UNSUPPORTED`,
|
|
40
|
+
(`.code`, `.stderr`) — surface `UNSUPPORTED_FORMAT`, `PATH_NOT_ALLOWED`, `OCR_LANG_UNSUPPORTED`,
|
|
37
41
|
`INGEST_FAILED`, `DOCKER_UNAVAILABLE` rather than retrying blindly.
|
|
38
42
|
|
|
39
43
|
## Step 2 — Decide direct vs. chunked
|
|
@@ -17,8 +17,13 @@ Do NOT read the vendored Python under `engine/document_converter/`.
|
|
|
17
17
|
## Prerequisites
|
|
18
18
|
|
|
19
19
|
- Docker available; image built: `cd packages/document-converter && npm run build:image`.
|
|
20
|
+
The `pi.tools` manifest (package root) declares `pi-doc-engine` as a
|
|
21
|
+
`docker-image` probe — `pi-dashboard-ensure <package-root>/package.json`
|
|
22
|
+
reports image presence and the first-party build hint (confirm-gated) via
|
|
23
|
+
the registry's Settings → Tools row.
|
|
20
24
|
- Styled diagrams (nano-banana) need `GEMINI_API_KEY` at run time; absent or on
|
|
21
|
-
failure, rendering falls back to mmdc
|
|
25
|
+
failure, rendering falls back to mmdc; if the headless browser cannot launch
|
|
26
|
+
(e.g. wrong architecture) the call fails with `MMDC_UNAVAILABLE`.
|
|
22
27
|
|
|
23
28
|
## Two directions
|
|
24
29
|
|
|
@@ -26,7 +31,11 @@ Do NOT read the vendored Python under `engine/document_converter/`.
|
|
|
26
31
|
|
|
27
32
|
```ts
|
|
28
33
|
import { createDocumentConverter } from "@blackbelt-technology/pi-dashboard-document-converter";
|
|
29
|
-
const dc = createDocumentConverter({
|
|
34
|
+
const dc = createDocumentConverter({
|
|
35
|
+
image: "pi-doc-engine:0.2.0",
|
|
36
|
+
stagingDir: "/abs/kb-staging",
|
|
37
|
+
mounts: ["/docs"], // files outside cwd need a root (mounts or workspaceRoot), else PATH_NOT_ALLOWED
|
|
38
|
+
});
|
|
30
39
|
|
|
31
40
|
await dc.convertToMarkdown("/docs/report.pdf"); // digital PDF (auto: native-first)
|
|
32
41
|
await dc.convertToMarkdown("/docs/scan.pdf", { // scanned HU PDF
|
|
@@ -75,5 +84,5 @@ All stages read/write one unified schema (`./schema`): template vars ·
|
|
|
75
84
|
## Errors
|
|
76
85
|
|
|
77
86
|
Every method rejects with `DocConverterError` (`.code`, `.stderr`, `.exitCode`):
|
|
78
|
-
`UNSUPPORTED_FORMAT`, `OCR_LANG_UNSUPPORTED`, `INGEST_FAILED`, `PRODUCE_FAILED`,
|
|
79
|
-
`DOCKER_UNAVAILABLE`, … Surface `.code` + `.stderr`; do not retry blindly.
|
|
87
|
+
`UNSUPPORTED_FORMAT`, `PATH_NOT_ALLOWED`, `OCR_LANG_UNSUPPORTED`, `INGEST_FAILED`, `PRODUCE_FAILED`,
|
|
88
|
+
`MMDC_UNAVAILABLE` (mermaid browser cannot launch — rebuild the image on this architecture), `DOCKER_UNAVAILABLE`, … Surface `.code` + `.stderr`; do not retry blindly.
|
package/README.md
CHANGED
|
@@ -14,8 +14,10 @@ touch Python, docling, pandoc, or the nano-banana CLI.
|
|
|
14
14
|
import { createDocumentConverter } from "@blackbelt-technology/pi-dashboard-document-converter";
|
|
15
15
|
|
|
16
16
|
const dc = createDocumentConverter({
|
|
17
|
-
image: "pi-doc-engine:0.
|
|
17
|
+
image: "pi-doc-engine:0.2.0",
|
|
18
18
|
stagingDir: "/abs/kb-staging",
|
|
19
|
+
// Files outside process.cwd() must sit under a configured root:
|
|
20
|
+
mounts: ["/docs", "/out"], // or workspaceRoot: "/abs/project"
|
|
19
21
|
});
|
|
20
22
|
|
|
21
23
|
// Ingest -> Markdown with provenance frontmatter (written into stagingDir).
|
|
@@ -68,10 +70,23 @@ The `provenance` frontmatter (`source_path`, `sha256`, `doc_type`,
|
|
|
68
70
|
originating file. Re-ingesting an unchanged file yields the same `sha256`, so
|
|
69
71
|
staging output is byte-stable (idempotent by hash).
|
|
70
72
|
|
|
73
|
+
## Path confinement
|
|
74
|
+
|
|
75
|
+
Every absolute path in a request must lie under a configured root:
|
|
76
|
+
`stagingDir` (mounted read-write), `mounts`, or `workspaceRoot` (default
|
|
77
|
+
`process.cwd()`). Comparison uses real paths, so a symlink cannot escape a root.
|
|
78
|
+
Sensitive dirs (`/etc`, `/root`, `/var/run`, `/proc`, `/sys`, `/dev`, `~/.ssh`,
|
|
79
|
+
`~/.aws`, `~/.gnupg`, `~/.config`, `~/.pi`, `~/.docker`, `~/.kube`) are refused
|
|
80
|
+
unless a root containing the path is itself inside that dir. A root of `/` is
|
|
81
|
+
refused. Violations reject with `DocConverterError` code `PATH_NOT_ALLOWED`
|
|
82
|
+
before docker runs. Inputs of `convertToMarkdown`, `renderPdf`, and
|
|
83
|
+
`fillFrontmatter`/`profileTables` with `apply:false` mount read-only.
|
|
84
|
+
|
|
71
85
|
## Templates (runtime-mounted, not baked)
|
|
72
86
|
|
|
73
87
|
DOCX templates are NOT baked into the image — pass `templatesDir` (an absolute
|
|
74
|
-
host dir containing `<template>/template.docx
|
|
88
|
+
host dir containing `<template>/template.docx`, under a configured root — add it
|
|
89
|
+
to `mounts`); the facade bind-mounts it. Keeps
|
|
75
90
|
branded/template assets out of the image and the repo.
|
|
76
91
|
|
|
77
92
|
## Engine image
|
|
@@ -82,17 +97,25 @@ Built from `engine/` (vendored Python; see `engine/VENDOR.md`):
|
|
|
82
97
|
npm run build:image # -> pi-doc-engine:$(cat engine/IMAGE_VERSION)
|
|
83
98
|
```
|
|
84
99
|
|
|
85
|
-
Heavy (docling ML models + LibreOffice + pandoc + chrome-headless-shell). The
|
|
100
|
+
Heavy (docling ML models + LibreOffice + pandoc + arch-selected headless browser: chrome-headless-shell on amd64, chromium on arm64). The
|
|
86
101
|
image runs as root, so an `mmdc` shim injects `--no-sandbox`; opencv needs
|
|
87
102
|
`libgl1`; `@puppeteer/browsers` needs `unzip` (all handled in the Dockerfile).
|
|
88
103
|
See `engine/README.md` for the JSON `docker run` contract.
|
|
89
104
|
|
|
105
|
+
## Breaking (next release)
|
|
106
|
+
|
|
107
|
+
`DocConverterErrorCode` gains `MMDC_UNAVAILABLE` (exhaustive `switch`es must add a case).
|
|
108
|
+
It is raised when a mermaid render was attempted and the engine's headless browser cannot
|
|
109
|
+
launch. The earlier no-hard-fail guarantee for styled rendering is withdrawn: nano-banana
|
|
110
|
+
failure falls back to mmdc, and a broken browser now fails the produce call with `MMDC_UNAVAILABLE`.
|
|
111
|
+
Rebuild the image (`pi-doc-engine:0.2.0`) to pick up the arch-selected browser.
|
|
112
|
+
|
|
90
113
|
## Integration test (opt-in)
|
|
91
114
|
|
|
92
|
-
|
|
115
|
+
Build the image (`pi-doc-engine:0.2.0`), then:
|
|
93
116
|
|
|
94
117
|
```bash
|
|
95
|
-
DOC_ENGINE_IMAGE=pi-doc-engine:0.
|
|
118
|
+
DOC_ENGINE_IMAGE=pi-doc-engine:0.2.0 \
|
|
96
119
|
DOC_ENGINE_PDF=/abs/sample.pdf \
|
|
97
120
|
DOC_ENGINE_TEMPLATES=/abs/templates \
|
|
98
121
|
npx vitest run integration
|
package/engine/Dockerfile
CHANGED
|
@@ -10,15 +10,16 @@
|
|
|
10
10
|
# docker build -t pi-doc-engine:<tag> packages/document-converter/engine
|
|
11
11
|
#
|
|
12
12
|
# Bundles: docling (+ EasyOCR/Tesseract/RapidOCR), python-docx/pptx, openpyxl,
|
|
13
|
-
# pandoc, LibreOffice (PDF), @mermaid-js/mermaid-cli (mmdc) +
|
|
13
|
+
# pandoc, LibreOffice (PDF), @mermaid-js/mermaid-cli (mmdc) + an arch-selected
|
|
14
|
+
# headless browser (chrome-headless-shell on amd64, distro chromium on arm64),
|
|
14
15
|
# @the-focus-ai/nano-banana, frontmatter_filler, markdown_table_profiler.
|
|
15
16
|
|
|
16
|
-
FROM python:3.12-slim AS base
|
|
17
|
+
FROM python:3.12-slim-trixie AS base
|
|
17
18
|
|
|
18
19
|
ENV DEBIAN_FRONTEND=noninteractive \
|
|
19
20
|
PYTHONUNBUFFERED=1 \
|
|
20
21
|
PIP_NO_CACHE_DIR=1 \
|
|
21
|
-
# mmdc/puppeteer use the
|
|
22
|
+
# mmdc/puppeteer use the browser provisioned below; never host Chrome.
|
|
22
23
|
PUPPETEER_EXECUTABLE_PATH=/opt/chrome-headless-shell/chrome-headless-shell \
|
|
23
24
|
PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=1
|
|
24
25
|
|
|
@@ -36,12 +37,28 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
|
36
37
|
&& apt-get install -y --no-install-recommends nodejs \
|
|
37
38
|
&& rm -rf /var/lib/apt/lists/*
|
|
38
39
|
|
|
39
|
-
# --- Node CLIs
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
40
|
+
# --- Node CLIs + arch-selected headless browser ---
|
|
41
|
+
# amd64: pinned chrome-headless-shell (Chrome for Testing publishes no linux-arm64
|
|
42
|
+
# build, so an unconditional install runs under qemu on arm64 and cannot exec).
|
|
43
|
+
# arm64: distro chromium, symlinked to the path PUPPETEER_EXECUTABLE_PATH expects.
|
|
44
|
+
RUN set -eu; \
|
|
45
|
+
case "$(dpkg --print-architecture)" in \
|
|
46
|
+
amd64) \
|
|
47
|
+
npx --yes @puppeteer/browsers install chrome-headless-shell@155.0.8059.84 \
|
|
48
|
+
--path /opt/chrome-headless-shell-dl; \
|
|
49
|
+
ln -s "$(find /opt/chrome-headless-shell-dl -name chrome-headless-shell -type f | head -1 | xargs dirname)" \
|
|
50
|
+
/opt/chrome-headless-shell ;; \
|
|
51
|
+
arm64) \
|
|
52
|
+
apt-get update; \
|
|
53
|
+
apt-get install -y --no-install-recommends chromium; \
|
|
54
|
+
rm -rf /var/lib/apt/lists/*; \
|
|
55
|
+
[ -x /usr/bin/chromium ] || { echo "chromium not executable at /usr/bin/chromium" >&2; exit 1; }; \
|
|
56
|
+
mkdir -p /opt/chrome-headless-shell; \
|
|
57
|
+
ln -s /usr/bin/chromium /opt/chrome-headless-shell/chrome-headless-shell ;; \
|
|
58
|
+
*) \
|
|
59
|
+
echo "unsupported build architecture: $(dpkg --print-architecture)" >&2; exit 1 ;; \
|
|
60
|
+
esac; \
|
|
61
|
+
npm install -g @mermaid-js/mermaid-cli@11.17.0 @the-focus-ai/nano-banana
|
|
45
62
|
|
|
46
63
|
# --- Python engine deps (docling pulls OCR/ML model libs) ---
|
|
47
64
|
# CPU-only torch FIRST: the default torch wheel bundles ~3.4GB of CUDA/triton
|
|
@@ -61,7 +78,7 @@ RUN pip install --index-url https://download.pytorch.org/whl/cpu torch torchvisi
|
|
|
61
78
|
# (/usr/local/bin precedes /usr/bin) injects `-p` without editing vendored code.
|
|
62
79
|
RUN printf '{"executablePath":"%s","args":["--no-sandbox","--disable-gpu","--disable-dev-shm-usage"]}\n' \
|
|
63
80
|
"$PUPPETEER_EXECUTABLE_PATH" > /opt/puppeteer.json \
|
|
64
|
-
&& printf '#!/bin/sh\nexec node /usr/lib/node_modules/@mermaid-js/mermaid-cli/src/cli.js -p /opt/puppeteer.json "$@"\n' \
|
|
81
|
+
&& printf '#!/bin/sh\n[ -z "$PI_DOC_MMDC_MARKER" ] || : > "$PI_DOC_MMDC_MARKER"\nexec node /usr/lib/node_modules/@mermaid-js/mermaid-cli/src/cli.js -p /opt/puppeteer.json "$@"\n' \
|
|
65
82
|
> /usr/local/bin/mmdc \
|
|
66
83
|
&& chmod +x /usr/local/bin/mmdc
|
|
67
84
|
|
|
@@ -69,6 +86,16 @@ RUN printf '{"executablePath":"%s","args":["--no-sandbox","--disable-gpu","--dis
|
|
|
69
86
|
WORKDIR /engine
|
|
70
87
|
COPY . /engine/
|
|
71
88
|
|
|
89
|
+
# Build-time smoke: render a two-node diagram through the engine's own default
|
|
90
|
+
# path (SVG -b transparent + PNG -b transparent -w 1200 -s 2) and through the
|
|
91
|
+
# fallback argv (-b white -w 1400 -s 2). Fails the build if the browser cannot
|
|
92
|
+
# launch on this architecture, instead of failing at a user's produce call.
|
|
93
|
+
RUN python -c "from pathlib import Path; from document_converter.mermaid_renderer import render_diagram; d='graph TD; A-->B'; p=Path('/tmp/smoke.png'); render_diagram(d, p, extract_dimensions=True, format='png'); assert p.exists()" \
|
|
94
|
+
&& printf 'graph TD; A-->B\n' > /tmp/smoke.mmd \
|
|
95
|
+
&& mmdc -i /tmp/smoke.mmd -o /tmp/smoke2.png -b white -w 1400 -s 2 \
|
|
96
|
+
&& test -s /tmp/smoke2.png \
|
|
97
|
+
&& rm -f /tmp/smoke*
|
|
98
|
+
|
|
72
99
|
# Pre-warm docling model artifacts so first run does not download at runtime.
|
|
73
100
|
# (Best-effort: skip silently if offline at build time.)
|
|
74
101
|
RUN python -c "from docling.utils.model_downloader import download_models; download_models()" || true
|
package/engine/IMAGE_VERSION
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
0.
|
|
1
|
+
0.2.0
|
package/engine/README.md
CHANGED
|
@@ -22,13 +22,24 @@ signals success.
|
|
|
22
22
|
docker run --rm -i \
|
|
23
23
|
-v "$WORKDIR:$WORKDIR" -w "$WORKDIR" \
|
|
24
24
|
-e GEMINI_API_KEY \
|
|
25
|
-
pi-doc-engine:0.
|
|
25
|
+
pi-doc-engine:0.2.0 < request.json > response.json
|
|
26
26
|
```
|
|
27
27
|
|
|
28
28
|
- All paths in the request/response are **container paths**. The facade bind-mounts
|
|
29
29
|
a work dir and rewrites host→container paths before calling.
|
|
30
30
|
- `GEMINI_API_KEY` is injected at `docker run` time only (never baked). Absent →
|
|
31
|
-
styled diagrams fall back to mmdc
|
|
31
|
+
styled diagrams fall back to mmdc; if the browser cannot launch, produce fails with `MMDC_UNAVAILABLE`.
|
|
32
|
+
|
|
33
|
+
### Browser (mermaid)
|
|
34
|
+
|
|
35
|
+
The headless browser is selected per build architecture: pinned
|
|
36
|
+
`chrome-headless-shell` on amd64, distro `chromium` on arm64 (symlinked to
|
|
37
|
+
`/opt/chrome-headless-shell/chrome-headless-shell`). Any other architecture
|
|
38
|
+
fails the build. Diagram raster output may differ slightly between arches. A
|
|
39
|
+
build-time smoke render fails the build if the browser cannot launch.
|
|
40
|
+
|
|
41
|
+
Upgrading from 0.1.0: rebuild (`build-image.sh` also tags `pi-doc-engine:latest`,
|
|
42
|
+
the server's default image name) or set `PI_DOC_ENGINE_IMAGE=pi-doc-engine:0.2.0`.
|
|
32
43
|
|
|
33
44
|
### Request
|
|
34
45
|
|
package/engine/VENDOR.md
CHANGED
|
@@ -25,7 +25,11 @@ anchor-file sha256 + copy date establish traceability.
|
|
|
25
25
|
- `markdown_table_profiler/profile.py` (PEP 723 inline): none
|
|
26
26
|
- Ingest engine: `docling` (+ OCR engines), installed via pip in the Dockerfile
|
|
27
27
|
- System tooling: `pandoc`, Gotenberg, `@mermaid-js/mermaid-cli` (mmdc),
|
|
28
|
-
|
|
28
|
+
`@the-focus-ai/nano-banana`
|
|
29
|
+
- Headless browser, arch-selected in the Dockerfile (verified 2026-10-17; 12.x dropped `-w`/`-s` that the vendored renderer passes, so stay on 11.x; base
|
|
30
|
+
`python:3.12-slim-trixie`, `@mermaid-js/mermaid-cli@11.17.0`):
|
|
31
|
+
- amd64: `chrome-headless-shell@155.0.8059.84` (Chrome for Testing, pinned build id)
|
|
32
|
+
- arm64: Debian trixie `chromium` 155.0.8059.79 (Chrome major 155 on both arches)
|
|
29
33
|
|
|
30
34
|
## Excluded from vendoring
|
|
31
35
|
|
|
@@ -38,3 +42,11 @@ anchor-file sha256 + copy date establish traceability.
|
|
|
38
42
|
reads one JSON request on stdin, dispatches to the vendored modules + docling,
|
|
39
43
|
writes one JSON response on stdout, and maps failures to non-zero exit codes.
|
|
40
44
|
See `engine/engine_cli.py` for the contract.
|
|
45
|
+
|
|
46
|
+
## Verification record (fix-doc-engine-arm64-chromium, 2026-10-17)
|
|
47
|
+
|
|
48
|
+
- `python:3.12-slim` resolves to Debian trixie on amd64 and arm64 → base pinned `-trixie`.
|
|
49
|
+
- arm64: `apt-cache policy chromium` candidate `155.0.8059.79-1~deb13u1` (main).
|
|
50
|
+
- amd64 pin: `chrome-headless-shell@155.0.8059.84` (CfT Stable at verification time).
|
|
51
|
+
- `@mermaid-js/mermaid-cli` 12.0.0 rejects `-w`/`-s` (vendored renderer passes them) → pinned 11.17.0.
|
|
52
|
+
- arm64 image built natively, smoke render green; `renderDocx` of a mermaid doc yields `word/media/*.png`.
|
package/engine/build-image.sh
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env bash
|
|
2
2
|
# Build the pi-doc-engine image from the in-repo vendored engine copy.
|
|
3
3
|
#
|
|
4
|
-
# ./build-image.sh # build pi-doc-engine:<IMAGE_VERSION>
|
|
5
|
-
# IMAGE_TAG=pi-doc-engine:dev ./build-image.sh
|
|
4
|
+
# ./build-image.sh # build pi-doc-engine:<IMAGE_VERSION> + pi-doc-engine:latest
|
|
5
|
+
# IMAGE_TAG=pi-doc-engine:dev ./build-image.sh # only that tag (no :latest)
|
|
6
6
|
#
|
|
7
7
|
# The build context is THIS directory only — the image must reference no
|
|
8
8
|
# home-directory path. A guard below fails the build if a ~/Documents reference
|
|
@@ -11,7 +11,14 @@ set -euo pipefail
|
|
|
11
11
|
|
|
12
12
|
ENGINE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
13
13
|
IMAGE_VERSION="$(cat "$ENGINE_DIR/IMAGE_VERSION")"
|
|
14
|
-
|
|
14
|
+
# `:latest` is added only for the default tag, so the server's untagged default
|
|
15
|
+
# image name (office-preview.ts) resolves to the freshly built image. Any
|
|
16
|
+
# non-empty IMAGE_TAG builds exactly that tag.
|
|
17
|
+
TAGS=()
|
|
18
|
+
if [ -z "${IMAGE_TAG:-}" ]; then
|
|
19
|
+
IMAGE_TAG="pi-doc-engine:${IMAGE_VERSION}"
|
|
20
|
+
TAGS=(-t "pi-doc-engine:latest")
|
|
21
|
+
fi
|
|
15
22
|
|
|
16
23
|
# --- Guard: no home-dir / ~/Documents path may leak into the runtime Python ---
|
|
17
24
|
# Scoped to *.py runtime source (the only code that ships); meta files (this
|
|
@@ -25,5 +32,5 @@ if grep -RInE "$GUARD_PAT" "$ENGINE_DIR" --include='*.py' \
|
|
|
25
32
|
fi
|
|
26
33
|
|
|
27
34
|
echo "Building ${IMAGE_TAG} from ${ENGINE_DIR} ..."
|
|
28
|
-
docker build -t "${IMAGE_TAG}" "${ENGINE_DIR}"
|
|
35
|
+
docker build -t "${IMAGE_TAG}" ${TAGS[@]+"${TAGS[@]}"} "${ENGINE_DIR}"
|
|
29
36
|
echo "Built ${IMAGE_TAG}"
|
package/engine/engine_cli.py
CHANGED
|
@@ -24,9 +24,11 @@ from __future__ import annotations
|
|
|
24
24
|
import hashlib
|
|
25
25
|
import json
|
|
26
26
|
import os
|
|
27
|
+
import platform
|
|
27
28
|
import re
|
|
28
29
|
import subprocess
|
|
29
30
|
import sys
|
|
31
|
+
import tempfile
|
|
30
32
|
import traceback
|
|
31
33
|
from datetime import datetime, timezone
|
|
32
34
|
from pathlib import Path
|
|
@@ -145,7 +147,8 @@ _MERMAID_BLOCK = re.compile(r"```mermaid\n(.*?)\n```", re.DOTALL)
|
|
|
145
147
|
|
|
146
148
|
def _render_styled_diagrams(md_path: Path, style: str, cache_dir: Path) -> Path:
|
|
147
149
|
"""Replace each ```mermaid block with a cached <md5>.png, generating misses
|
|
148
|
-
via nano-banana CLI; fall back to mmdc per-diagram on any failure
|
|
150
|
+
via nano-banana CLI; fall back to mmdc per-diagram on any failure (a broken
|
|
151
|
+
browser raises MMDC_UNAVAILABLE instead). Returns a
|
|
149
152
|
rewritten temp .md placed IN THE SAME DIR so relative image paths resolve."""
|
|
150
153
|
text = md_path.read_text(encoding="utf-8")
|
|
151
154
|
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
@@ -201,19 +204,53 @@ def _nano_banana(source: str, style: str, png: Path) -> bool:
|
|
|
201
204
|
return False
|
|
202
205
|
|
|
203
206
|
|
|
207
|
+
_DEFAULT_BROWSER = "/opt/chrome-headless-shell/chrome-headless-shell"
|
|
208
|
+
_PROBE_FLAGS = ["--headless", "--no-sandbox", "--disable-gpu", "--disable-dev-shm-usage", "--dump-dom", "about:blank"]
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _browser_path() -> str:
|
|
212
|
+
return os.environ.get("PUPPETEER_EXECUTABLE_PATH") or _DEFAULT_BROWSER
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def browser_launch_probe() -> bool:
|
|
216
|
+
"""Real headless launch with the flags /opt/puppeteer.json passes.
|
|
217
|
+
|
|
218
|
+
True when the browser starts and dumps a DOM; False on exec failure (arch
|
|
219
|
+
mismatch, missing file), non-zero exit, timeout, or no ``<html`` output.
|
|
220
|
+
Never raises. See change: fix-doc-engine-arm64-chromium (D6).
|
|
221
|
+
"""
|
|
222
|
+
try:
|
|
223
|
+
proc = subprocess.run(
|
|
224
|
+
[_browser_path(), *_PROBE_FLAGS],
|
|
225
|
+
capture_output=True,
|
|
226
|
+
text=True,
|
|
227
|
+
timeout=10,
|
|
228
|
+
)
|
|
229
|
+
except Exception: # noqa: BLE001 - OSError, TimeoutExpired, ...
|
|
230
|
+
return False
|
|
231
|
+
return proc.returncode == 0 and "<html" in (proc.stdout or "")
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _unavailable(stderr: str) -> EngineError:
|
|
235
|
+
return EngineError(
|
|
236
|
+
"MMDC_UNAVAILABLE",
|
|
237
|
+
f"browser could not launch: {_browser_path()} (machine {platform.machine()})",
|
|
238
|
+
stderr,
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
|
|
204
242
|
def _mmdc(source: str, png: Path) -> None:
|
|
205
243
|
blk = png.with_suffix(".mmd")
|
|
206
244
|
blk.write_text(source, encoding="utf-8")
|
|
207
|
-
env = dict(os.environ)
|
|
208
|
-
# Use the baked headless shell; never the host Chrome.
|
|
209
|
-
shell = os.environ.get("PUPPETEER_EXECUTABLE_PATH")
|
|
210
245
|
proc = subprocess.run(
|
|
211
246
|
["mmdc", "-i", str(blk), "-o", str(png), "-b", "white", "-w", "1400", "-s", "2"],
|
|
212
247
|
capture_output=True,
|
|
213
248
|
text=True,
|
|
214
|
-
env=
|
|
249
|
+
env=dict(os.environ),
|
|
215
250
|
)
|
|
216
251
|
if proc.returncode != 0 or not png.exists():
|
|
252
|
+
if not browser_launch_probe():
|
|
253
|
+
raise _unavailable(proc.stderr)
|
|
217
254
|
raise EngineError("MMDC_FAILED", "mermaid render failed", proc.stderr)
|
|
218
255
|
|
|
219
256
|
|
|
@@ -222,12 +259,27 @@ def _mmdc(source: str, png: Path) -> None:
|
|
|
222
259
|
# ---------------------------------------------------------------------------
|
|
223
260
|
|
|
224
261
|
|
|
225
|
-
def _run_dc(args: list[str]) -> subprocess.CompletedProcess:
|
|
262
|
+
def _run_dc(args: list[str], classify_mmdc: bool = False) -> subprocess.CompletedProcess:
|
|
263
|
+
"""Run document_converter. With ``classify_mmdc`` a failure is probed for a
|
|
264
|
+
broken browser, but only when the mmdc shim touched the render-attempt marker."""
|
|
226
265
|
cmd = [sys.executable, "-m", "document_converter.cli", *args]
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
266
|
+
marker: str | None = None
|
|
267
|
+
kwargs: dict = {}
|
|
268
|
+
if classify_mmdc:
|
|
269
|
+
fd, marker = tempfile.mkstemp(prefix="mmdc-marker-")
|
|
270
|
+
os.close(fd)
|
|
271
|
+
os.unlink(marker) # the shim creates it only when mmdc runs
|
|
272
|
+
kwargs["env"] = {**os.environ, "PI_DOC_MMDC_MARKER": marker}
|
|
273
|
+
try:
|
|
274
|
+
proc = subprocess.run(cmd, capture_output=True, text=True, cwd=str(ENGINE_DIR), **kwargs)
|
|
275
|
+
if proc.returncode != 0:
|
|
276
|
+
if marker and os.path.exists(marker) and not browser_launch_probe():
|
|
277
|
+
raise _unavailable(proc.stderr)
|
|
278
|
+
raise EngineError("PRODUCE_FAILED", f"document_converter exited {proc.returncode}", proc.stderr, proc.returncode)
|
|
279
|
+
return proc
|
|
280
|
+
finally:
|
|
281
|
+
if marker and os.path.exists(marker):
|
|
282
|
+
os.unlink(marker)
|
|
231
283
|
|
|
232
284
|
|
|
233
285
|
def cmd_render_docx(req: dict) -> dict:
|
|
@@ -249,7 +301,7 @@ def cmd_render_docx(req: dict) -> dict:
|
|
|
249
301
|
if req.get("noToc"):
|
|
250
302
|
args += ["--no-update-fields"]
|
|
251
303
|
args += ["--non-interactive"]
|
|
252
|
-
_run_dc(args)
|
|
304
|
+
_run_dc(args, classify_mmdc=True)
|
|
253
305
|
return _ok(output=out)
|
|
254
306
|
|
|
255
307
|
|
|
@@ -263,7 +315,7 @@ def cmd_render_pdf(req: dict) -> dict:
|
|
|
263
315
|
args += ["--page-size", req["pageSize"]]
|
|
264
316
|
if req.get("template"):
|
|
265
317
|
args += ["--template", req["template"]]
|
|
266
|
-
_run_dc(args)
|
|
318
|
+
_run_dc(args, classify_mmdc=True)
|
|
267
319
|
return _ok(output=out)
|
|
268
320
|
|
|
269
321
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blackbelt-technology/pi-dashboard-document-converter",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "TypeScript facade over a Dockerized Python document engine (pi-doc-engine). Bidirectional: ingest any format to provenance-stamped Markdown for kb, produce templated DOCX/PDF with diagrams. Engine quarantined in Docker; TS is the only call surface.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -16,6 +16,12 @@
|
|
|
16
16
|
"skills": [
|
|
17
17
|
".pi/skills/document-converter",
|
|
18
18
|
".pi/skills/doc-summarizer"
|
|
19
|
+
],
|
|
20
|
+
"tools": [
|
|
21
|
+
{
|
|
22
|
+
"id": "pi-doc-engine",
|
|
23
|
+
"probe": "docker-image"
|
|
24
|
+
}
|
|
19
25
|
]
|
|
20
26
|
},
|
|
21
27
|
"exports": {
|
|
@@ -30,7 +36,7 @@
|
|
|
30
36
|
"test": "vitest run"
|
|
31
37
|
},
|
|
32
38
|
"dependencies": {
|
|
33
|
-
"@blackbelt-technology/pi-dashboard-shared": "^0.
|
|
39
|
+
"@blackbelt-technology/pi-dashboard-shared": "^0.10.0"
|
|
34
40
|
},
|
|
35
41
|
"files": [
|
|
36
42
|
"dist",
|
package/src/engine.ts
CHANGED
|
@@ -3,14 +3,22 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Spawns `docker run -i pi-doc-engine`, pipes one JSON request to stdin, reads
|
|
5
5
|
* one JSON response from stdout, and maps exit codes + the response envelope to
|
|
6
|
-
* typed errors.
|
|
7
|
-
* paths equal
|
|
6
|
+
* typed errors. Mount *targets* keep the lexical request path so container
|
|
7
|
+
* paths equal request paths — no path rewriting needed; mount *sources* are the
|
|
8
|
+
* realpath'd host dir that is actually exposed.
|
|
9
|
+
*
|
|
10
|
+
* Confinement (change: harden-untrusted-content-ingestion, D1): every absolute
|
|
11
|
+
* request path must lie under a configured root (`writable` ∪ `mounts` ∪
|
|
12
|
+
* `workspaceRoot`), outside the sensitive denylist, before docker is spawned.
|
|
8
13
|
*
|
|
9
14
|
* The raw runner is injectable so unit tests can mock the Docker boundary
|
|
10
15
|
* without a container.
|
|
11
16
|
*/
|
|
17
|
+
|
|
18
|
+
import { mkdir, realpath, stat } from "node:fs/promises";
|
|
19
|
+
import { homedir } from "node:os";
|
|
20
|
+
import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
|
|
12
21
|
import { spawn } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
|
|
13
|
-
import { dirname } from "node:path";
|
|
14
22
|
import { DocConverterError } from "./errors.js";
|
|
15
23
|
|
|
16
24
|
/** One JSON request to the engine. `command` selects the handler. */
|
|
@@ -47,10 +55,14 @@ export interface RunnerResult {
|
|
|
47
55
|
export type EngineRunner = (argv: string[], stdin: string) => Promise<RunnerResult>;
|
|
48
56
|
|
|
49
57
|
export interface EngineConfig {
|
|
50
|
-
/** Image tag, e.g. `pi-doc-engine:0.
|
|
58
|
+
/** Image tag, e.g. `pi-doc-engine:0.2.0`. */
|
|
51
59
|
image: string;
|
|
52
|
-
/**
|
|
60
|
+
/** Roots always mounted read-write (the facade puts `stagingDir` here). Created on demand. */
|
|
61
|
+
writable?: string[];
|
|
62
|
+
/** Extra caller-configured roots. Request paths under them are admitted. */
|
|
53
63
|
mounts?: string[];
|
|
64
|
+
/** Workspace root admitting request paths (default `process.cwd()`). */
|
|
65
|
+
workspaceRoot?: string;
|
|
54
66
|
/** Passed through to `docker run -e GEMINI_API_KEY` when set in env. */
|
|
55
67
|
passEnv?: string[];
|
|
56
68
|
/** Override the process runner (tests). */
|
|
@@ -88,10 +100,18 @@ const defaultRunner: EngineRunner = (argv, stdin) =>
|
|
|
88
100
|
child.stdin.end(stdin);
|
|
89
101
|
});
|
|
90
102
|
|
|
103
|
+
/** One planned bind mount, keyed by its (lexical) container target. */
|
|
104
|
+
interface PlannedMount {
|
|
105
|
+
source: string;
|
|
106
|
+
mode: "ro" | "rw";
|
|
107
|
+
}
|
|
108
|
+
|
|
91
109
|
/** Build the `docker run` argv for a request. */
|
|
92
|
-
function buildArgv(cfg: EngineConfig, mounts:
|
|
110
|
+
function buildArgv(cfg: EngineConfig, mounts: Map<string, PlannedMount>): string[] {
|
|
93
111
|
const argv = [cfg.dockerBin ?? "docker", "run", "--rm", "-i"];
|
|
94
|
-
for (const
|
|
112
|
+
for (const [target, { source, mode }] of mounts) {
|
|
113
|
+
argv.push("-v", mode === "ro" ? `${source}:${target}:ro` : `${source}:${target}`);
|
|
114
|
+
}
|
|
95
115
|
for (const key of cfg.passEnv ?? ["GEMINI_API_KEY"]) {
|
|
96
116
|
if (process.env[key] !== undefined) argv.push("-e", key);
|
|
97
117
|
}
|
|
@@ -99,18 +119,136 @@ function buildArgv(cfg: EngineConfig, mounts: Set<string>): string[] {
|
|
|
99
119
|
return argv;
|
|
100
120
|
}
|
|
101
121
|
|
|
102
|
-
/**
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
122
|
+
/** Sensitive host dirs never mounted unless a containing root opts in. `~` = homedir at call time. */
|
|
123
|
+
const DENYLIST = ["/etc", "/root", "/var/run", "/proc", "/sys", "/dev"];
|
|
124
|
+
const HOME_DENYLIST = [".ssh", ".aws", ".gnupg", ".config", ".pi", ".docker", ".kube"];
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Write keys per command (mounted rw), and whether the command's other paths
|
|
128
|
+
* are verified read-only. Unknown commands mount everything rw (within
|
|
129
|
+
* confinement). Engine write sites: design D1 table.
|
|
130
|
+
*/
|
|
131
|
+
function modeFor(req: EngineRequest): { writeKeys: Set<string>; othersRo: boolean } {
|
|
132
|
+
const apply = req.apply !== false;
|
|
133
|
+
switch (req.command) {
|
|
134
|
+
case "convertToMarkdown":
|
|
135
|
+
return { writeKeys: new Set(), othersRo: true };
|
|
136
|
+
case "renderPdf":
|
|
137
|
+
return { writeKeys: new Set(["output"]), othersRo: true };
|
|
138
|
+
case "renderDocx":
|
|
139
|
+
return { writeKeys: new Set(["output", "cacheDir"]), othersRo: false };
|
|
140
|
+
case "extractForEdit":
|
|
141
|
+
case "mergeBack":
|
|
142
|
+
return { writeKeys: new Set(["output"]), othersRo: false };
|
|
143
|
+
case "fillFrontmatter":
|
|
144
|
+
case "profileTables":
|
|
145
|
+
return apply ? { writeKeys: new Set(["paths"]), othersRo: false } : { writeKeys: new Set(), othersRo: true };
|
|
146
|
+
default:
|
|
147
|
+
return { writeKeys: new Set(), othersRo: false };
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const isUnder = (p: string, root: string) => p === root || p.startsWith(root.endsWith(sep) ? root : root + sep);
|
|
152
|
+
|
|
153
|
+
/** realpath of the nearest existing ancestor, with the non-existent remainder re-appended. */
|
|
154
|
+
async function realpathLoose(p: string): Promise<string> {
|
|
155
|
+
let cur = resolve(p);
|
|
156
|
+
const rest: string[] = [];
|
|
157
|
+
for (;;) {
|
|
158
|
+
try {
|
|
159
|
+
return join(await realpath(cur), ...rest.reverse());
|
|
160
|
+
} catch {
|
|
161
|
+
const parent = dirname(cur);
|
|
162
|
+
if (parent === cur) return resolve(p);
|
|
163
|
+
rest.push(basename(cur));
|
|
164
|
+
cur = parent;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async function isDir(p: string): Promise<boolean> {
|
|
170
|
+
try {
|
|
171
|
+
return (await stat(p)).isDirectory();
|
|
172
|
+
} catch {
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function notAllowed(path: string, why: string, roots: string[]): DocConverterError {
|
|
178
|
+
return new DocConverterError({
|
|
179
|
+
code: "PATH_NOT_ALLOWED",
|
|
180
|
+
message:
|
|
181
|
+
`path not allowed: ${path} (${why}). Configured roots: ${roots.join(", ") || "(none)"}. ` +
|
|
182
|
+
`Pass \`mounts:[dir]\` or \`workspaceRoot\` to admit files outside the workspace.`,
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Plan the bind mounts for a request, enforcing confinement + denylist.
|
|
188
|
+
* Throws `PATH_NOT_ALLOWED` before anything is spawned.
|
|
189
|
+
*/
|
|
190
|
+
async function planMounts(cfg: EngineConfig, req: EngineRequest): Promise<Map<string, PlannedMount>> {
|
|
191
|
+
const configured = [...(cfg.writable ?? []), ...(cfg.mounts ?? []), cfg.workspaceRoot ?? process.cwd()];
|
|
192
|
+
// Materialise roots: create writable ones, then realpath every root.
|
|
193
|
+
for (const w of cfg.writable ?? []) await mkdir(w, { recursive: true });
|
|
194
|
+
const roots: string[] = [];
|
|
195
|
+
for (const r of configured) {
|
|
196
|
+
const real = await realpathLoose(r);
|
|
197
|
+
if (real === sep || resolve(r) === sep) throw notAllowed(r, "`/` cannot be a root", configured);
|
|
198
|
+
roots.push(real);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Denylist entries, lexical + realpath (e.g. /var/run → /run, symlinked ~/.pi).
|
|
202
|
+
const home = homedir();
|
|
203
|
+
const deny: string[][] = [];
|
|
204
|
+
for (const d of [...DENYLIST, ...HOME_DENYLIST.map((h) => join(home, h))]) {
|
|
205
|
+
deny.push([...new Set([d, await realpathLoose(d)])]);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const plan = new Map<string, PlannedMount>();
|
|
209
|
+
const addMount = (target: string, source: string, mode: "ro" | "rw") => {
|
|
210
|
+
const prev = plan.get(target);
|
|
211
|
+
plan.set(target, { source, mode: prev?.mode === "rw" ? "rw" : mode });
|
|
107
212
|
};
|
|
213
|
+
for (const w of cfg.writable ?? []) addMount(resolve(w), await realpathLoose(w), "rw");
|
|
214
|
+
|
|
215
|
+
const { writeKeys, othersRo } = modeFor(req);
|
|
216
|
+
const check = async (p: string, mode: "ro" | "rw") => {
|
|
217
|
+
if (!isAbsolute(p)) return; // engine has no host cwd: relative paths never hit host files
|
|
218
|
+
if (p.split(/[\\/]/).includes("..")) throw notAllowed(p, "`..` segment", configured);
|
|
219
|
+
if (p.includes(":")) throw notAllowed(p, "`:` breaks the bind-mount spec", configured);
|
|
220
|
+
const lexical = resolve(p);
|
|
221
|
+
const globAt = lexical.search(/[*?[]/);
|
|
222
|
+
let target: string;
|
|
223
|
+
if (globAt >= 0) target = dirname(lexical.slice(0, globAt + 1));
|
|
224
|
+
else if (await isDir(lexical)) target = lexical;
|
|
225
|
+
else target = dirname(lexical);
|
|
226
|
+
const realPath = await realpathLoose(lexical.slice(0, globAt >= 0 ? globAt : undefined));
|
|
227
|
+
const source = await realpathLoose(target);
|
|
228
|
+
|
|
229
|
+
const containing = roots.filter((r) => isUnder(realPath, r) && isUnder(source, r));
|
|
230
|
+
if (containing.length === 0) throw notAllowed(p, "outside every configured root", configured);
|
|
231
|
+
for (const variants of deny) {
|
|
232
|
+
const hit = variants.some((d) => isUnder(source, d) || isUnder(realPath, d) || (globAt >= 0 && isUnder(d, source)));
|
|
233
|
+
if (!hit) continue;
|
|
234
|
+
const optedIn = containing.some((r) => variants.some((d) => isUnder(r, d)));
|
|
235
|
+
if (!optedIn) throw notAllowed(p, `sensitive directory ${variants[0]}`, configured);
|
|
236
|
+
}
|
|
237
|
+
addMount(target, source, mode);
|
|
238
|
+
};
|
|
239
|
+
|
|
108
240
|
for (const [k, v] of Object.entries(req)) {
|
|
109
241
|
if (k === "command") continue;
|
|
110
|
-
|
|
111
|
-
|
|
242
|
+
const mode = writeKeys.has(k) || !othersRo ? "rw" : "ro";
|
|
243
|
+
for (const item of Array.isArray(v) ? v : [v]) {
|
|
244
|
+
if (typeof item === "string") await check(item, mode);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
// Only after every path passed: create missing rw dirs (else docker creates them as root).
|
|
248
|
+
for (const { source, mode } of plan.values()) {
|
|
249
|
+
if (mode === "rw" && !(await isDir(source))) await mkdir(source, { recursive: true });
|
|
112
250
|
}
|
|
113
|
-
return
|
|
251
|
+
return plan;
|
|
114
252
|
}
|
|
115
253
|
|
|
116
254
|
/**
|
|
@@ -122,7 +260,7 @@ export async function runEngine<T = Record<string, unknown>>(
|
|
|
122
260
|
req: EngineRequest,
|
|
123
261
|
): Promise<T> {
|
|
124
262
|
const runner = cfg.runner ?? defaultRunner;
|
|
125
|
-
const argv = buildArgv(cfg,
|
|
263
|
+
const argv = buildArgv(cfg, await planMounts(cfg, req));
|
|
126
264
|
const { stdout, stderr, exitCode } = await runner(argv, JSON.stringify(req));
|
|
127
265
|
|
|
128
266
|
let parsed: EngineResponse | undefined;
|
|
@@ -174,6 +312,8 @@ function mapEngineCode(code: string): DocConverterError["code"] {
|
|
|
174
312
|
case "INGEST_FAILED":
|
|
175
313
|
case "DOCLING_UNAVAILABLE":
|
|
176
314
|
return "INGEST_FAILED";
|
|
315
|
+
case "MMDC_UNAVAILABLE":
|
|
316
|
+
return "MMDC_UNAVAILABLE";
|
|
177
317
|
case "PRODUCE_FAILED":
|
|
178
318
|
case "MMDC_FAILED":
|
|
179
319
|
return "PRODUCE_FAILED";
|
package/src/errors.ts
CHANGED
|
@@ -12,8 +12,10 @@ export type DocConverterErrorCode =
|
|
|
12
12
|
| "OCR_LANG_UNSUPPORTED" // canonical lang not supported by chosen engine
|
|
13
13
|
| "OCR_ENGINE_UNKNOWN" // unknown OCR engine
|
|
14
14
|
| "UNSUPPORTED_FORMAT" // extension not routable to a command
|
|
15
|
+
| "PATH_NOT_ALLOWED" // request path outside configured roots or in a sensitive dir
|
|
15
16
|
| "INGEST_FAILED"
|
|
16
17
|
| "PRODUCE_FAILED"
|
|
18
|
+
| "MMDC_UNAVAILABLE" // mermaid render attempted but the headless browser cannot launch (arch/runtime)
|
|
17
19
|
| "FILL_FAILED"
|
|
18
20
|
| "PROFILE_FAILED"
|
|
19
21
|
| "INTERNAL";
|
package/src/index.ts
CHANGED
|
@@ -7,14 +7,14 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { mkdir, writeFile } from "node:fs/promises";
|
|
9
9
|
import { basename, join } from "node:path";
|
|
10
|
-
import {
|
|
10
|
+
import { type EngineConfig, runEngine } from "./engine.js";
|
|
11
11
|
import { mapOcrCodes } from "./ocr.js";
|
|
12
|
-
import { ingestDocType } from "./routing.js";
|
|
13
12
|
import {
|
|
14
13
|
buildProvenance,
|
|
15
14
|
sha256File,
|
|
16
15
|
stampProvenance,
|
|
17
16
|
} from "./provenance.js";
|
|
17
|
+
import { ingestDocType } from "./routing.js";
|
|
18
18
|
import type {
|
|
19
19
|
ConvertToMarkdownOptions,
|
|
20
20
|
ConvertToMarkdownResult,
|
|
@@ -28,12 +28,14 @@ import type {
|
|
|
28
28
|
} from "./types.js";
|
|
29
29
|
|
|
30
30
|
export interface DocumentConverterConfig {
|
|
31
|
-
/** Image tag, e.g. `pi-doc-engine:0.
|
|
31
|
+
/** Image tag, e.g. `pi-doc-engine:0.2.0`. */
|
|
32
32
|
image: string;
|
|
33
33
|
/** Staging dir where ingest writes `.md` for kb. Created on demand. */
|
|
34
34
|
stagingDir: string;
|
|
35
|
-
/** Extra host
|
|
35
|
+
/** Extra host roots: request paths under them are admitted (mounted on demand). */
|
|
36
36
|
mounts?: string[];
|
|
37
|
+
/** Workspace root admitting request paths (default `process.cwd()`). */
|
|
38
|
+
workspaceRoot?: string;
|
|
37
39
|
/** Test hook: inject the engine config (e.g. a fake runner). */
|
|
38
40
|
engine?: Partial<EngineConfig>;
|
|
39
41
|
}
|
|
@@ -42,7 +44,9 @@ export interface DocumentConverterConfig {
|
|
|
42
44
|
export function createDocumentConverter(config: DocumentConverterConfig) {
|
|
43
45
|
const engineCfg = (extraMounts: string[] = []): EngineConfig => ({
|
|
44
46
|
image: config.image,
|
|
45
|
-
|
|
47
|
+
writable: [config.stagingDir],
|
|
48
|
+
mounts: [...(config.mounts ?? []), ...extraMounts],
|
|
49
|
+
workspaceRoot: config.workspaceRoot,
|
|
46
50
|
...config.engine,
|
|
47
51
|
});
|
|
48
52
|
|
|
@@ -164,16 +168,16 @@ function replaceExt(name: string, ext: string): string {
|
|
|
164
168
|
return name.replace(/\.[^.]+$/, "") + ext;
|
|
165
169
|
}
|
|
166
170
|
|
|
167
|
-
export { DocConverterError } from "./errors.js";
|
|
168
171
|
export type { DocConverterErrorCode } from "./errors.js";
|
|
169
|
-
export
|
|
172
|
+
export { DocConverterError } from "./errors.js";
|
|
173
|
+
export { mapOcrCodes, SUPPORTED_LANGUAGES } from "./ocr.js";
|
|
174
|
+
export { buildProvenance, provenanceFrontmatter, sha256File, stampProvenance } from "./provenance.js";
|
|
175
|
+
export { docTypeOf, ingestDocType, isIngestable } from "./routing.js";
|
|
170
176
|
export type {
|
|
171
177
|
DocumentFrontmatter,
|
|
172
|
-
Provenance,
|
|
173
178
|
NanoBananaConfig,
|
|
174
|
-
|
|
179
|
+
Provenance,
|
|
175
180
|
TableProfile,
|
|
181
|
+
TableProfiles,
|
|
176
182
|
} from "./schema.js";
|
|
177
|
-
export
|
|
178
|
-
export { docTypeOf, isIngestable, ingestDocType } from "./routing.js";
|
|
179
|
-
export { buildProvenance, stampProvenance, provenanceFrontmatter, sha256File } from "./provenance.js";
|
|
183
|
+
export * from "./types.js";
|
package/src/schema.ts
CHANGED
|
@@ -21,7 +21,7 @@ export type LogoMap = Record<string, string>;
|
|
|
21
21
|
/**
|
|
22
22
|
* Opt-in styled-diagram rendering. When `enabled`, each Mermaid block is
|
|
23
23
|
* replaced by a cached `.mermaid-cache/<md5>.png` generated via the nano-banana
|
|
24
|
-
* CLI using the named `style`. Any failure falls back to mmdc
|
|
24
|
+
* CLI using the named `style`. Any failure falls back to mmdc; if the browser cannot launch the call fails with `MMDC_UNAVAILABLE`.
|
|
25
25
|
*/
|
|
26
26
|
export interface NanoBananaConfig {
|
|
27
27
|
enabled: boolean;
|