Open source CapCut alternative.
TypeScript
feat(app): drive lit through an in-process pdf.parse sidecar; require bundled tools
David Lea2697f79e573
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swiftindex 6f398454..f3864456 100644--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift@@ -795,6 +795,11 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {let hostedFormMapper = HostedFormMapper(backend: backend)let formOrchestrator = FormFillOrchestrator(mapper: { form, data in await hostedFormMapper.map(formText: form, dataText: data) })harnessServices.formFiller = { request in await formOrchestrator.fill(request) }+ // PDF reading behind pdf.parse: run the bundled `lit` (liteparse) in-process — it resolves the binary+ // path and PDFIUM_LIB_PATH — so the planner extracts a PDF's text/JSON through one tool and never+ // invokes `lit` in a shell. Pure code, no model call.+ let pdfParseOrchestrator = PdfParseOrchestrator()+ harnessServices.pdfParser = { request in await pdfParseOrchestrator.parse(request) }// Short-form video behind shorts.make: transcribe on-device, make ONE bounded inference to pick the// moments, then cut/reframe/caption each clip in fixed code — so the whole download→clip→caption// recipe is a single tool call instead of a ~37-step planner loop billed at every tool. Momentdiff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swiftindex ad67dbd6..7f179d0d 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift@@ -492,6 +492,50 @@ public struct HarnessFormFillOutcome: Sendable {}}+/// The typed request for the `pdf.parse` tool: the PDF to read, the output format (plain text or+/// structured JSON), an optional page range, whether to skip OCR, an optional output file, and the+/// conversation's working directory (so the orchestrator runs the bundled `lit` and resolves paths inside+/// the agent's own folder). Declared in DonkeyHarness so the executor passes it across the closure+/// boundary without importing the runtime.+public struct HarnessPdfParseRequest: Sendable {+ public var file: String+ public var format: String?+ public var pages: String?+ public var noOcr: Bool+ public var out: String?+ public var workingDirectory: String?++ public init(+ file: String,+ format: String? = nil,+ pages: String? = nil,+ noOcr: Bool = false,+ out: String? = nil,+ workingDirectory: String? = nil+ ) {+ self.file = file+ self.format = format+ self.pages = pages+ self.noOcr = noOcr+ self.out = out+ self.workingDirectory = workingDirectory+ }+}++/// The result of a `pdf.parse` run: the extracted text/JSON (or a short summary when it was written to a+/// file), whether parsing succeeded, and the output path when one was written.+public struct HarnessPdfParseOutcome: Sendable {+ public var text: String+ public var succeeded: Bool+ public var outPath: String?++ public init(text: String, succeeded: Bool, outPath: String? = nil) {+ self.text = text+ self.succeeded = succeeded+ self.outPath = outPath+ }+}+/// The typed request for the `shorts.make` tool: the source (a local video path OR a URL to download), an/// optional clip count, an optional aspect ratio for the vertical crop, and the conversation's working/// directory (so the pipeline writes its clips inside the agent's own folder). Declared in DonkeyHarness so@@ -666,6 +710,12 @@ public struct HarnessBuiltInToolServices: Sendable {/// captions a video in a single call instead of hand-building and debugging the ffmpeg/SRT plumbing./// nil ⇒ the tool reports unavailable.public var captioner: (@Sendable (HarnessCaptionRequest) async -> HarnessCaptionOutcome)?+ /// PDF text/structured-data extraction behind `pdf.parse`: a PDF in, its text or per-element JSON out.+ /// The runtime supplies an orchestrator that runs the bundled `lit` (liteparse) in-process — resolving+ /// the binary path and PDFIUM_LIB_PATH itself — so the planner reads a PDF through this tool and never+ /// invokes `lit` in a shell. nil ⇒ the tool reports unavailable. Set after construction like the other+ /// injected backends, so it needs no init parameter.+ public var pdfParser: (@Sendable (HarnessPdfParseRequest) async -> HarnessPdfParseOutcome)? = nilpublic init(memoryEntries: [HarnessMemoryEntry] = [],@@ -801,6 +851,8 @@ public enum BuiltInHarnessToolExecutors {return await webAutomate(context, services: services)case "pdf.fill":return await formFill(context, services: services)+ case "pdf.parse":+ return await pdfParse(context, services: services)case "shorts.make":return await shortsMake(context, services: services)case "media.caption":@@ -2527,6 +2579,43 @@ public enum BuiltInHarnessToolExecutors {)}+ /// `pdf.parse` — extract a PDF's text or structured data. The injected orchestrator runs the bundled+ /// `lit` (liteparse) in-process, resolving its path and PDFIUM_LIB_PATH, so the planner never types+ /// `lit` into a shell. OCR is built in, so a scanned PDF reads the same as a digital one.+ private static func pdfParse(+ _ context: HarnessToolExecutionContext,+ services: HarnessBuiltInToolServices+ ) async -> HarnessToolResult {+ guard let parser = services.pdfParser else {+ return failed(context, "PDF parsing is not configured.", reason: "pdfParseUnavailable")+ }+ guard let file = trimmed(context.call.input["file"]) else {+ return invalidInput(context, "pdf.parse requires a `file` — the path to the PDF to read.")+ }+ let workingDirectory = context.worldModel.facts[ConversationWorkspace.baseDirFactKey]+ let request = HarnessPdfParseRequest(+ file: file,+ format: trimmed(context.call.input["format"]),+ pages: trimmed(context.call.input["pages"]),+ noOcr: boolFlag(context.call.input["noOcr"]),+ out: trimmed(context.call.input["out"]),+ workingDirectory: (workingDirectory?.isEmpty == false) ? workingDirectory : nil+ )+ let outcome = await parser(request)+ guard outcome.succeeded else {+ let message = outcome.text.isEmpty ? "The PDF could not be parsed." : outcome.text+ return failed(context, message, reason: "pdfParseFailed", metadata: ["text": message])+ }+ var metadata = ["text": outcome.text]+ if let outPath = outcome.outPath { metadata["filePath"] = outPath }+ return success(+ context,+ summary: outcome.text,+ facts: ["lastAcceptedTool": context.call.name],+ metadata: metadata+ )+ }+/// `shorts.make` — turn a long video into captioned vertical clips end to end. The planner gives the/// source and an optional clip count; the injected orchestrator transcribes on-device, makes ONE bounded/// inference to pick the moments, then cuts/reframes/captions each clip in fixed code and returns thediff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swiftindex 6a193178..f55ee9b6 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessCoordinator.swift@@ -827,7 +827,7 @@ public actor HarnessAgentCoordinator {}guard !parts.isEmpty else { return nil }return "Contents of the small files in your working directory — READ THEM HERE, do not re-open them "- + "with cat/python/lit:\n" + parts.joined(separator: "\n\n")+ + "with cat/python/pdf.parse:\n" + parts.joined(separator: "\n\n")}/// Appends a note to the most recent tool record's summary. The runtime uses this to warn thediff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swiftindex e8e5868c..68f97979 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift@@ -765,6 +765,27 @@ public enum BuiltInHarnessToolCatalog {verification: ["the filled PDF exists and the data values are present in its fields"],metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]),+ descriptor(+ "pdf.parse",+ pluginID: "core.pdf",+ summary: "Read a PDF's contents — text or structured data — from any PDF, digital or scanned (OCR is built in, so there is no separate rasterize/OCR step). Give it the `file`; get the plain text back, or set format=\"json\" for per-element text with layout and bounding boxes (use that for tables or positions). Limit to certain `pages` (e.g. \"1-5,10\"), and set noOcr=\"true\" to skip OCR on a known-digital PDF for speed. For a large document, pass `out` to write the result to a file instead of returning it inline. This is the one and only way to extract a PDF's contents: prefer it over running `lit`/`pdf-fill` yourself.",+ input: [+ "file": "Path to the PDF to read.",+ "format": "\"text\" (default) for plain text, or \"json\" for per-element text with layout/bounding boxes.",+ "pages": "Optional page range to limit extraction, e.g. \"1-5,10\".",+ "noOcr": "Set \"true\" to skip OCR on a known-digital PDF (faster). Omit for scanned PDFs.",+ "out": "Optional output path to write the extracted text/JSON to instead of returning it inline (use for large documents)."+ ],+ output: [+ "text": "The extracted text or JSON, or a short summary when written to a file.",+ "filePath": "Path to the written output, when `out` was given."+ ],+ optionalInputKeys: ["format", "pages", "noOcr", "out"],+ permissions: [],+ safety: .readOnly,+ verification: ["the returned text (or the written output file) holds the PDF's contents"],+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]+ ),descriptor("shorts.make",pluginID: "core.media",diff --git a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swiftindex e9c765d2..4d204b23 100644--- a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift@@ -1041,32 +1041,28 @@ public enum DonkeyCommandBackends {}/// Run a bundled command-line tool (`pdf-fill`, `lit`, …) DIRECTLY by resolving its path in the- /// bundled-tools dir, bypassing the shell so arguments with spaces or `⟦…⟧` need no quoting. Falls- /// back to the bare name through the login-shell PATH when the bundled dir can't be resolved. Uses- /// `shellEnvironment()` so PDFIUM_LIB_PATH and the bundled PATH are set, and runs in `workingDirectory`- /// (else home). Blocking — callers run it off the main actor. Used by `FormFillOrchestrator` so the- /// `pdf.fill` pipeline drives `pdf-fill` without going through the model-facing `shell_exec` gate.+ /// bundled-tools dir, bypassing the shell so arguments with spaces or `⟦…⟧` need no quoting. The+ /// bundled binary is REQUIRED: when it can't be resolved this returns exit 127 with a descriptive+ /// stderr — never a same-named binary off the user's PATH, which would be the wrong build with no+ /// pdfium and is worse than a clean failure. Uses `shellEnvironment()` so PDFIUM_LIB_PATH and the+ /// bundled PATH are set, and runs in `workingDirectory` (else home). Blocking — callers run it off the+ /// main actor. Used by the form/PDF/media orchestrators so a pipeline drives its tool without going+ /// through the model-facing `shell_exec` gate.public static func runBundledTool(_ name: String,_ arguments: [String],workingDirectory: String?) -> (exitCode: Int32, stdout: String, stderr: String) {- let process = Process()- if let directory = bundledToolsDirectory {- let binary = directory.appendingPathComponent(name)- if FileManager.default.isExecutableFile(atPath: binary.path) {- process.executableURL = binary- process.arguments = arguments- }+ guard let directory = bundledToolsDirectory else {+ return (127, "", "Bundled tools directory is unavailable, so '\(name)' cannot run.")}- if process.executableURL == nil {- // No bundled copy — run the bare name through the shell so PATH resolves it.- process.executableURL = URL(fileURLWithPath: "/bin/zsh")- let quoted = ([name] + arguments)- .map { "'" + $0.replacingOccurrences(of: "'", with: "'\\''") + "'" }- .joined(separator: " ")- process.arguments = ["-c", quoted]+ let binary = directory.appendingPathComponent(name)+ guard FileManager.default.isExecutableFile(atPath: binary.path) else {+ return (127, "", "Bundled tool '\(name)' is missing from \(directory.path).")}+ let process = Process()+ process.executableURL = binary+ process.arguments = argumentsprocess.environment = shellEnvironment()process.currentDirectoryURL = resolvedWorkingDirectory(workingDirectory)// Concurrent drain via runProcess: the large `--full` dump on stdout and a verbose error on stderr@@ -1110,6 +1106,15 @@ public enum DonkeyCommandBackends {}}}+ // In a development build (where the baked donkey-tools resource is a symlink),+ // we MUST prioritize it so that local uncommitted changes to native tools are immediately+ // reflected in the app without being shadowed by older downloads in Application Support.+ if let baked = Bundle.main.resourceURL?.appendingPathComponent("donkey-tools", isDirectory: true) {+ let isSymlink = (try? baked.resourceValues(forKeys: [.isSymbolicLinkKey]))?.isSymbolicLink ?? false+ if isSymlink && fileManager.fileExists(atPath: baked.path) {+ return baked+ }+ }let installed = BundledTools.installDirectoryif BundledTools.isInstalled(at: installed) {return installeddiff --git a/apps/Donkey/Sources/DonkeyRuntime/PdfParseOrchestrator.swift b/apps/Donkey/Sources/DonkeyRuntime/PdfParseOrchestrator.swiftnew file mode 100644index 00000000..f884a6a1--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/PdfParseOrchestrator.swift@@ -0,0 +1,83 @@+import DonkeyHarness+import Foundation++/// The deterministic half of `pdf.parse`: resolve the PDF path, run the bundled `lit` (liteparse) in-process+/// via `runBundledTool` — which resolves the binary and sets PDFIUM_LIB_PATH — and hand back the extracted+/// text or JSON. There is NO model call here, and `lit` is never invoked through the model-facing shell, so+/// the planner reads a PDF through one tool and never types `lit` itself.+public struct PdfParseOrchestrator: Sendable {+ public init() {}++ public func parse(_ request: HarnessPdfParseRequest) async -> HarnessPdfParseOutcome {+ 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)++ // The PDF to read may live anywhere the user pointed at (an attachment, a Downloads file); reading is+ // trusted, so the input path is resolved as-is.+ let filePath = Self.resolve(request.file, against: workingDirectory)+ guard fileManager.fileExists(atPath: filePath) else {+ return HarnessPdfParseOutcome(text: "No PDF at \(request.file).", succeeded: false)+ }++ var arguments = ["parse", filePath]+ if request.format?.lowercased() == "json" {+ arguments += ["--format", "json"]+ }+ if let pages = request.pages, !pages.isEmpty {+ arguments += ["--target-pages", pages]+ }+ if request.noOcr {+ arguments.append("--no-ocr")+ }+ // A written output is confined to the workspace: pdf.parse runs without a consent prompt, so its file+ // never lands outside the agent's own folder even if the model passes an absolute or `..` path.+ var outPath: String?+ if let out = request.out, !out.isEmpty {+ let resolved = Self.confine(out, to: workingDirectory)+ arguments += ["-o", resolved]+ outPath = resolved+ }++ let result = DonkeyCommandBackends.runBundledTool("lit", arguments, workingDirectory: workingDirectory)+ guard result.exitCode == 0 else {+ let why = result.stderr.isEmpty ? result.stdout : result.stderr+ return HarnessPdfParseOutcome(text: "Could not parse \(request.file): \(why)", succeeded: false)+ }++ if let outPath {+ guard fileManager.fileExists(atPath: outPath) else {+ return HarnessPdfParseOutcome(text: "lit reported success but wrote no file to \(outPath).", succeeded: false)+ }+ let bytes = (try? fileManager.attributesOfItem(atPath: outPath))?[.size] as? Int+ let size = bytes.map { " (\($0) bytes)" } ?? ""+ return HarnessPdfParseOutcome(+ text: "Parsed \(request.file) → \(outPath)\(size).",+ succeeded: true,+ outPath: outPath+ )+ }++ let text = result.stdout.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !text.isEmpty else {+ return HarnessPdfParseOutcome(text: "Parsed \(request.file) but it produced no text.", succeeded: false)+ }+ return HarnessPdfParseOutcome(text: text, succeeded: true)+ }++ /// Resolve a read path against the working directory — absolute/`~` honored, a bare name lands in the+ /// workspace.+ 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)+ }++ /// Re-root a write path under the workspace, dropping `..`/absolute escapes.+ private static func confine(_ path: String, to workingDirectory: String) -> String {+ let safe = path+ .split(separator: "/", omittingEmptySubsequences: true)+ .filter { $0 != ".." && $0 != "." }+ return safe.reduce(workingDirectory) { ($0 as NSString).appendingPathComponent(String($1)) }+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/pdf/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/pdf/SKILL.mdindex ac53416d..361e381e 100644--- a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/pdf/SKILL.md+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/pdf/SKILL.md@@ -6,17 +6,17 @@ tags: pdf, document, convert, merge, split, ocr, extract, fill, formkeywords: pdf, extract, parse, text, ocr, scan, json, merge, combine, split, extract pages, rotate, convert, docx, rtf, html, fill, form, fillable, acroform, checkboxtools: shell_exec-`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.+`pdf-fill` and `qpdf` are bundled and on the PATH; `textutil` and `mdls` ship with macOS. To read a PDF's text or structured data, use the `pdf.parse` tool — it runs the bundled liteparse and resolves everything for you, so never call `lit` yourself. 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. These bundled tools run without a prompt, and your shell runs in your working directory, so use BARE filenames (`f1120.pdf`, `out.pdf`), never your home root.## 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.-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`.+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 `pdf.parse` (`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; the parse 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 — 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"`. 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`.+## Extract text or structured data — `pdf.parse`+- `pdf.parse` handles both digital and scanned PDFs; OCR is built in, so there is no separate rasterize/OCR step. The bundled liteparse runs inside the tool — never call `lit` yourself.+- Plain text: `pdf.parse` with `file`. Specific pages: add `pages: "1-5,10"`. Skip OCR on a known-digital PDF to go faster: `noOcr: "true"`.+- Structured JSON (per-element text with layout/bounding boxes — for tables or positions): `pdf.parse` with `format: "json"`. For a large document, add `out` to write it to a file instead of returning it inline.- Just a title/metadata lookup: `mdls -name kMDItemTitle in.pdf`.## Restructure and convert@@ -24,5 +24,5 @@ Flat or scanned form (no fillable fields — a page is just printed text or a sc- 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-- `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.+- `pdf.fill` already verifies its own output and reports the applied fields. For an overlay, flatten then `pdf.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/scripts/fetch-bundled-tools.sh b/scripts/fetch-bundled-tools.shindex 6d232bf5..6e7f5cba 100755--- a/scripts/fetch-bundled-tools.sh+++ b/scripts/fetch-bundled-tools.sh@@ -146,9 +146,11 @@ build_lgpl_ffmpeg() {# "could not find pdfium shared library" unless that dylib ships beside it. We stage both here, and the app# (and the evals) point PDFIUM_LIB_PATH at this dir. MANDATORY: the pdf skill's extraction/OCR depends on it.build_liteparse() {- # Require BOTH lit and its pdfium dylib before treating the build as cached — staging only `lit` (the old- # behavior) left PDF parsing broken at runtime.- if [ -x "$VENDOR_DIR/lit" ] && [ -f "$VENDOR_DIR/libpdfium.dylib" ]; then ok "lit (cached)"; return 0; fi+ # Require both the `lit` binary and its pdfium dylib before treating the build as cached.+ if [ -x "$VENDOR_DIR/lit" ] && [ -f "$VENDOR_DIR/libpdfium.dylib" ]; then+ ok "lit (cached)"+ return 0+ filocal ver="2.1.1"command -v cargo >/dev/null 2>&1 || brew install rust >/dev/null 2>&1command -v cmake >/dev/null 2>&1 || brew install cmake >/dev/null 2>&1@@ -166,8 +168,13 @@ build_liteparse() {tail -25 "$root.log" >&2exit 1fi++ # Stage the real binary directly as `lit` — a single signed Mach-O (sign-bundled-tools.sh signs it). It is+ # never invoked through the model's shell; Donkey drives `lit parse` in-process via runBundledTool, which+ # sets PDFIUM_LIB_PATH to the tools dir, so the binary always finds its pdfium without a wrapper.cp -f "$root/bin/lit" "$VENDOR_DIR/lit"chmod +x "$VENDOR_DIR/lit"+# Stage the matching libpdfium.dylib next to `lit` so it loads at runtime via PDFIUM_LIB_PATH. Pick the# NEWEST match (this build's fresh download), not an arbitrary one, in case the cache holds more than one.local pdfium@@ -184,9 +191,8 @@ build_liteparse() {echo "FATAL: staged libpdfium.dylib is not arm64: $(lipo -archs "$VENDOR_DIR/libpdfium.dylib" 2>/dev/null)" >&2exit 1fi- # Smoke-test the PAIR: lit must actually parse a PDF using the staged pdfium. This catches an- # ABI/version mismatch on THIS machine before the bundle ships, instead of every runtime `lit parse`- # crashing later. Uses a committed sample PDF; skipped only if that asset is absent.+ # Smoke-test the PAIR exactly as Donkey runs it: `lit` parses a PDF using the staged pdfium with+ # PDFIUM_LIB_PATH pointed at the tools dir (the env runBundledTool/shellEnvironment set at runtime).local sample="$ROOT_DIR/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/FunctionalEval/merge-pdfs/inputs/a.pdf"if [ -f "$sample" ]; thenif ! PDFIUM_LIB_PATH="$VENDOR_DIR" "$VENDOR_DIR/lit" parse "$sample" --no-ocr >/dev/null 2>"$root.smoke.log"; then@@ -203,7 +209,10 @@ build_liteparse() {# self-contained binary — no dylib bundling. MANDATORY: it is the pdf skill's# headless form-fill/overlay path (litparse reads PDFs; this writes them).build_pdf_fill() {- if [ -x "$VENDOR_DIR/pdf-fill" ]; then ok "pdf-fill (cached)"; return 0; fi+ if [ -x "$VENDOR_DIR/pdf-fill" ] && [ ! "$ROOT_DIR/tools/pdf-fill/main.swift" -nt "$VENDOR_DIR/pdf-fill" ]; then+ ok "pdf-fill (cached)"+ return 0+ ficommand -v swiftc >/dev/null 2>&1 || { echo "FATAL: swiftc unavailable for pdf-fill build" >&2; exit 1; }if ! swiftc -O "$ROOT_DIR/tools/pdf-fill/main.swift" -o "$VENDOR_DIR/pdf-fill" 2>/tmp/pdf-fill-build.log; thenecho "FATAL: pdf-fill build failed; tail of /tmp/pdf-fill-build.log:" >&2@@ -219,7 +228,10 @@ build_pdf_fill() {# result is a single self-contained binary — no dylib bundling. MANDATORY: it is the book# skill's EPUB packaging path (image_render writes the PDF; this writes the .epub).build_epub_pack() {- if [ -x "$VENDOR_DIR/epub-pack" ]; then ok "epub-pack (cached)"; return 0; fi+ if [ -x "$VENDOR_DIR/epub-pack" ] && [ ! "$ROOT_DIR/tools/epub-pack/main.swift" -nt "$VENDOR_DIR/epub-pack" ]; then+ ok "epub-pack (cached)"+ return 0+ ficommand -v swiftc >/dev/null 2>&1 || { echo "FATAL: swiftc unavailable for epub-pack build" >&2; exit 1; }if ! swiftc -O "$ROOT_DIR/tools/epub-pack/main.swift" -o "$VENDOR_DIR/epub-pack" 2>/tmp/epub-pack-build.log; thenecho "FATAL: epub-pack build failed; tail of /tmp/epub-pack-build.log:" >&2@@ -237,7 +249,12 @@ build_epub_pack() {# shipped algorithm is the tested one. MANDATORY: it is the shorts skill's on-device# active-speaker auto-reframe (landscape -> vertical 9:16 that follows whoever is talking).build_reframe() {- if [ -x "$VENDOR_DIR/reframe" ]; then ok "reframe (cached)"; return 0; fi+ if [ -x "$VENDOR_DIR/reframe" ] && \+ [ ! "$ROOT_DIR/tools/reframe/main.swift" -nt "$VENDOR_DIR/reframe" ] && \+ [ ! "$ROOT_DIR/apps/Donkey/Sources/DonkeyRuntime/ReframePlanner.swift" -nt "$VENDOR_DIR/reframe" ]; then+ ok "reframe (cached)"+ return 0+ ficommand -v swiftc >/dev/null 2>&1 || { echo "FATAL: swiftc unavailable for reframe build" >&2; exit 1; }if ! swiftc -O \"$ROOT_DIR/tools/reframe/main.swift" \@@ -332,13 +349,26 @@ log "Signing"# that drops --enable-libass (or a libass build break) would silently cripple every caption# workflow, so verify the now-signed binary and fail the whole run loudly rather than ship it.if [ -x "$VENDOR_DIR/ffmpeg" ]; then- if "$VENDOR_DIR/ffmpeg" -hide_banner -filters 2>/dev/null | grep -qw subtitles; then- ok "ffmpeg libass(subtitles) verified"+ out=$(mktemp)+ err=$(mktemp)+ if "$VENDOR_DIR/ffmpeg" -hide_banner -filters > "$out" 2> "$err"; then+ if grep -qw subtitles "$out"; then+ ok "ffmpeg libass(subtitles) verified"+ else+ echo "FATAL: bundled ffmpeg lacks the libass 'subtitles' filter (subtitle burn-in)." >&2+ echo " It must be built with --enable-libass; see build_libass/build_lgpl_ffmpeg." >&2+ rm -f "$out" "$err"+ exit 1+ fielse- echo "FATAL: bundled ffmpeg lacks the libass 'subtitles' filter (subtitle burn-in)." >&2- echo " It must be built with --enable-libass; see build_libass/build_lgpl_ffmpeg." >&2+ exit_code=$?+ echo "FATAL: bundled ffmpeg failed to execute (exit code: $exit_code)." >&2+ echo " Stderr output:" >&2+ cat "$err" >&2+ rm -f "$out" "$err"exit 1fi+ rm -f "$out" "$err"filog "Summary"