Skip to content

Open source CapCut alternative.

TypeScript

feat(pdf-fill): add PDF form filling and hosted form mapper pipeline

David Le5d05fbd81bdf
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedFormMapper.swift b/apps/Donkey/Sources/DonkeyAI/HostedFormMapper.swift
new file mode 100644
index 00000000..4de59e9f
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/HostedFormMapper.swift
@@ -0,0 +1,117 @@
+import DonkeyContracts
+import Foundation
+
+/// The model boundary behind `pdf.fill`: a form rendered in reading order (each fillable field inline)
+/// plus the user's data in, a `{field_id: value}` map out. This is the ONE bounded inference the fill
+/// pipeline makes — the planner never composes the map step by step, so it cannot stall before the
+/// write. Returns nil on any failure; the orchestrator turns nil into a clean "could not map" outcome.
+public struct HostedFormMapper: Sendable {
+ private let backend: DonkeyBackendInferenceClient
+ private let maxOutputTokens: Int
+ private let timeoutSeconds: TimeInterval
+
+ public init(
+ backend: DonkeyBackendInferenceClient,
+ maxOutputTokens: Int = 8_000,
+ timeoutSeconds: TimeInterval = 180
+ ) {
+ self.backend = backend
+ self.maxOutputTokens = maxOutputTokens
+ self.timeoutSeconds = timeoutSeconds
+ }
+
+ public func map(formText: String, dataText: String) async -> [String: String]? {
+ let request = RemoteInferenceResponseCreateRequest(
+ input: .array([
+ .object([
+ "role": .string("user"),
+ "content": .array([
+ .object(["type": .string("input_text"), "text": .string(Self.prompt(formText: formText, dataText: dataText))])
+ ])
+ ])
+ ]),
+ store: false,
+ metadata: ["source": "hosted-form-mapper", "prompt_version": "pdf-fill-map-v1"],
+ parameters: [
+ // Deterministic: a form fill should map the same data the same way every time.
+ "temperature": .number(0),
+ "max_output_tokens": .number(Double(maxOutputTokens)),
+ "thinking_level": .string("medium"),
+ // json_object, NOT a strict schema — constrained-schema decoding corrupts the map on this
+ // backend, so ask for a bare JSON object and parse it tolerantly.
+ "response_format": .object(["type": .string("json_object")])
+ ]
+ )
+ let backend = self.backend
+ // This is the one network call in the fill pipeline, and the backend can drop a request under
+ // load. A single transient miss here used to fail the whole `pdf.fill` and send the planner back
+ // to scouting, so retry a couple of times before giving up. The call is deterministic
+ // (temperature 0), so a retry costs only latency, never a different answer.
+ for attempt in 0..<3 {
+ if attempt > 0 { try? await Task.sleep(nanoseconds: 800_000_000) }
+ guard let response = try? await AIDeadline.enforce(seconds: timeoutSeconds, {
+ try await backend.createResponse(request)
+ }) else { continue }
+ guard let text = RemoteInferenceResponseHelpers.outputText(from: response),
+ let map = Self.decodeMap(from: text) else { continue }
+ return map
+ }
+ return nil
+ }
+
+ /// Pull a `{field_id: value}` object out of the model's reply — tolerant of surrounding prose or a
+ /// code fence by slicing from the first `{` to the last `}` — and coerce each scalar value to a
+ /// string. Nested objects/arrays/null are skipped (a field value is always a scalar).
+ static func decodeMap(from text: String) -> [String: String]? {
+ guard let start = text.firstIndex(of: "{"), let end = text.lastIndex(of: "}"), start < end else {
+ return nil
+ }
+ guard let data = String(text[start...end]).data(using: .utf8),
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
+ return nil
+ }
+ var map: [String: String] = [:]
+ for (key, value) in object {
+ if let string = value as? String {
+ map[key] = string
+ } else if let number = value as? NSNumber {
+ map[key] = scalarString(number)
+ }
+ }
+ return map.isEmpty ? nil : map
+ }
+
+ /// Render a JSON scalar without a spurious ".0" on integers (so a money line lands as "120000", not
+ /// "120000.0"). Booleans round-trip as "true"/"false" for checkbox on/off.
+ private static func scalarString(_ number: NSNumber) -> String {
+ if CFGetTypeID(number) == CFBooleanGetTypeID() {
+ return number.boolValue ? "true" : "false"
+ }
+ let double = number.doubleValue
+ if double == double.rounded(), abs(double) < 1e15 {
+ return String(Int64(double))
+ }
+ return number.stringValue
+ }
+
+ private static func prompt(formText: String, dataText: String) -> String {
+ """
+ You fill PDF forms. Below is a form in reading order with each fillable field shown inline as \
+ ⟦id⟧ (text field), ⟦x id=on⟧ (checkbox — the value is the on-state shown after =, used to tick \
+ it), or ⟦? id=a|b⟧ (dropdown with its options). Map the user's data onto the form's fields.
+
+ Return ONLY a strict JSON object {field_id: value} — no prose, no code fence. Use the exact ids \
+ from the markers. Cover the entity name, full address, and ID numbers, plus every money line you \
+ can match. COMPUTE the values the data does not state outright — for a Form 1120 that means net \
+ receipts (gross − returns), total income, total deductions, taxable income, and tax (21% of \
+ taxable income). Text and dropdown values are strings; a checkbox value is the on-state shown \
+ after its = . Omit any field you have no value for.
+
+ FORM:
+ \(formText)
+
+ DATA:
+ \(dataText)
+ """
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/FormFillOrchestrator.swift b/apps/Donkey/Sources/DonkeyRuntime/FormFillOrchestrator.swift
new file mode 100644
index 00000000..f8b1425b
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/FormFillOrchestrator.swift
@@ -0,0 +1,125 @@
+import DonkeyHarness
+import Foundation
+
+/// The deterministic half of `pdf.fill`: read the whole form, hand it (with the data) to the one-shot
+/// `mapper` for a `{field_id: value}` map, write the filled PDF with the bundled `pdf-fill`, then verify
+/// and reconcile. The mapping is the ONLY model call; everything else is fixed code, so once a map
+/// exists the write always happens — the planner never gets the chance to stall before it.
+public struct FormFillOrchestrator: Sendable {
+ private let mapper: @Sendable (String, String) async -> [String: String]?
+
+ public init(mapper: @escaping @Sendable (String, String) async -> [String: String]?) {
+ self.mapper = mapper
+ }
+
+ public func fill(_ request: HarnessFormFillRequest) async -> HarnessFormFillOutcome {
+ let fileManager = FileManager.default
+ // Working directory: the conversation's own folder when present, else home — same rule as shell_exec.
+ let workingDirectory = DonkeyCommandBackends.resolvedWorkingDirectoryPath(request.workingDirectory)
+
+ let formPath = Self.resolve(request.form, against: workingDirectory)
+ guard fileManager.fileExists(atPath: formPath) else {
+ return HarnessFormFillOutcome(text: "No form file at \(request.form).", succeeded: false)
+ }
+
+ // `data` is either a file path or the literal data text.
+ let dataText: String = {
+ let dataPath = Self.resolve(request.data, against: workingDirectory)
+ if fileManager.fileExists(atPath: dataPath),
+ let contents = try? String(contentsOfFile: dataPath, encoding: .utf8) {
+ return contents
+ }
+ return request.data
+ }()
+
+ // 1. Read the WHOLE form in reading order (fields inline) for a single mapping pass.
+ let read = DonkeyCommandBackends.runBundledTool(
+ "pdf-fill", ["form", formPath, "--full"], workingDirectory: workingDirectory
+ )
+ guard read.exitCode == 0, !read.stdout.isEmpty else {
+ return HarnessFormFillOutcome(
+ text: "Could not read the form: \(read.stderr.isEmpty ? read.stdout : read.stderr)",
+ succeeded: false
+ )
+ }
+
+ // 2. The ONE bounded inference: form + data → {field_id: value}.
+ guard let map = await mapper(read.stdout, dataText), !map.isEmpty else {
+ return HarnessFormFillOutcome(text: "Could not map any fields onto the form.", succeeded: false)
+ }
+
+ // 3. Write the map and apply it with `pdf-fill set` (writes a NEW pdf, regenerates appearances).
+ let outPath = Self.resolve(request.out ?? "out.pdf", against: workingDirectory)
+ let mapPath = (workingDirectory as NSString).appendingPathComponent("map.json")
+ guard let mapData = try? JSONSerialization.data(withJSONObject: map, options: [.sortedKeys]),
+ (try? mapData.write(to: URL(fileURLWithPath: mapPath))) != nil else {
+ return HarnessFormFillOutcome(text: "Could not write the field map.", succeeded: false)
+ }
+ let set = DonkeyCommandBackends.runBundledTool(
+ "pdf-fill", ["set", formPath, "--data", mapPath, "-o", outPath], workingDirectory: workingDirectory
+ )
+
+ // 4. Verify + reconcile from `pdf-fill set`'s own JSON report and the file on disk.
+ let report = Self.parseSetReport(set.stdout)
+ let produced = fileManager.fileExists(atPath: outPath)
+ guard produced, !report.applied.isEmpty else {
+ let why = set.exitCode == 0
+ ? "mapped \(map.count) value(s) but applied none to the form"
+ : (set.stderr.isEmpty ? set.stdout : set.stderr)
+ return HarnessFormFillOutcome(
+ text: "Filling \(request.form) did not complete: \(why)",
+ succeeded: false,
+ outPath: produced ? outPath : nil
+ )
+ }
+ // Strong, self-contained evidence so the planner COMPLETES instead of re-verifying — the same loop
+ // the skill_run path documents, where a generic "succeeded" sent the run hunting for a second tool
+ // to confirm. State the verified path, that the file exists, the applied count, and a few real
+ // values that landed, so the result IS the proof and the planner can finish on it.
+ // Prefer the values whose ids the report says it applied; if those ids don't resolve against the map
+ // (a key-space mismatch between the tool's report and the mapper), fall back to the mapped values so
+ // the evidence never silently goes blank.
+ let appliedValues = report.applied.compactMap { map[$0] }
+ let samples = Self.evidenceSamples(appliedValues.isEmpty ? Array(map.values) : appliedValues)
+ var summary = "Done. Wrote and verified the filled form at \(outPath) "
+ + "(file exists; \(report.applied.count) field\(report.applied.count == 1 ? "" : "s") applied"
+ + (samples.isEmpty ? "" : ", including \(samples)") + "). "
+ + "This is the finished deliverable — no further checking is needed."
+ if !report.missing.isEmpty {
+ summary += " (\(report.missing.count) mapped id\(report.missing.count == 1 ? "" : "s") were not present on the form and were skipped.)"
+ }
+ return HarnessFormFillOutcome(text: summary, succeeded: true, outPath: outPath)
+ }
+
+ /// Resolve a path against the working directory (absolute and `~` paths pass through unchanged).
+ private static func resolve(_ path: String, against workingDirectory: String) -> String {
+ let expanded = (path as NSString).expandingTildeInPath
+ if (expanded as NSString).isAbsolutePath { return expanded }
+ return (workingDirectory as NSString).appendingPathComponent(expanded)
+ }
+
+ /// A short, recognizable sample of the values that landed — preferring the longer, textual ones
+ /// (names, addresses, ids) over bare numbers — so the planner sees concrete proof the right data is
+ /// in the form and can complete on this result alone.
+ private static func evidenceSamples(_ values: [String]) -> String {
+ values
+ .filter { $0.count >= 3 }
+ .sorted { $0.count > $1.count }
+ .prefix(3)
+ .map { value in "“\(value.count > 40 ? String(value.prefix(40)) + "…" : value)”" }
+ .joined(separator: ", ")
+ }
+
+ /// `pdf-fill set` prints `{"out":…, "applied":[…], "missing":[…]}`. Pull applied/missing for the
+ /// coverage report; tolerate a non-JSON line by returning empties.
+ private static func parseSetReport(_ stdout: String) -> (applied: [String], missing: [String]) {
+ guard let start = stdout.firstIndex(of: "{"), let end = stdout.lastIndex(of: "}"), start < end,
+ let data = String(stdout[start...end]).data(using: .utf8),
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
+ return ([], [])
+ }
+ let applied = (object["applied"] as? [Any])?.compactMap { $0 as? String } ?? []
+ let missing = (object["missing"] as? [Any])?.compactMap { $0 as? String } ?? []
+ return (applied, missing)
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/pdf/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/pdf/SKILL.md
index 6ec7413f..ac53416d 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/pdf/SKILL.md
+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/pdf/SKILL.md
@@ -1,51 +1,28 @@
# PDF
id: pdf
-description: Expert headless PDF and document work — extract text and structured data with liteparse, fill forms with pdf-fill, merge/split/rotate with qpdf, and convert document formats with textutil.
+description: Expert headless PDF and document work — fill forms with pdf-fill, extract text and structured data with liteparse, merge/split/rotate with qpdf, and convert document formats with textutil.
tags: pdf, document, convert, merge, split, ocr, extract, fill, form
keywords: pdf, extract, parse, text, ocr, scan, json, merge, combine, split, extract pages, rotate, convert, docx, rtf, html, fill, form, fillable, acroform, checkbox
tools: shell_exec
-`lit` (liteparse), `pdf-fill`, and `qpdf` are bundled and on the PATH; `textutil`
-and `mdls` ship with macOS. This is the headless path — fill a form right here with
-`pdf-fill`; only drop to the `documents` skill when the user wants to watch it
-happen in Preview. Creating files is reversible (consent gate).
+`pdf-fill`, `lit` (liteparse), and `qpdf` are bundled and on the PATH; `textutil` and `mdls` ship with macOS. This is the headless path — fill, parse, and convert right here; only drop to the `documents` skill when the user wants to watch it in Preview. Files you create are reversible (consent gate), and your shell runs in your working directory, so use BARE filenames (`f1120.pdf`, `out.pdf`), never your home root.
-## qpdf — structure (page order in, page order out)
-- Merge: `qpdf --empty --pages a.pdf b.pdf -- out.pdf`.
-- Extract / split a range: `qpdf in.pdf --pages in.pdf 1-5 -- out.pdf`.
-- Rotate page 1 by 90°: `qpdf in.pdf --rotate=+90:1 -- out.pdf`.
-- Remove a known password: `qpdf --password=PW --decrypt in.pdf out.pdf`.
-- Page count: `qpdf --show-npages in.pdf`.
+## Fill a PDF form — `pdf.fill`
+A fillable form (an IRS/tax/government/insurance PDF with fillable fields) is filled in ONE call to the `pdf.fill` tool: give it `form` (the PDF) and `data` (a data file path, or the values as text). It reads the whole form, maps every value it can — entity name, address, ID numbers, every money line, and the totals it must compute (net receipts, total income/deductions, taxable income, tax) — writes a NEW filled PDF (`out.pdf` by default, or pass `out`), and reports what it applied and what it could not place. Do NOT run `pdf-fill` by hand, dump the field list, or read the form field-by-field — `pdf.fill` is the whole job. Ask for any value you don't have; don't invent field contents.
-## Convert document formats (textutil, built into macOS)
-- `textutil` converts among txt, html, rtf, doc, docx, odt with no extra tools: `textutil -convert docx in.html -output out.docx`, `textutil -convert txt in.docx -output out.txt`, `textutil -convert html in.rtf -output out.html`.
-- Markdown, LaTeX, and EPUB are NOT covered by textutil and need `pandoc`, which is not bundled — run `pandoc in.md -o out.docx` directly, and if it isn't installed (`command not found`), say plainly that those formats need pandoc installed.
-- To make a PDF from a document: convert it to HTML with textutil, then render that HTML to PDF via the `web-capture` skill (headless print).
+Flat or scanned form (no fillable fields — a page is just printed text or a scan): there is nothing for `pdf.fill` to fill, so overlay by position. Get label boxes with `lit parse in.pdf --format json`, then `echo '[{"page":0,"x":120,"y":700,"text":"Ada Lovelace","size":12}]' | pdf-fill overlay in.pdf --data - -o out.pdf`. Coordinates are PDF points from the BOTTOM-left; lit boxes are top-left, so convert with `pdf-fill pages in.pdf` (`y_pdf = height - y_top - h`). The result reports `stamped` and any `skipped`. `pdf-fill flatten out.pdf -o final.pdf` burns values in (non-editable) and warns on `droppedPages`.
-## Extract text or structured data from a PDF — use liteparse (`lit`)
+## Extract text or structured data — liteparse (`lit`)
- `lit` handles both digital and scanned PDFs; OCR is built in, so there is no separate rasterize/OCR step.
-- Plain text: `lit parse in.pdf`. Specific pages: `lit parse in.pdf --target-pages "1-5,10"`.
-- Structured JSON (per-element text with layout/bounding boxes — use this when the task needs fields, tables, or positions): `lit parse in.pdf --format json -o out.json`.
-- Skip OCR for a known-digital PDF to go faster: `lit parse in.pdf --no-ocr`.
-- For just a title/metadata lookup without parsing, `mdls -name kMDItemTitle in.pdf` still works.
+- Plain text: `lit parse in.pdf`. Specific pages: `lit parse in.pdf --target-pages "1-5,10"`. Skip OCR on a known-digital PDF to go faster: `--no-ocr`.
+- Structured JSON (per-element text with layout/bounding boxes — for tables or positions): `lit parse in.pdf --format json -o out.json`.
+- Just a title/metadata lookup: `mdls -name kMDItemTitle in.pdf`.
-## Fill a PDF form — use pdf-fill (`pdf-fill`)
-`pdf-fill` writes a NEW file; it never edits in place. All I/O is JSON. Start by asking it what kind of form this is:
-- `pdf-fill list in.pdf --pretty > fields.json` — ALWAYS redirect the field list to a file. A real form (a tax or government form) has hundreds of fields; dumping that to stdout floods the next step's context and times out the read on volume. Write it to a file, then inspect it (`head`, count with a `lit`/`jq` pass), and work from the file.
-- The list entries are `{name, type, value, page, rect}`. Field NAMES on official forms are opaque (`topmostSubform[0].Page1[0].f1_11[0]`) and carry no meaning on their own, so you must recover what each field IS before filling it — don't guess from the name.
-
-### Filling an official form (tax / government / insurance) — recover labels, then map and compute
-Opaque field names plus loose source data is a mapping problem, not a typing problem. Plan it as **read the data → recover each field's label → map data to fields → compute the derived values → write → verify**, and front-load the mapping and computation rather than circling the easy reads.
-- Recover labels by position: a field's caption is the text printed next to it. Get the page text with boxes (`lit parse in.pdf --format json`) and join each field's `rect` from `pdf-fill list` to the nearest text run (the label is usually just left of, or above, the box). pdf-fill rects are bottom-left-origin PDF points; lit boxes are top-left — convert with the page height from `pdf-fill pages in.pdf`. Now you have `field → label`, which is what to map the data onto.
-- Map the source data to fields by MEANING (you do this — match "gross receipts/total sales" to the receipts line, "officer compensation" to that line, etc.), then build the `{fieldName: value}` object and write it with `pdf-fill set`.
-- Compute the derived values the data doesn't state outright — most official forms have them. A 1120, for instance, needs net receipts (gross − returns), total income, total deductions, taxable income, and tax (21% of taxable income). Work these out explicitly before filling; don't leave them blank and don't expect them in the data.
-- If labels can't be recovered from the text layer (a scanned/flattened form), fall back to vision: rasterize a page (`lit screenshot`) and read the layout.
-- **Has fields (non-empty list) → set them.** Build a `{fieldName: value}` map and pipe it in: `echo '{"FullName":"Ada","Agree":true}' | pdf-fill set in.pdf --data - -o out.pdf`. Text and dropdown fields take strings; checkboxes take `true`/`false`. The result reports `applied` and `missing` so you can see any name that did not match.
-- **No fields (empty list) → it is a flat or scanned form; overlay text by position.** Get the labels and their boxes with `lit parse in.pdf --format json`, then stamp values next to them: `echo '[{"page":0,"x":120,"y":700,"text":"Ada Lovelace","size":12}]' | pdf-fill overlay in.pdf --data - -o out.pdf`. Coordinates are PDF points from the BOTTOM-left; lit boxes are top-left, so convert with the page height from `pdf-fill pages in.pdf` (`y_pdf = height - y_top - h`). Valid stamps are written even if some items are bad; the result reports `stamped` and any `skipped` items (with index and reason), so check `skipped` to catch dropped values.
-- To make the result non-editable (e.g. before sending it on), `pdf-fill flatten out.pdf -o final.pdf` burns the values into the page. It reports `processedPages`/`totalPages`; if it includes `droppedPages`/`warning`, some pages were lost — do not treat that output as complete.
-- Ask the user for any value you do not have before filling; do not invent field contents.
+## Restructure and convert
+- qpdf (page order in, page order out): merge `qpdf --empty --pages a.pdf b.pdf -- out.pdf`; split a range `qpdf in.pdf --pages in.pdf 1-5 -- out.pdf`; rotate `qpdf in.pdf --rotate=+90:1 -- out.pdf`; remove a known password `qpdf --password=PW --decrypt in.pdf out.pdf`; page count `qpdf --show-npages in.pdf`.
+- textutil (txt/html/rtf/doc/docx/odt, built into macOS): `textutil -convert docx in.html -output out.docx`. Markdown, LaTeX, and EPUB need `pandoc` (not bundled — run it directly, and if `command not found`, say those formats need pandoc installed). To make a PDF from a document: convert it to HTML with textutil, then render that HTML to PDF via the `web-capture` skill.
## Verify
-- After a structural edit, confirm with `qpdf --show-npages out.pdf` or re-read the text with `mdls`. After a conversion, confirm the output file exists and opens.
-- After filling, re-run `pdf-fill list out.pdf` and check the values are present (for an overlay, flatten then `lit parse` the result).
\ No newline at end of file
+- `pdf.fill` already verifies its own output and reports the applied fields. For an overlay, flatten then `lit parse` the result to confirm the values are present.
+- After a structural edit, `qpdf --show-npages out.pdf`; after a conversion, confirm the output file exists and opens.
diff --git a/tools/pdf-fill/README.md b/tools/pdf-fill/README.md
index a99ec012..08eff043 100644
--- a/tools/pdf-fill/README.md
+++ b/tools/pdf-fill/README.md
@@ -17,15 +17,16 @@ swiftc -O tools/pdf-fill/main.swift -o pdf-fill
## Subcommands
-All output is JSON. Errors print `{"error":"…"}` to stderr and exit non-zero.
-`--data` accepts a file path or `-` for stdin. Coordinates are PDF points from the
-**bottom-left** of the page.
+Output is JSON except for `form`, which is a plain-text page view. Errors print
+`{"error":"…"}` to stderr and exit non-zero. `--data` accepts a file path or `-`
+for stdin. Coordinates are PDF points from the **bottom-left** of the page.
| Command | Purpose |
|---|---|
-| `pdf-fill list <in.pdf>` | List fillable AcroForm fields: `{name, type, value, page, rect, options?}`. An empty array means the PDF has no fillable fields — use `overlay`. |
+| `pdf-fill list <in.pdf>` | List fillable AcroForm fields: `{name, type, value, page, rect, options?}`. An empty array means the PDF has no fillable fields — use `overlay`. Output is always indented; `--pretty` is accepted as a no-op so `pdf-fill list in.pdf --pretty > fields.json` works. |
| `pdf-fill pages <in.pdf>` | Per-page sizes: `{page, width, height}`. Use the height to convert a top-left parser's y (`y_pdf = height - y_top - h`). |
-| `pdf-fill set <in.pdf> --data map.json -o out.pdf` | Set field values from a `{fieldName: value}` map. Text/choice take strings; checkboxes take `true`/`false` (or on/off). Reports `applied` and `missing`. |
+| `pdf-fill form <in.pdf> [--page N] [--part K]` | Reading-order view of ONE page: printed text top-to-bottom, left-to-right, with fields interleaved inline where they sit — `⟦id⟧` (text), `⟦x id=on⟧` (checkbox, `on` ticks it), `⟦? id=a\|b⟧` (dropdown). `id` is the field's short leaf (`f1_4[0]`), which `set` resolves back to the full name. Lets a reader bind values the way a person reads the paper form instead of guessing a label per field by coordinates. Default page 0; `--page N` (0-indexed) picks a page; a dense page splits into `--part K` chunks that each fit the caller's output budget — a footer shows the next page/part. Text comes from PDFKit's `characterBounds`, in the same bottom-left space as the fields (no coordinate flip). |
+| `pdf-fill set <in.pdf> --data map.json -o out.pdf` | Set field values from a `{id: value}` map. `id` is either a full field name or the short id `form` shows (`f1_4[0]`, or `f1_4` without the widget index when unambiguous). Text/choice take strings; checkboxes take the on-value (or `true`/`false`/on/off). Reports `applied`, `missing`, and `ambiguous` (an id matching several fields — add the widget index). |
| `pdf-fill overlay <in.pdf> --data items.json -o out.pdf` | Stamp text onto a flat PDF from `[{page, x, y, text, size?, width?, height?}]`. Numeric fields accept JSON numbers or numeric strings. Invalid items are skipped (not fatal); the result reports `stamped` and any `skipped` items with `{index, reason}`. Fails only if nothing could be stamped. |
| `pdf-fill flatten <in.pdf> -o out.pdf` | Burn form values and overlays into page content (non-editable, text stays selectable). Reports `processedPages`/`totalPages`; if any page could not be read it adds `droppedPages` and a `warning` instead of reporting a clean success. |
@@ -38,4 +39,6 @@ All output is JSON. Errors print `{"error":"…"}` to stderr and exit non-zero.
separate `NeedAppearances` pass.
- Password-protected PDFs are rejected; decrypt first
(`qpdf --password=… --decrypt in.pdf out.pdf`).
-- Digital signatures and XFA forms are out of scope.
+- Digital signatures and pure-XFA dynamic forms are out of scope. XFA-*hybrid*
+ forms (which also carry a normal AcroForm layer, like IRS tax forms) work through
+ that layer — `list`, `form`, and `set` operate on it.
diff --git a/tools/pdf-fill/main.swift b/tools/pdf-fill/main.swift
index 41f0ca8f..6896b7e2 100644
--- a/tools/pdf-fill/main.swift
+++ b/tools/pdf-fill/main.swift
@@ -8,6 +8,7 @@
// Subcommands (all I/O is JSON so an LLM can drive it):
// pdf-fill list <in.pdf> → fillable fields as JSON
// pdf-fill pages <in.pdf> → per-page sizes as JSON
+// pdf-fill form <in.pdf> [--page N] → reading-order page view (text + fields)
// pdf-fill set <in.pdf> --data <map.json> -o <out.pdf>
// pdf-fill overlay <in.pdf> --data <items.json> -o <out.pdf>
// pdf-fill flatten <in.pdf> -o <out.pdf>
@@ -41,8 +42,16 @@ func emit(_ object: Any) {
// MARK: - Argument parsing
+/// Valueless boolean flags: present means true, and they never consume the next
+/// argument. `--pretty` is one because output is always pretty-printed — the `pdf`
+/// skill documents `pdf-fill list … --pretty`, and without this the parser tried to
+/// read a value for it, failed ("missing value for --pretty"), and wrote an empty
+/// field list, so form filling silently had nothing to map.
+let booleanFlags: Set<String> = ["pretty", "full"]
+
/// Pulls `--flag value` pairs out of an argument list, returning the leftover
-/// positional arguments and a flag map. Supports `-o` as an alias for `--out`.
+/// positional arguments and a flag map. Supports `-o` as an alias for `--out`, and
+/// valueless boolean flags (see `booleanFlags`) that stand alone.
func parse(_ args: [String]) -> (positional: [String], flags: [String: String]) {
var positional: [String] = []
var flags: [String: String] = [:]
@@ -54,9 +63,13 @@ func parse(_ args: [String]) -> (positional: [String], flags: [String: String])
else if arg.hasPrefix("--") { key = String(arg.dropFirst(2)) }
else { key = nil }
if let key = key {
- i += 1
- guard i < args.count else { fail("missing value for --\(key)") }
- flags[key] = args[i]
+ if booleanFlags.contains(key) {
+ flags[key] = "true"
+ } else {
+ i += 1
+ guard i < args.count else { fail("missing value for --\(key)") }
+ flags[key] = args[i]
+ }
} else {
positional.append(arg)
}
@@ -164,6 +177,167 @@ func commandPages(_ path: String) {
emit(pages)
}
+// MARK: - Reading-order page view
+
+/// Groups a page's characters into words with their on-page bounds. PDFKit's
+/// `characterBounds(at:)` returns rects in the same bottom-left coordinate space
+/// as widget annotations, so words and fields can be merged without any flip.
+func words(on page: PDFPage) -> [(rect: CGRect, text: String)] {
+ let count = page.numberOfCharacters
+ guard count > 0, let text = page.string as NSString? else { return [] }
+ var out: [(CGRect, String)] = []
+ var current = ""
+ var rect = CGRect.null
+ func flush() {
+ let trimmed = current.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !trimmed.isEmpty, !rect.isNull { out.append((rect, trimmed)) }
+ current = ""
+ rect = .null
+ }
+ for index in 0..<count {
+ let char = index < text.length ? text.substring(with: NSRange(location: index, length: 1)) : " "
+ if char == " " || char == "\n" || char == "\t" || char == "\r" { flush(); continue }
+ current += char
+ let bounds = page.characterBounds(at: index)
+ rect = rect.isNull ? bounds : rect.union(bounds)
+ }
+ flush()
+ return out
+}
+
+/// The short, unique id shown for a field and accepted by `set`: the leaf of the
+/// fully-qualified name, keeping the trailing widget index so paired checkbox widgets
+/// (`c1_11[0]` vs `c1_11[1]`) stay distinct. The full name on a real form is ~56
+/// characters (`topmostSubform[0].Page1[0].NameFieldsReadOrder[0].f1_4[0]`), which
+/// is far too verbose to repeat for every field in a page view bound by a small
+/// output budget — the leaf (`f1_4[0]`) carries the same identity in a handful of
+/// characters, and `set` maps it back.
+func leafName(_ fullName: String) -> String {
+ fullName.split(separator: ".").last.map(String.init) ?? fullName
+}
+
+/// An inline marker for a form field, placed where the field sits in the page so an
+/// LLM can read the surrounding label and bind a value to the field's short id.
+/// `⟦id⟧` is a text field, `⟦x id=on⟧` a checkbox (set `id` to `on` to tick it), and
+/// `⟦? id=a|b⟧` a dropdown with its options.
+func fieldMarker(_ annotation: PDFAnnotation, name: String) -> String {
+ let id = leafName(name)
+ switch annotation.widgetFieldType {
+ case .button:
+ let on = annotation.buttonWidgetStateString
+ return on.isEmpty ? "⟦x \(id)⟧" : "⟦x \(id)=\(on)⟧"
+ case .choice:
+ let options = (annotation.value(forAnnotationKey: kChoiceOptions) as? [Any])?.compactMap { $0 as? String } ?? []
+ return options.isEmpty ? "⟦? \(id)⟧" : "⟦? \(id)=\(options.joined(separator: "|"))⟧"
+ default:
+ return "⟦\(id)⟧"
+ }
+}
+
+/// The reading-order lines for ONE page: printed words and inline field markers, banded
+/// top-to-bottom and joined left-to-right. Shared by the paged view and `--full`.
+func formLines(for page: PDFPage) -> [String] {
+ // A token is a positioned piece of the page — either a printed word or a field marker.
+ struct Token { let y: CGFloat; let x: CGFloat; let text: String }
+ var tokens: [Token] = []
+ for (rect, text) in words(on: page) {
+ // Drop dotted leaders ("....") — pure visual fill between a label and its blank,
+ // noise in a text view and a large fraction of a dense form's characters.
+ if text.allSatisfy({ $0 == "." }) { continue }
+ tokens.append(Token(y: rect.midY, x: rect.minX, text: text))
+ }
+ for annotation in page.annotations where annotation.type == "Widget" {
+ guard let name = fieldName(annotation) else { continue }
+ tokens.append(Token(y: annotation.bounds.midY, x: annotation.bounds.minX, text: fieldMarker(annotation, name: name)))
+ }
+
+ // Top-to-bottom, then left-to-right within a band. Bands grow from their own top
+ // edge so a tall field cannot swallow rows far below it. Each band becomes a line.
+ tokens.sort { $0.y != $1.y ? $0.y > $1.y : $0.x < $1.x }
+ let bandTolerance: CGFloat = 6
+ var bands: [[Token]] = []
+ for token in tokens {
+ if let top = bands.last?.first, top.y - token.y <= bandTolerance {
+ bands[bands.count - 1].append(token)
+ } else {
+ bands.append([token])
+ }
+ }
+ return bands.map { band in band.sorted { $0.x < $1.x }.map(\.text).joined(separator: " ") }
+}
+
+let formMarkerLegend = "(⟦id⟧ = text field · ⟦x id=on⟧ = checkbox, set id to its on-value to tick · ⟦? id=a|b⟧ = dropdown. Fill with: pdf-fill set)"
+
+/// Renders ONE page of the form the way a person reads it: top-to-bottom,
+/// left-to-right, with the fillable fields interleaved inline among the printed text
+/// as short-id markers. This replaces guessing one label per field (which fails on
+/// dense grid forms where a field shares a horizontal band with unrelated text) — the
+/// model reads the page and binds values to the ids it sees.
+///
+/// One page at a time (default page 0; `--page N`, 0-indexed) because the model's
+/// per-tool-result budget is small and a whole multi-page form floods it. A single
+/// dense page can still exceed that budget, so the page is packed into PARTS of whole
+/// lines that each fit, navigated with `--part K` — nothing is silently truncated
+/// mid-page, and a footer says how to read the rest.
+func commandForm(_ path: String, _ flags: [String: String]) {
+ let document = loadDocument(path)
+ let pageCount = document.pageCount
+ let pageIndex = flags["page"].flatMap { Int($0) } ?? 0
+ let requestedPart = max(1, flags["part"].flatMap { Int($0) } ?? 1)
+ let fileName = (path as NSString).lastPathComponent
+
+ // `--full` dumps the WHOLE form — every page, no part-chunking, no nav footer — for a
+ // single mapping pass (the pdf.fill tool). The part/budget logic below exists only to
+ // fit the planner's per-result cap, which the one-shot mapper does not have.
+ if flags["full"] != nil {
+ var out: [String] = [formMarkerLegend]
+ for index in 0..<pageCount {
+ guard let page = document.page(at: index) else { continue }
+ let box = page.bounds(for: .mediaBox)
+ out.append("=== \(fileName) · page \(index) of \(pageCount - 1) (\(Int(box.width))x\(Int(box.height))) ===")
+ out.append(contentsOf: formLines(for: page))
+ }
+ print(out.joined(separator: "\n"))
+ return
+ }
+
+ guard pageIndex >= 0, pageIndex < pageCount, let page = document.page(at: pageIndex) else {
+ fail("no such page \(pageIndex); the form has pages 0…\(pageCount - 1)")
+ }
+ let box = page.bounds(for: .mediaBox)
+
+ let lines = formLines(for: page)
+
+ // Pack whole lines into parts that each fit the model's per-result budget, so a
+ // dense page is read part by part instead of being cut off mid-page.
+ let partBudget = 3000
+ var parts: [[String]] = [[]]
+ var size = 0
+ for line in lines {
+ if size + line.count > partBudget, !(parts[parts.count - 1].isEmpty) {
+ parts.append([])
+ size = 0
+ }
+ parts[parts.count - 1].append(line)
+ size += line.count + 1
+ }
+ let partCount = parts.count
+ let part = min(requestedPart, partCount)
+
+ var out: [String] = []
+ let partLabel = partCount > 1 ? ", part \(part) of \(partCount)" : ""
+ out.append("=== \(fileName) · page \(pageIndex) of \(pageCount - 1)\(partLabel) (\(Int(box.width))x\(Int(box.height))) ===")
+ if part == 1 {
+ out.append(formMarkerLegend)
+ }
+ out.append(contentsOf: parts[part - 1])
+ var nav: [String] = []
+ if part < partCount { nav.append("rest of THIS page → --page \(pageIndex) --part \(part + 1)") }
+ if pageIndex < pageCount - 1 { nav.append("NEXT page → --page \(pageIndex + 1)") }
+ if !nav.isEmpty { out.append("[\(nav.joined(separator: " "))]") }
+ print(out.joined(separator: "\n"))
+}
+
/// Coerce a JSON value to a number, accepting either a real JSON number or a
/// numeric string (an LLM may emit `"x":"120"`). Returns nil for anything else.
func numericValue(_ value: Any?) -> NSNumber? {
@@ -226,11 +400,36 @@ func commandSet(_ path: String, _ flags: [String: String]) {
for (_, annotation) in widgetAnnotations(document) {
if let name = fieldName(annotation) { byName[name, default: []].append(annotation) }
}
+ // Accept the short ids the `form` view shows (`f1_4[0]`, or `f1_4` without the
+ // widget index) as well as full names: index leaf → the full names that carry it,
+ // so a key can be resolved when it is unambiguous.
+ var byLeaf: [String: Set<String>] = [:]
+ for name in byName.keys {
+ let last = leafName(name)
+ byLeaf[last, default: []].insert(name)
+ if let bracket = last.firstIndex(of: "["), last.hasSuffix("]") {
+ byLeaf[String(last[..<bracket]), default: []].insert(name)
+ }
+ }
var applied: [String] = []
var missing: [String] = []
- for (name, rawValue) in map {
- guard let widgets = byName[name], !widgets.isEmpty else { missing.append(name); continue }
+ var ambiguous: [String] = []
+ for (key, rawValue) in map {
+ // Resolve the key to a full field name: exact match first, else a unique leaf.
+ let fullName: String
+ if byName[key] != nil {
+ fullName = key
+ } else if let names = byLeaf[key], names.count == 1 {
+ fullName = names.first!
+ } else if let names = byLeaf[key], names.count > 1 {
+ ambiguous.append("\(key) → \(names.sorted().joined(separator: ", "))")
+ continue
+ } else {
+ missing.append(key)
+ continue
+ }
+ guard let widgets = byName[fullName], !widgets.isEmpty else { missing.append(key); continue }
// A field is button-like if any of its widgets is a button (radio/checkbox).
let isButton = widgets.contains { $0.widgetFieldType == .button }
if isButton {
@@ -243,12 +442,20 @@ func commandSet(_ path: String, _ flags: [String: String]) {
// Set on every widget sharing the name (text fields spanning pages).
for widget in widgets { widget.widgetStringValue = string }
}
- applied.append(name)
+ // Report the caller's OWN key (the short id it passed), not the resolved full field name, so
+ // `applied`/`missing`/`ambiguous` are all in one key space and a caller can map an applied id back to
+ // the value it sent. Reporting the full name here broke that — the value lookup keyed by short id
+ // missed every applied field.
+ applied.append(key)
}
let out = outputURL(flags)
guard document.write(to: out) else { fail("could not write output: \(out.path)") }
- emit(["out": out.path, "applied": applied.sorted(), "missing": missing.sorted()])
+ var result: [String: Any] = ["out": out.path, "applied": applied.sorted(), "missing": missing.sorted()]
+ // Surface ambiguous ids distinctly (with their candidates) so the caller adds the
+ // widget index rather than assuming the value silently landed.
+ if !ambiguous.isEmpty { result["ambiguous"] = ambiguous.sorted() }
+ emit(result)
}
func commandOverlay(_ path: String, _ flags: [String: String]) {
@@ -356,10 +563,36 @@ func commandFlatten(_ path: String, _ flags: [String: String]) {
// MARK: - Entry point
+/// Usage, printed to stdout (exit 0) for `--help`/`-h`/`help` or a bare invocation.
+/// A confused caller that probes `pdf-fill --help` gets oriented instead of a non-zero
+/// exit that reads as a broken tool and sends it flailing.
+let usageText = """
+pdf-fill — fill PDF forms headlessly (native PDFKit, JSON I/O).
+
+ pdf-fill list <in.pdf> fillable fields as JSON {name,type,value,page,rect}
+ pdf-fill pages <in.pdf> per-page sizes as JSON
+ pdf-fill form <in.pdf> [--page N] [--part K]
+ read ONE page like a person: text with fields shown
+ inline as ⟦id⟧ / ⟦x id=on⟧ / ⟦? id=a|b⟧. Default page 0;
+ a dense page splits into parts. THIS is how you learn
+ which id to fill — read it page by page.
+ pdf-fill set <in.pdf> --data <map.json|-> -o <out.pdf>
+ apply {id: value}. Ids are what `form` shows (e.g.
+ "f1_4[0]") or full names; checkboxes take the on-value
+ (or true/false). Reports applied / missing / ambiguous.
+ pdf-fill overlay <in.pdf> --data <items.json|-> -o <out.pdf>
+ stamp text on a flat/scanned form by position
+ pdf-fill flatten <in.pdf> -o <out.pdf> burn values into the page (non-editable)
+
+Typical form fill: pdf-fill form in.pdf → read page, build {id:value} → pdf-fill set … -o out.pdf → next page.
+"""
+
let arguments = Array(CommandLine.arguments.dropFirst())
-guard let command = arguments.first else {
- fail("usage: pdf-fill <list|pages|set|overlay|flatten> <in.pdf> [options]")
+if arguments.isEmpty || arguments.contains("--help") || arguments.contains("-h") || arguments.first == "help" {
+ print(usageText)
+ exit(0)
}
+let command = arguments[0]
let rest = Array(arguments.dropFirst())
let (positional, flags) = parse(rest)
guard let input = positional.first else { fail("missing input PDF path") }
@@ -367,8 +600,9 @@ guard let input = positional.first else { fail("missing input PDF path") }
switch command {
case "list": commandList(input)
case "pages": commandPages(input)
+case "form": commandForm(input, flags)
case "set": commandSet(input, flags)
case "overlay": commandOverlay(input, flags)
case "flatten": commandFlatten(input, flags)
-default: fail("unknown command: \(command)")
+default: fail("unknown command: \(command); run `pdf-fill --help`")
}