Open source CapCut alternative.
TypeScript
feat(app): bundle CLI tools into the app and add web_snapshot capture
David Le3bf657d9387a
diff --git a/.gitignore b/.gitignoreindex 8ea58060..2a608d4d 100644--- a/.gitignore+++ b/.gitignore@@ -15,5 +15,8 @@ xcuserdata/__pycache__/*.pyc+## Bundled capability tools (large arm64 binaries; fetched by scripts/fetch-bundled-tools.sh)+/vendor/+## Project policy# Keep Package.resolved tracked for reproducible dependency resolution.diff --git a/THIRD-PARTY-LICENSES.md b/THIRD-PARTY-LICENSES.mdnew file mode 100644index 00000000..70cb6d9d--- /dev/null+++ b/THIRD-PARTY-LICENSES.md@@ -0,0 +1,15 @@+# Third-Party Tools Bundled in Donkey++Bundled in `donkey-tools/` (built by `scripts/fetch-bundled-tools.sh`).++| Tool | License | Notes |+|---|---|---|+| ffmpeg | LGPL-2.1 | built `--disable-gpl`, no x264/x265; H.264/HEVC encode via VideoToolbox |+| liteparse (`lit`) | Apache-2.0 | PDF extraction; bundles Tesseract (Apache-2.0) for OCR |+| yt-dlp | Unlicense | |+| qpdf | Apache-2.0 | |+| exiftool | Perl Artistic / GPL-1.0+ | runs via system `/usr/bin/perl` |++Not bundled — used only if the user already has them installed:+- **pandoc** (GPL-3.0): macOS `textutil` covers the common office conversions.+- **ImageMagick** (`magick`): `sips` covers the common image operations.diff --git a/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift b/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swiftindex 5aee6489..ede31cc6 100644--- a/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift+++ b/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift@@ -21,6 +21,7 @@ public enum DonkeyCommandLayer {case appSkill = "app_skill"case appCommands = "app_commands"case skillRun = "skill_run"+ case webSnapshot = "web_snapshot"}public static var descriptors: [HarnessToolDescriptor] {@@ -112,6 +113,22 @@ public enum DonkeyCommandLayer {safetyClass: .guardedInput,verificationHints: ["the script reports a successful structured status"],metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]+ ),+ HarnessToolDescriptor(+ name: Command.webSnapshot.rawValue,+ pluginID: pluginID,+ summary: "Render a web page in a built-in headless browser and save it as a PDF or a full-page PNG — no external browser needed. Use this to capture a page to a file (\"save this page as a PDF\", \"screenshot this page\") when the user does not need to watch it happen. It only reads the page and writes the output file. For static text, prefer `web.fetch` (markdown); for pages behind a login or heavy bot-protection that fail to render here, fall back to the hosted browser tool.",+ inputSchema: [+ "url": "The http(s) page URL to capture.",+ "format": "\"pdf\" (default) or \"png\" (full-page screenshot).",+ "destination": "Optional output file path; defaults to ~/Downloads."+ ],+ optionalInputKeys: ["format", "destination"],+ outputSchema: ["filePath": "Path to the saved PDF or PNG."],+ requiredPermissions: [],+ safetyClass: .readOnly,+ verificationHints: ["the saved file exists and is non-empty"],+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"])]}diff --git a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swiftindex 5ce6f229..3e7fe764 100644--- a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift@@ -2,6 +2,7 @@ import AppKitimport DonkeyContractsimport DonkeyHarnessimport Foundation+import WebKit/// Native implementations for the Donkey Command Layer (`DonkeyCommandLayer`).///@@ -33,9 +34,130 @@ public enum DonkeyCommandBackends {return await appCommands(context)case .skillRun:return await runSkillScript(context)+ case .webSnapshot:+ return await webSnapshot(context)}}+ // MARK: - web_snapshot++ /// Render a URL in an offscreen `WKWebView` and save it as a PDF or full-page+ /// PNG. The free, in-app rung of the web-capture ladder: no external browser,+ /// no hosted service. It only reads the page and writes the output file, so it+ /// runs without consent (like `web.fetch`).+ @MainActor+ private static func webSnapshot(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {+ guard let raw = trimmed(context.call.input["url"]),+ let url = URL(string: raw),+ let scheme = url.scheme?.lowercased(),+ scheme == "http" || scheme == "https" else {+ return invalidInput(context, "web_snapshot requires a valid http(s) `url`.")+ }+ let format = (trimmed(context.call.input["format"]) ?? "pdf").lowercased()+ guard format == "pdf" || format == "png" else {+ return invalidInput(context, "web_snapshot `format` must be \"pdf\" or \"png\".")+ }+ let destination = snapshotDestination(trimmed(context.call.input["destination"]), url: url, format: format)++ // An offscreen window backs the web view so layout and rendering actually+ // run (an unattached WKWebView can snapshot blank).+ let webView = WKWebView(frame: NSRect(x: 0, y: 0, width: 1280, height: 1600))+ let window = NSWindow(+ contentRect: webView.frame,+ styleMask: [.borderless],+ backing: .buffered,+ defer: false+ )+ window.contentView = webView+ let loader = WebSnapshotLoader()+ webView.navigationDelegate = loader++ let loaded = await loader.load(url, in: webView, timeout: 25)+ guard loaded else {+ return failed(context, "Could not load \(url.absoluteString).", reason: "webSnapshotLoadFailed")+ }+ // Give late layout/JS a brief beat to settle before capturing.+ try? await Task.sleep(nanoseconds: 700_000_000)++ do {+ let data = try await (format == "pdf" ? exportPDF(webView) : exportPNG(webView))+ guard !data.isEmpty else {+ return failed(context, "web_snapshot produced an empty \(format).", reason: "webSnapshotEmpty")+ }+ try FileManager.default.createDirectory(+ at: destination.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )+ try data.write(to: destination, options: .atomic)+ } catch {+ return failed(+ context,+ "web_snapshot could not save the \(format): \(error.localizedDescription)",+ reason: "webSnapshotExportFailed"+ )+ }+ withExtendedLifetime(window) {}+ return success(+ context,+ summary: "Saved \(format.uppercased()) of \(url.absoluteString) → \(destination.path)",+ facts: ["webSnapshot.format": format],+ metadata: ["filePath": destination.path, "format": format]+ )+ }++ /// Resolve the output file URL: an explicit `destination` (absolute, or a bare+ /// name placed in ~/Downloads), else a generated `~/Downloads/<host>.<ext>`.+ private static func snapshotDestination(_ destination: String?, url: URL, format: String) -> URL {+ let downloads = FileManager.default.homeDirectoryForCurrentUser+ .appendingPathComponent("Downloads", isDirectory: true)+ if let destination {+ let candidate = (destination as NSString).isAbsolutePath+ ? URL(fileURLWithPath: destination)+ : downloads.appendingPathComponent(destination)+ return candidate.pathExtension.isEmpty+ ? candidate.appendingPathExtension(format)+ : candidate+ }+ let host = url.host?.replacingOccurrences(of: ".", with: "-") ?? "page"+ return downloads.appendingPathComponent("\(host).\(format)")+ }++ @MainActor+ private static func exportPDF(_ webView: WKWebView) async throws -> Data {+ try await withCheckedThrowingContinuation { continuation in+ webView.createPDF(configuration: WKPDFConfiguration()) { result in+ continuation.resume(with: result)+ }+ }+ }++ @MainActor+ private static func exportPNG(_ webView: WKWebView) async throws -> Data {+ // Resize to the full scrollable height so the snapshot captures the whole page.+ if let height = try? await webView.evaluateJavaScript("document.body.scrollHeight") as? CGFloat,+ height > 0 {+ webView.frame.size.height = min(height, 20_000)+ try? await Task.sleep(nanoseconds: 300_000_000)+ }+ let config = WKSnapshotConfiguration()+ config.rect = CGRect(origin: .zero, size: webView.bounds.size)+ let image: NSImage = try await withCheckedThrowingContinuation { continuation in+ webView.takeSnapshot(with: config) { image, error in+ if let image {+ continuation.resume(returning: image)+ } else {+ continuation.resume(throwing: error ?? CocoaError(.fileWriteUnknown))+ }+ }+ }+ guard let tiff = image.tiffRepresentation,+ let rep = NSBitmapImageRep(data: tiff),+ let png = rep.representation(using: .png, properties: [:]) else {+ throw CocoaError(.fileWriteUnknown)+ }+ return png+ }+// MARK: - app_commands/// Surface the app's REAL AppleScript vocabulary from its parsed scripting dictionary, so the@@ -505,6 +627,7 @@ public enum DonkeyCommandBackends {let process = Process()process.executableURL = URL(fileURLWithPath: "/bin/zsh")process.arguments = ["-c", command]+ process.environment = shellEnvironment()let outPipe = Pipe()let errPipe = Pipe()process.standardOutput = outPipe@@ -546,6 +669,35 @@ public enum DonkeyCommandBackends {)}+ /// The bundled command-line tools directory inside the packaged app+ /// (`…/Contents/Resources/donkey-tools`). Skills invoke `ffmpeg`/`yt-dlp` and the+ /// other bundled tools by bare name and rely on this being on the shell PATH.+ /// `nil` in dev/test builds (SwiftPM) where no packaged tools directory exists,+ /// so the environment is left to inherit unchanged there.+ static let bundledToolsDirectory: URL? = {+ guard let dir = Bundle.main.resourceURL?+ .appendingPathComponent("donkey-tools", isDirectory: true),+ FileManager.default.fileExists(atPath: dir.path)+ else {+ return nil+ }+ return dir+ }()++ /// The environment for a `shell_exec` child: the app's environment with the bundled+ /// tools directory appended to PATH. Appended, not prepended, so a tool the user has+ /// installed (e.g. a newer Homebrew `yt-dlp`) still wins, while the bundled copy is the+ /// guaranteed fallback that keeps a capability working with nothing installed. Returns+ /// `nil` when there is no bundled tools directory, so `Process` inherits the environment+ /// exactly as before.+ static func shellEnvironment() -> [String: String]? {+ guard let toolsDirectory = bundledToolsDirectory else { return nil }+ var environment = ProcessInfo.processInfo.environment+ let existing = environment["PATH"] ?? "/usr/bin:/bin:/usr/sbin:/sbin"+ environment["PATH"] = existing + ":" + toolsDirectory.path+ return environment+ }+// MARK: - Result helpersprivate static func success(@@ -599,3 +751,42 @@ public enum DonkeyCommandBackends {return result.isEmpty ? nil : result}}++/// Drives a one-shot `WKWebView` load to completion (or a timeout) for+/// `web_snapshot`. Resolves `true` on `didFinish`, `false` on failure or timeout;+/// the `settled` guard keeps the continuation from resuming twice.+@MainActor+private final class WebSnapshotLoader: NSObject, WKNavigationDelegate {+ private var continuation: CheckedContinuation<Bool, Never>?+ private var settled = false++ func load(_ url: URL, in webView: WKWebView, timeout: TimeInterval) async -> Bool {+ await withCheckedContinuation { continuation in+ self.continuation = continuation+ webView.load(URLRequest(url: url))+ Task { @MainActor in+ try? await Task.sleep(nanoseconds: UInt64(timeout * 1_000_000_000))+ self.settle(false)+ }+ }+ }++ func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {+ settle(true)+ }++ func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {+ settle(false)+ }++ func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {+ settle(false)+ }++ private func settle(_ value: Bool) {+ guard !settled else { return }+ settled = true+ continuation?.resume(returning: value)+ continuation = nil+ }+}diff --git a/scripts/fetch-bundled-tools.sh b/scripts/fetch-bundled-tools.shnew file mode 100755index 00000000..3d905659--- /dev/null+++ b/scripts/fetch-bundled-tools.sh@@ -0,0 +1,173 @@+#!/usr/bin/env bash+#+# Vendors the arm64 command-line tools that Donkey's capability skills use into+# vendor/donkey-tools/, making each binary self-contained (its Homebrew dylibs are+# copied alongside and the install names are rewritten to @loader_path). The+# packaging step (scripts/package-donkey-app.sh -> stage_bundled_tools) then copies+# this directory into Donkey.app/Contents/Resources/donkey-tools/.+#+# The vendored binaries are large (~250MB) and are NOT committed to git — run this+# on the build machine before packaging. Re-runnable; each tool is independent, so+# one failure does not abort the rest.+#+# Requires: Homebrew, dylibbundler (installed automatically), network access.+set -uo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"+VENDOR_DIR="$ROOT_DIR/vendor/donkey-tools"+BREW_LIB="$(brew --prefix 2>/dev/null)/lib"++mkdir -p "$VENDOR_DIR"+STATUS=()++log() { printf '\n==> %s\n' "$*"; }+ok() { STATUS+=("OK $1"); }+fail(){ STATUS+=("FAIL $1 ($2)"); echo " ! $1: $2" >&2; }++ensure_brew_tool() {+ # $1 = formula, $2 = binary name to check+ command -v "$2" >/dev/null 2>&1 && return 0+ log "brew install $1"+ brew install "$1" >/dev/null 2>&1+}++# Extra dylib search dirs (besides Homebrew's lib) for the next bundle() call.+EXTRA_SEARCH=()++# Copy a binary into the vendor dir and bundle its dylibs flat (so @loader_path,+# which is relative to each file's own directory, resolves for binary->lib and+# lib->lib alike).+bundle() {+ # $1 = absolute source binary, $2 = vendored name+ local src="$1" name="$2"+ [ -f "$src" ] || { fail "$name" "source not found: $src"; return 1; }+ cp -f "$src" "$VENDOR_DIR/$name"+ chmod +x "$VENDOR_DIR/$name"+ local search=(--search-path "$BREW_LIB")+ local dir+ for dir in "${EXTRA_SEARCH[@]:-}"; do [ -n "$dir" ] && search+=(--search-path "$dir"); done+ dylibbundler --overwrite-files --bundle-deps --fix-file "$VENDOR_DIR/$name" \+ --dest-dir "$VENDOR_DIR" --install-path "@loader_path/" "${search[@]}" \+ >/dev/null 2>&1+ ok "$name"+}++# Build a TRUE LGPL ffmpeg from source — no --enable-gpl, no x264/x265. H.264/HEVC+# encode comes from Apple VideoToolbox; decode is built in; mp3 via LGPL libmp3lame,+# opus via BSD libopus, AV1 decode via BSD dav1d. Built shared, then dylibbundled.+# ffmpeg is MANDATORY: any failure here aborts the whole vendoring run, because a+# bundle without ffmpeg is not shippable.+build_lgpl_ffmpeg() {+ local ver="7.1.1"+ local work="/tmp/ffmpeg-lgpl-build"+ local brew_prefix; brew_prefix="$(brew --prefix)"+ command -v nasm >/dev/null 2>&1 || brew install nasm >/dev/null 2>&1+ command -v pkg-config >/dev/null 2>&1 || brew install pkg-config >/dev/null 2>&1+ local dep+ for dep in lame opus dav1d; do+ brew list "$dep" >/dev/null 2>&1 || brew install "$dep" >/dev/null 2>&1+ done+ rm -rf "$work"; mkdir -p "$work"+ curl -fsSL -o "$work/ffmpeg.tar.xz" "https://ffmpeg.org/releases/ffmpeg-${ver}.tar.xz" \+ || { echo "FATAL: ffmpeg source download failed" >&2; exit 1; }+ tar -xJf "$work/ffmpeg.tar.xz" -C "$work" --strip-components=1+ ( cd "$work" \+ && PKG_CONFIG_PATH="$brew_prefix/lib/pkgconfig:$brew_prefix/share/pkgconfig" \+ ./configure --prefix="$work/out" \+ --disable-gpl --disable-nonfree --disable-doc --disable-static --enable-shared \+ --enable-videotoolbox --enable-audiotoolbox \+ --enable-libmp3lame --enable-libopus --enable-libdav1d \+ --extra-cflags="-I$brew_prefix/include" --extra-ldflags="-L$brew_prefix/lib" \+ && make -j"$(sysctl -n hw.ncpu)" \+ && make install ) >"$work/build.log" 2>&1+ if [ ! -x "$work/out/bin/ffmpeg" ] || [ ! -x "$work/out/bin/ffprobe" ]; then+ echo "FATAL: LGPL ffmpeg build failed; tail of $work/build.log:" >&2+ tail -25 "$work/build.log" >&2+ exit 1+ fi+ EXTRA_SEARCH=("$work/out/lib")+ bundle "$work/out/bin/ffmpeg" ffmpeg+ bundle "$work/out/bin/ffprobe" ffprobe+ EXTRA_SEARCH=()+}++# Build liteparse's `lit` from source (Rust). It static-links leptonica+tesseract,+# so the result is a single self-contained binary (system libs only — no dylib+# bundling). MANDATORY: the pdf skill's extraction/OCR depends on it, and it+# replaces a separate tesseract.+build_liteparse() {+ command -v cargo >/dev/null 2>&1 || brew install rust >/dev/null 2>&1+ command -v cmake >/dev/null 2>&1 || brew install cmake >/dev/null 2>&1+ command -v cargo >/dev/null 2>&1 || { echo "FATAL: cargo unavailable for liteparse build" >&2; exit 1; }+ local root="/tmp/liteparse-build"+ rm -rf "$root"+ PKG_CONFIG_PATH="$(brew --prefix)/lib/pkgconfig" cargo install liteparse --root "$root" >"$root.log" 2>&1+ if [ ! -x "$root/bin/lit" ]; then+ echo "FATAL: liteparse (lit) build failed; tail of $root.log:" >&2+ tail -25 "$root.log" >&2+ exit 1+ fi+ cp -f "$root/bin/lit" "$VENDOR_DIR/lit"+ chmod +x "$VENDOR_DIR/lit"+ ok "lit"+}++log "Ensuring dylibbundler"+command -v dylibbundler >/dev/null 2>&1 || brew install dylibbundler >/dev/null 2>&1++# --- ffmpeg + ffprobe: mandatory, built LGPL from source (see build_lgpl_ffmpeg) ---+build_lgpl_ffmpeg++# --- liteparse `lit`: mandatory, built from source (self-contained, includes OCR) ---+build_liteparse++# --- qpdf (Homebrew) ---+if ensure_brew_tool qpdf qpdf; then+ bundle "$(brew --prefix qpdf)/bin/qpdf" qpdf+fi++# pandoc is intentionally NOT bundled. macOS's built-in `textutil` already converts+# among txt/html/rtf/doc/docx/odt (the common office formats), so the ~180MB pandoc+# binary isn't worth shipping. The `pdf` skill leads with textutil and uses pandoc+# only when the user happens to have it installed (markdown/LaTeX/EPUB).+#+# tesseract is no longer bundled separately: `lit` (liteparse) static-links its own+# Tesseract and is the pdf skill's extraction/OCR path.++# --- ImageMagick `magick` is intentionally NOT bundled. It loads coder modules+# (PNG/JPEG/etc.) and configuration at runtime from its install tree, which+# dylibbundler cannot relocate — a bundled copy fails with "no decode delegate".+# The `images` skill leads with `sips` (always present) and treats magick as an+# optional tool used only when the user has it installed. ---++# --- yt-dlp: official self-contained macOS build (bundles its own Python) ---+log "Downloading yt-dlp"+if curl -fsSL -o "$VENDOR_DIR/yt-dlp" \+ "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos"; then+ chmod +x "$VENDOR_DIR/yt-dlp"+ ok "yt-dlp"+else+ fail "yt-dlp" "download failed"+fi++# --- exiftool: standalone Perl distribution, runs via system /usr/bin/perl ---+log "Downloading exiftool"+if curl -fsSL -o /tmp/exiftool.tar.gz \+ "https://github.com/exiftool/exiftool/archive/refs/heads/master.tar.gz"; then+ rm -rf /tmp/exiftool-src "$VENDOR_DIR/exiftool" "$VENDOR_DIR/lib/Image"+ mkdir -p /tmp/exiftool-src+ tar -xzf /tmp/exiftool.tar.gz -C /tmp/exiftool-src --strip-components=1+ cp /tmp/exiftool-src/exiftool "$VENDOR_DIR/exiftool"+ chmod +x "$VENDOR_DIR/exiftool"+ mkdir -p "$VENDOR_DIR/lib"+ cp -R /tmp/exiftool-src/lib/. "$VENDOR_DIR/lib/"+ ok "exiftool"+else+ fail "exiftool" "download failed"+fi++log "Summary"+printf '%s\n' "${STATUS[@]}"+echo+echo "Vendored into: $VENDOR_DIR"diff --git a/scripts/package-donkey-app.sh b/scripts/package-donkey-app.shindex 8483d81e..82b861e1 100755--- a/scripts/package-donkey-app.sh+++ b/scripts/package-donkey-app.sh@@ -190,6 +190,34 @@ cd "$BUILD_DIR"echo "Compiling Donkey for Mac ..."swift build -c release --product Donkey+# Stage the bundled command-line tools (yt-dlp, ffmpeg, pandoc, qpdf, exiftool,+# tesseract, magick) into the app so the capability skills work with nothing+# installed. The arm64 binaries are NOT committed to the repo; point+# DONKEY_TOOLS_DIR at a directory containing them (default: vendor/donkey-tools).+# When that directory is absent this is a no-op, so a normal build still succeeds+# and the skills fall back to whatever the user has installed.+stage_bundled_tools() {+ local source_dir="${DONKEY_TOOLS_DIR:-$ROOT_DIR/vendor/donkey-tools}"+ if [ ! -d "$source_dir" ]; then+ echo "No bundled tools at $source_dir; skipping (capability skills will use installed tools)."+ return 0+ fi+ local dest_dir="$RESOURCES_DIR/donkey-tools"+ rm -rf "$dest_dir"+ mkdir -p "$dest_dir"+ cp -R "$source_dir/." "$dest_dir/"+ # Ad-hoc sign each executable so the outer --deep sign stays consistent. Release+ # builds re-sign these with Developer ID + hardened runtime and notarize the DMG+ # (see docs/guides/releasing-donkey.md); a non-Mach-O script just no-ops here.+ if command -v codesign >/dev/null 2>&1; then+ find "$dest_dir" -type f -perm -u+x -print0 | while IFS= read -r -d '' tool; do+ chmod +x "$tool"+ codesign --force --sign - "$tool" >/dev/null 2>&1 || true+ done+ fi+ echo "Staged bundled tools from $source_dir into $dest_dir."+}+rm -rf "$APP_DIR"mkdir -p "$MACOS_DIR" "$RESOURCES_DIR" "$FRAMEWORKS_DIR"cp "$EXECUTABLE" "$MACOS_DIR/Donkey"@@ -220,6 +248,8 @@ if [ -n "$SPARKLE_FRAMEWORK" ]; thencp -R "$SPARKLE_FRAMEWORK" "$FRAMEWORKS_DIR/"fi+stage_bundled_tools+SPARKLE_PLIST_KEYS=""if [ -n "$SPARKLE_FEED_URL" ] && [ -n "$SPARKLE_PUBLIC_ED_KEY" ]; thenSPARKLE_PLIST_KEYS=" <key>SUEnableInstallerLauncherService</key>