Skip to content

Open source CapCut alternative.

TypeScript

feat(app): generative video and code-rendered images

David Leb4d80bfbced8
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedImageGenerator.swift b/apps/Donkey/Sources/DonkeyAI/HostedImageGenerator.swift
index 74801053..bf0bcc4a 100644
--- a/apps/Donkey/Sources/DonkeyAI/HostedImageGenerator.swift
+++ b/apps/Donkey/Sources/DonkeyAI/HostedImageGenerator.swift
@@ -64,7 +64,8 @@ public struct HostedImageGenerator: Sendable {
)
let outputDirectory = Self.resolvedOutputDirectory(
request.outputDirectory,
- inputImagePaths: request.inputImagePaths
+ inputImagePaths: request.inputImagePaths,
+ workspaceBaseDir: request.workspaceBaseDir
)
let backend = self.backend
@@ -118,28 +119,33 @@ public struct HostedImageGenerator: Sendable {
}
/// Resolves where outputs are written. An absolute `outDir` is used as-is; a relative one resolves
- /// against the source image's folder (so "edited" lands next to the source) or, with no source,
- /// against Downloads. With no `outDir`, an edit writes next to its source and a generation writes
- /// to Downloads. Outputs are written FLAT into this directory (no per-generation nesting).
+ /// against the source image's folder (so "edited" lands next to the source) or, with no source, against
+ /// the base. With no `outDir`, an edit writes next to its source and a generation writes to the base.
+ /// The base is the conversation workspace folder when one exists, else Downloads — so generated images
+ /// and clips collect with the turn's other deliverables instead of scattering into Downloads. Outputs
+ /// are written FLAT into this directory (no per-generation nesting).
static func resolvedOutputDirectory(
_ outDir: String?,
- inputImagePaths: [String]
+ inputImagePaths: [String],
+ workspaceBaseDir: String?
) -> URL {
let fileManager = FileManager.default
let sourceDir = inputImagePaths.first.map { path in
URL(fileURLWithPath: (path as NSString).expandingTildeInPath).deletingLastPathComponent()
}
- let downloads = fileManager.homeDirectoryForCurrentUser
- .appendingPathComponent("Downloads", isDirectory: true)
+ let base = workspaceBaseDir.flatMap { dir -> URL? in
+ let trimmed = dir.trimmingCharacters(in: .whitespaces)
+ return trimmed.isEmpty ? nil : URL(fileURLWithPath: (trimmed as NSString).expandingTildeInPath, isDirectory: true)
+ } ?? fileManager.homeDirectoryForCurrentUser.appendingPathComponent("Downloads", isDirectory: true)
guard let outDir, !outDir.trimmingCharacters(in: .whitespaces).isEmpty else {
- return sourceDir ?? downloads
+ return sourceDir ?? base
}
let expanded = (outDir as NSString).expandingTildeInPath
if expanded.hasPrefix("/") {
return URL(fileURLWithPath: expanded, isDirectory: true)
}
- return (sourceDir ?? downloads).appendingPathComponent(expanded, isDirectory: true)
+ return (sourceDir ?? base).appendingPathComponent(expanded, isDirectory: true)
}
private static func failureReason(from record: RemoteInferenceGenerationRecord) -> String {
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedVideoGenerator.swift b/apps/Donkey/Sources/DonkeyAI/HostedVideoGenerator.swift
new file mode 100644
index 00000000..b7666f35
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/HostedVideoGenerator.swift
@@ -0,0 +1,170 @@
+import DonkeyContracts
+import DonkeyHarness
+import Foundation
+
+/// The model boundary behind the generic `video.generate` harness tool. It encodes an optional
+/// first-frame image, asks the hosted asset API for a video generation (provider AND model unset, so
+/// the backend routes to its configured video model — Veo), then polls until the clip is ready and
+/// writes the output file(s) to disk — keeping every provider/model detail behind the backend.
+///
+/// Video generation is a long-running job: the backend submits it and returns `inProgress` with an
+/// operation handle, and this poll loop drives `refreshAssetGeneration` until it completes. The budget
+/// is far larger than the image generator's because Veo takes minutes, not the near-instant image path.
+public struct HostedVideoGenerator: Sendable {
+ private let backend: DonkeyBackendInferenceClient
+ private let timeoutSeconds: TimeInterval
+ private let maxPixelSize: Int
+ private let maxPollAttempts: Int
+ private let pollIntervalSeconds: UInt64
+
+ public init(
+ backend: DonkeyBackendInferenceClient,
+ // Veo clips usually land in 30s–2min, but a cold/queued job can run longer; bound the whole
+ // call so the harness step can't hang while still giving a slow generation room to finish.
+ timeoutSeconds: TimeInterval = 660,
+ maxPixelSize: Int = 4_096,
+ maxPollAttempts: Int = 120,
+ pollIntervalSeconds: UInt64 = 5
+ ) {
+ self.backend = backend
+ self.timeoutSeconds = timeoutSeconds
+ self.maxPixelSize = maxPixelSize
+ self.maxPollAttempts = maxPollAttempts
+ self.pollIntervalSeconds = pollIntervalSeconds
+ }
+
+ public func generate(
+ _ request: HarnessVideoGenerationRequest
+ ) async -> HarnessVideoGenerationResult? {
+ // Encode the optional first-frame image (image-to-video). An unreadable path is fatal only
+ // when one was explicitly supplied — a plain text-to-video request carries none. The image
+ // tool's encoder is reused so the wire shape (inputs.images = [{ data, mimeType }]) matches
+ // what the backend video adapter already parses.
+ var inputs: RemoteInferenceJSONObject = [:]
+ if let sourcePath = request.inputImagePaths.first {
+ guard let encoded = HostedImageGenerator.encodedSourceImage(
+ atPath: sourcePath,
+ maxPixelSize: maxPixelSize
+ ) else {
+ return HarnessVideoGenerationResult(
+ savedPaths: [],
+ failureReason: "Could not read the source image at \(sourcePath)."
+ )
+ }
+ inputs["images"] = .array([
+ .object([
+ "data": .string(encoded.base64),
+ "mimeType": .string(encoded.mimeType)
+ ])
+ ])
+ }
+
+ let trimmedModel = request.model?.trimmingCharacters(in: .whitespaces)
+ let assetRequest = RemoteInferenceAssetGenerationRequest(
+ kind: .video,
+ provider: nil,
+ model: (trimmedModel?.isEmpty == false) ? trimmedModel : nil,
+ prompt: request.prompt,
+ inputs: inputs,
+ parameters: Self.parameters(from: request),
+ metadata: ["source": "video-tool"]
+ )
+ let outputDirectory = HostedImageGenerator.resolvedOutputDirectory(
+ request.outputDirectory,
+ inputImagePaths: request.inputImagePaths,
+ workspaceBaseDir: request.workspaceBaseDir
+ )
+
+ let backend = self.backend
+ let maxPollAttempts = self.maxPollAttempts
+ let pollIntervalSeconds = self.pollIntervalSeconds
+ do {
+ return try await AIDeadline.enforce(seconds: timeoutSeconds) {
+ () -> HarnessVideoGenerationResult in
+ var record = try await backend.createAssetGeneration(assetRequest)
+ var attempts = 0
+ while record.status == .pending || record.status == .inProgress, attempts < maxPollAttempts {
+ attempts += 1
+ try await Task.sleep(nanoseconds: pollIntervalSeconds * 1_000_000_000)
+ do {
+ record = try await backend.refreshAssetGeneration(record)
+ } catch {
+ // A transient refresh error shouldn't abort an in-flight generation — keep
+ // polling until it resolves or the attempt budget runs out.
+ continue
+ }
+ }
+ guard record.status == .completed else {
+ return HarnessVideoGenerationResult(
+ savedPaths: [],
+ failureReason: Self.failureReason(from: record)
+ )
+ }
+ let saved = await backend.writeOutputsFlat(record.outputs, to: outputDirectory) { index, _ in
+ "video-\(index).mp4"
+ }
+ return HarnessVideoGenerationResult(
+ savedPaths: saved,
+ failureReason: saved.isEmpty ? "The video model returned no video." : nil
+ )
+ }
+ } catch let error where DonkeyCreditExhaustion.isExhausted(error) {
+ return HarnessVideoGenerationResult(
+ savedPaths: [],
+ failureReason: DonkeyCreditExhaustion.userMessage()
+ )
+ } catch {
+ return HarnessVideoGenerationResult(
+ savedPaths: [],
+ failureReason: "Video generation timed out or could not reach the model."
+ )
+ }
+ }
+
+ /// Maps the typed Veo knobs onto the provider-neutral `parameters` object the backend video
+ /// adapter reads. Omitted fields are left out so the model/back-end default stays in place.
+ private static func parameters(
+ from request: HarnessVideoGenerationRequest
+ ) -> RemoteInferenceJSONObject {
+ var parameters: RemoteInferenceJSONObject = [:]
+ if let tier = request.tier?.trimmingCharacters(in: .whitespaces), !tier.isEmpty {
+ parameters["tier"] = .string(tier)
+ }
+ if let audio = request.audio {
+ parameters["generateAudio"] = .bool(audio)
+ }
+ if let aspectRatio = request.aspectRatio?.trimmingCharacters(in: .whitespaces),
+ !aspectRatio.isEmpty {
+ parameters["aspectRatio"] = .string(aspectRatio)
+ }
+ if let durationSeconds = request.durationSeconds {
+ parameters["durationSeconds"] = .number(Double(durationSeconds))
+ }
+ if let negativePrompt = request.negativePrompt?.trimmingCharacters(in: .whitespaces),
+ !negativePrompt.isEmpty {
+ parameters["negativePrompt"] = .string(negativePrompt)
+ }
+ return parameters
+ }
+
+ private static func failureReason(from record: RemoteInferenceGenerationRecord) -> String {
+ if let detail = errorText(record.error) {
+ return "Video generation \(record.status.rawValue): \(detail)"
+ }
+ return "Video generation \(record.status.rawValue)."
+ }
+
+ private static func errorText(_ value: RemoteInferenceJSONValue?) -> String? {
+ switch value {
+ case .string(let text):
+ return text
+ case .object(let object):
+ if case .string(let message)? = object["message"] {
+ return message
+ }
+ return nil
+ default:
+ return nil
+ }
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift b/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift
index bfcece18..1feed79c 100644
--- a/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift
@@ -22,6 +22,7 @@ public enum DonkeyCommandLayer {
case appCommands = "app_commands"
case skillRun = "skill_run"
case webSnapshot = "web_snapshot"
+ case imageRender = "image_render"
}
public static var descriptors: [HarnessToolDescriptor] {
@@ -121,7 +122,7 @@ public enum DonkeyCommandLayer {
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."
+ "destination": "Optional output name. A relative name or subfolder (e.g. assets/page.pdf) lands in the conversation's workspace folder; this runs without consent, so the output always stays inside that folder (else ~/Downloads) — absolute or .. paths are re-rooted there, not written elsewhere. Omit to save to the workspace, else ~/Downloads."
],
optionalInputKeys: ["format", "destination"],
outputSchema: ["filePath": "Path to the saved PDF or PNG."],
@@ -129,6 +130,24 @@ public enum DonkeyCommandLayer {
safetyClass: .readOnly,
verificationHints: ["the saved file exists and is non-empty"],
metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]
+ ),
+ HarnessToolDescriptor(
+ name: Command.imageRender.rawValue,
+ pluginID: pluginID,
+ summary: "Render HTML/SVG markup YOU write into a crisp PNG (or PDF) image, using the same built-in headless browser as web_snapshot. This is how you CREATE an image of text or data — an infographic, diagram, chart, standings/bracket, poster, card, certificate, or any explanatory graphic about any topic. Unlike image.generate (a generative model that garbles text and numbers), this renders your exact markup, so every label and value is sharp and you control the whole layout. Write one self-contained HTML document (inline CSS, system fonts, inline <svg> for shapes, data: URIs for any images), then pass it here. Follow the `design` skill for how to make it look good. It only renders your markup and writes the output file, so it runs without consent.",
+ inputSchema: [
+ "html": "A complete, self-contained HTML (or SVG) document to render. Inline all CSS; use system fonts; remote fonts/images are not loaded (embed images as data: URIs).",
+ "width": "Canvas width in pixels (default 1200, 200–4000). Author your layout to this width.",
+ "height": "Optional canvas height in pixels (200–8000). Omit to fit the content's natural height.",
+ "format": "\"png\" (default) or \"pdf\".",
+ "destination": "Optional output name. A relative name or subfolder (e.g. charts/q3.png) lands in the conversation's workspace folder; this runs without consent, so the output always stays inside that folder (else ~/Downloads) — absolute or .. paths are re-rooted there, not written elsewhere. Omit to save to the workspace, else ~/Downloads."
+ ],
+ optionalInputKeys: ["width", "height", "format", "destination"],
+ outputSchema: ["filePath": "Path to the saved PNG or PDF."],
+ 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.swift
index ad09d314..550317f8 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift
@@ -36,6 +36,8 @@ public enum DonkeyCommandBackends {
return await runSkillScript(context)
case .webSnapshot:
return await webSnapshot(context)
+ case .imageRender:
+ return await imageRender(context)
}
}
@@ -57,7 +59,12 @@ public enum DonkeyCommandBackends {
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)
+ let destination = snapshotDestination(
+ trimmed(context.call.input["destination"]),
+ url: url,
+ format: format,
+ baseDir: workspaceBaseDir(context)
+ )
// An offscreen window backs the web view so layout and rendering actually
// run (an unattached WKWebView can snapshot blank).
@@ -105,24 +112,16 @@ public enum DonkeyCommandBackends {
)
}
- /// Resolve the output file URL inside ~/Downloads. A `destination` is treated as
- /// a file *name* only — any directory components are stripped — so this no-consent
- /// capture tool can never overwrite a file outside Downloads. Falls back to a
- /// generated `<host>.<ext>` name.
- private static func snapshotDestination(_ destination: String?, url: URL, format: String) -> URL {
- let downloads = FileManager.default.homeDirectoryForCurrentUser
- .appendingPathComponent("Downloads", isDirectory: true)
- if let destination {
- let name = (destination as NSString).lastPathComponent
- if !name.isEmpty {
- let candidate = downloads.appendingPathComponent(name)
- return candidate.pathExtension.isEmpty
- ? candidate.appendingPathExtension(format)
- : candidate
- }
- }
+ /// Resolve the output file URL for `web_snapshot`. Defaults the file name to `<host>.<ext>` and
+ /// resolves through the shared workspace-aware rule (see `resolveOutputDestination`).
+ private static func snapshotDestination(
+ _ destination: String?,
+ url: URL,
+ format: String,
+ baseDir: String?
+ ) -> URL {
let host = url.host?.replacingOccurrences(of: ".", with: "-") ?? "page"
- return downloads.appendingPathComponent("\(host).\(format)")
+ return resolveOutputDestination(destination, baseDir: baseDir, format: format, defaultName: host)
}
@MainActor
@@ -163,6 +162,171 @@ public enum DonkeyCommandBackends {
}
}
+ // MARK: - image_render
+
+ /// Render model-authored HTML/SVG markup into a PNG (or PDF) using the same offscreen
+ /// `WKWebView` path as `web_snapshot`. This is the reliable way to CREATE an image of text
+ /// or data — an infographic, diagram, chart, poster — because the markup is rendered exactly,
+ /// so labels and numbers stay sharp (a generative image model would garble them). Like
+ /// `web_snapshot` it only renders and writes a file, so it runs without consent. The output lands in
+ /// the conversation workspace (or ~/Downloads when none is set yet); see `resolveOutputDestination`.
+ @MainActor
+ private static func imageRender(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {
+ guard let html = trimmed(context.call.input["html"]) else {
+ return invalidInput(context, "image_render requires `html` — the HTML/SVG markup to render.")
+ }
+ let format = (trimmed(context.call.input["format"]) ?? "png").lowercased()
+ guard format == "png" || format == "pdf" else {
+ return invalidInput(context, "image_render `format` must be \"png\" or \"pdf\".")
+ }
+ let width = dimension(context.call.input["width"], lower: 200, upper: 4000) ?? 1200
+ let fixedHeight = dimension(context.call.input["height"], lower: 200, upper: 8000)
+ let destination = renderDestination(
+ trimmed(context.call.input["destination"]),
+ format: format,
+ baseDir: workspaceBaseDir(context)
+ )
+
+ // An offscreen window backs the web view so layout and rendering actually run.
+ let webView = WKWebView(frame: NSRect(x: 0, y: 0, width: width, height: fixedHeight ?? 800))
+ 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.loadHTML(html, in: webView, timeout: 20)
+ guard loaded else {
+ return failed(context, "image_render could not render the provided markup.", reason: "imageRenderLoadFailed")
+ }
+ // Give late layout (fonts, inline SVG) a brief beat to settle before capturing.
+ try? await Task.sleep(nanoseconds: 500_000_000)
+
+ do {
+ let data = try await (format == "pdf"
+ ? exportPDF(webView)
+ : exportRenderedPNG(webView, width: width, fixedHeight: fixedHeight))
+ guard !data.isEmpty else {
+ return failed(context, "image_render produced an empty \(format).", reason: "imageRenderEmpty")
+ }
+ try FileManager.default.createDirectory(
+ at: destination.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
+ try data.write(to: destination, options: .atomic)
+ } catch {
+ return failed(
+ context,
+ "image_render could not save the \(format): \(error.localizedDescription)",
+ reason: "imageRenderExportFailed"
+ )
+ }
+ withExtendedLifetime(window) {}
+ return success(
+ context,
+ summary: "Rendered \(format.uppercased()) → \(destination.path)",
+ facts: ["imageRender.format": format],
+ metadata: ["filePath": destination.path, "format": format]
+ )
+ }
+
+ /// Snapshot the rendered markup at the authored width. Height is the caller's fixed value when
+ /// given, else the content's natural height (capped) — so an infographic renders at its designed
+ /// size instead of a giant scrolling page.
+ @MainActor
+ private static func exportRenderedPNG(_ webView: WKWebView, width: CGFloat, fixedHeight: CGFloat?) async throws -> Data {
+ let height: CGFloat
+ if let fixedHeight {
+ height = fixedHeight
+ } else if let measured = try? await webView.evaluateJavaScript("document.body.scrollHeight") as? CGFloat,
+ measured > 0 {
+ height = min(measured, 8000)
+ } else {
+ height = webView.bounds.size.height
+ }
+ webView.frame.size = CGSize(width: width, height: height)
+ try? await Task.sleep(nanoseconds: 200_000_000)
+ let config = WKSnapshotConfiguration()
+ config.rect = CGRect(origin: .zero, size: webView.bounds.size)
+ // Convert to PNG inside the completion handler so the non-Sendable NSImage never
+ // crosses the continuation boundary.
+ return try await withCheckedThrowingContinuation { continuation in
+ webView.takeSnapshot(with: config) { image, error in
+ guard let image else {
+ continuation.resume(throwing: error ?? CocoaError(.fileWriteUnknown))
+ return
+ }
+ guard let tiff = image.tiffRepresentation,
+ let rep = NSBitmapImageRep(data: tiff),
+ let png = rep.representation(using: .png, properties: [:]) else {
+ continuation.resume(throwing: CocoaError(.fileWriteUnknown))
+ return
+ }
+ continuation.resume(returning: png)
+ }
+ }
+ }
+
+ /// Resolve the output file for `image_render`. Defaults the file name to `image.<ext>` and resolves
+ /// through the shared workspace-aware rule (see `resolveOutputDestination`).
+ private static func renderDestination(_ destination: String?, format: String, baseDir: String?) -> URL {
+ resolveOutputDestination(destination, baseDir: baseDir, format: format, defaultName: "image")
+ }
+
+ /// The conversation workspace's current directory, if the runtime has set one. Read from the typed
+ /// fact the harness maintains — never from user text.
+ private static func workspaceBaseDir(_ context: HarnessToolExecutionContext) -> String? {
+ let value = context.worldModel.facts[ConversationWorkspace.baseDirFactKey]
+ return (value?.isEmpty == false) ? value : nil
+ }
+
+ /// Shared destination rule for the no-consent capture/render tools (`image_render`, `web_snapshot`).
+ ///
+ /// The result is ALWAYS inside `base` — the conversation workspace `baseDir` when one exists, else
+ /// `~/Downloads`. These tools run with no permission prompt and their `destination` can be steered by
+ /// content they capture (an injected page or document), so the path must never escape a user directory.
+ /// Subfolders survive (`assets/chart.png`), but `..` traversal and absolute paths are re-rooted under
+ /// `base` rather than honored — escape is impossible by construction. A nil/empty `destination`
+ /// becomes `<base>/<defaultName>.<format>`.
+ static func resolveOutputDestination(
+ _ destination: String?,
+ baseDir: String?,
+ format: String,
+ defaultName: String
+ ) -> URL {
+ let base: URL = {
+ if let baseDir, !baseDir.isEmpty {
+ return URL(fileURLWithPath: (baseDir as NSString).expandingTildeInPath, isDirectory: true)
+ }
+ return FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent("Downloads", isDirectory: true)
+ }()
+ func ensuringExtension(_ url: URL) -> URL {
+ url.pathExtension.isEmpty ? url.appendingPathExtension(format) : url
+ }
+ // Keep only the non-traversal path components and re-root them under `base`, so no destination —
+ // relative, absolute, or `..`-laden — can resolve outside `base`.
+ let safeComponents = (destination ?? "")
+ .split(separator: "/", omittingEmptySubsequences: true)
+ .filter { $0 != ".." && $0 != "." }
+ guard !safeComponents.isEmpty else {
+ return base.appendingPathComponent("\(defaultName).\(format)")
+ }
+ let confined = safeComponents.reduce(base) { $0.appendingPathComponent(String($1)) }
+ return ensuringExtension(confined)
+ }
+
+ /// Parse a pixel dimension from a string input, clamped to `[lower, upper]`; `nil` when absent or
+ /// not a number.
+ private static func dimension(_ value: String?, lower: CGFloat, upper: CGFloat) -> CGFloat? {
+ guard let value = trimmed(value), let number = Double(value) else { return nil }
+ return Swift.min(Swift.max(CGFloat(number), lower), upper)
+ }
+
// MARK: - app_commands
/// Surface the app's REAL AppleScript vocabulary from its parsed scripting dictionary, so the
@@ -508,7 +672,16 @@ public enum DonkeyCommandBackends {
/// the model must know it saw a prefix, not the whole output.
private static func boundedOutput(_ output: String) -> (text: String, truncated: Bool) {
guard output.count > shellOutputMaxLength else { return (output, false) }
- return (String(output.prefix(shellOutputMaxLength)) + "\n… [output truncated]", true)
+ // This IS partial data — the command produced more than the capture cap, so the tail is gone from
+ // this result. Unlike a prompt-side context trim, re-running won't help; the fix is to redirect the
+ // command's output to a file and read it in pieces. Say so, so the planner reaches for the file
+ // instead of re-running or bumping the timeout.
+ return (
+ String(output.prefix(shellOutputMaxLength))
+ + "\n… [output truncated at \(shellOutputMaxLength) chars; the command produced more — "
+ + "re-run it redirected to a file (`cmd > out.txt`) and read that, don't re-run as-is]",
+ true
+ )
}
/// The diagnostic TAIL of a failed command's output. A tool prints its banner/help first and the
@@ -559,11 +732,23 @@ public enum DonkeyCommandBackends {
// failure (e.g. retrying the same `subtitles=` filter without seeing `No such filter`).
let stderrTail = diagnosticTail(result.stderr)
let stdoutTail = diagnosticTail(result.stdout)
- var failureLines = [
- result.timedOut
- ? "Command timed out after \(Int(timeout))s and was terminated. Pass timeoutSeconds (max \(Int(shellTimeoutMax))) for known-slow commands."
- : "Command exited with code \(result.exitCode)."
- ]
+ // A timeout that already produced a lot of stdout is an OUTPUT-VOLUME problem, not a
+ // needs-more-time problem: the command was streaming faster than it could be drained, so a
+ // bigger timeout just buys a bigger truncated dump. Steer to a file redirect instead of a
+ // higher timeout. A timeout with little/no output is genuinely slow — there, bumping helps.
+ let timedOutOnVolume = result.timedOut && result.stdout.count >= shellOutputMaxLength
+ let firstLine: String
+ if timedOutOnVolume {
+ firstLine = "Command timed out after \(Int(timeout))s while producing a large, streaming "
+ + "output — this is a volume problem, not a speed one. Do NOT just raise timeoutSeconds; "
+ + "re-run it redirected to a file (`cmd > out.txt`) and read that file in pieces."
+ } else if result.timedOut {
+ firstLine = "Command timed out after \(Int(timeout))s and was terminated. Pass "
+ + "timeoutSeconds (max \(Int(shellTimeoutMax))) for known-slow commands."
+ } else {
+ firstLine = "Command exited with code \(result.exitCode)."
+ }
+ var failureLines = [firstLine]
if !stderrTail.isEmpty {
failureLines.append("stderr: " + stderrTail)
} else if !stdoutTail.isEmpty {
@@ -912,6 +1097,19 @@ private final class WebSnapshotLoader: NSObject, WKNavigationDelegate {
}
}
+ /// Load an in-memory HTML/SVG document (no network) for `image_render`. Resolves the same way as
+ /// `load` — `true` on `didFinish`, `false` on failure or timeout.
+ func loadHTML(_ html: String, in webView: WKWebView, timeout: TimeInterval) async -> Bool {
+ await withCheckedContinuation { continuation in
+ self.continuation = continuation
+ webView.loadHTMLString(html, baseURL: nil)
+ 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)
}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/design/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/design/SKILL.md
new file mode 100644
index 00000000..bad0b5db
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/design/SKILL.md
@@ -0,0 +1,63 @@
+# Design
+
+id: design
+description: Create an image from scratch about any topic by designing it as code — infographics, explainers, diagrams, standings/brackets, charts, profiles, posters, cards. Write a self-contained HTML/SVG document, then render it to a crisp PNG with image_render. This is the reliable way to make a "nice image" of text, data, or knowledge.
+tags: design, infographic, diagram, chart, poster, explainer, visual
+keywords: image, infographic, explainer, diagram, chart, graph, poster, flyer, card, certificate, banner, visualize, visualization, visualisation, draw, drawing, design, graphic, illustrate, standings, table, bracket, leaderboard, timeline, roadmap, profile, summary, learn, teach, overview, nice, pretty, beautiful, clean
+tools: image_render, web.search, web.fetch, llm.generate, files.describe
+
+When someone wants "an image" / "an infographic" / "a nice diagram" about something —
+sports standings, an election result, a person's profile, the solar system, how a
+system works, a comparison, a poster — you design it yourself: write one HTML/SVG
+document and render it with `image_render`. Do NOT screenshot a web page (that is
+someone else's cluttered layout) and do NOT use `image.generate` (a generative model
+garbles text and numbers). Rendering your own markup keeps every label sharp and gives
+you full control of the layout. This works for ANY topic.
+
+## The loop
+1. Gather the content. For anything current or factual you're not sure of (today's
+ standings, an election result, a player's stats), use `web.search` → `web.fetch`,
+ then keep only the handful of facts the image needs. For general knowledge (the
+ planets, a concept) you may already have it. Use `llm.generate` to distill messy
+ source text into a clean, structured set of facts (`toFile=true` for a lot).
+2. Decide the design before writing markup. In one sentence: the ONE thing this image
+ should get across, the layout that carries it (a ranked list, a grid of cards, a
+ bracket, a labelled diagram, a stat block, a timeline), and a small deliberate
+ palette + type scale. Match the structure to the subject — a profile is not a table.
+3. Write a single self-contained HTML document. Inline ALL CSS. Use system fonts
+ (`-apple-system, "Helvetica Neue", Arial, sans-serif`) — remote fonts and images do
+ not load. Embed any image/flag/logo as a `data:` URI, or use emoji (🇰🇷 ⚽ 🪐). Use
+ inline `<svg>` for diagrams, brackets, arrows, gauges, and precise shapes. Wrap
+ everything in a fixed-width container matching the width you'll render at.
+4. Render it: `image_render` with your `html`, a `width`, and an optional `height`.
+ Omit `height` to fit the content; default canvas is 1200px wide.
+5. Verify and present: confirm the file exists (`files.describe`), then show it.
+
+## Make it nice — this is the whole point
+- Commit to a real visual concept, not a default box of text. A tournament group stage
+ → a grid of group cards, each a small standings table with rank, flag, points, the
+ leader highlighted. An election → a result bar or hemicycle of seats per party with a
+ headline winner. A person → a profile card: name, role, a key-stat strip, a short
+ bio, a few highlights. The solar system → a row of planets scaled and labelled with
+ one or two facts each. A process → labelled boxes and arrows in inline SVG.
+- Hierarchy: one strong title, a quiet subtitle (e.g. "as of <date>" or a source),
+ then the content. Big size contrast between title and body.
+- Restraint: one accent color plus neutrals; consistent padding; aligned columns;
+ rounded corners and a soft shadow if they help. No rainbow palettes, no clutter.
+- Size for the content, never a giant scroll: a wide dashboard (1600×900), a tall
+ poster (1080×1350), a card (1200×630), a square (1080×1080).
+
+## Examples
+- "current fifa standings as a nice image" → fetch the ranking → titled card grid or a
+ clean ranked table with flags + points → `image_render` width=1200.
+- "infographic about the current local election in Korea" → fetch results → a seats/
+ vote bar per party, headline result, turnout stat → `image_render` width=1200.
+- "infographic about Son Heung-min" → fetch/recall key facts → a profile card: photo
+ area (emoji/initials if no image), club, position, a career-stats strip, highlights.
+- "I want to learn about the solar system" → an explainer: a scaled planet row, each
+ with name + 2 facts, a legend, a short intro line → tall or wide canvas.
+
+## When NOT to use this
+- A real photo or piece of art ("a watercolor fox", "a sunset photo") → `image.generate`.
+- Editing an existing photo → `image.edit`.
+- The user explicitly wants a screenshot of a real web page → `web_snapshot`.
diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/images/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/images/SKILL.md
index f7d80c3e..53dfc8dc 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/images/SKILL.md
+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/images/SKILL.md
@@ -36,7 +36,7 @@ directly and fall back to `sips` if it isn't installed. Editing in place is reve
## Generative edits — image.edit / image.generate
- Change an existing image: `image.edit` with `inputPath` and a plain-words `prompt` ("remove the background", "make the sky a sunset", "put a hat on the dog"). It writes a NEW file and returns its path; it never touches the source.
-- New image from text: `image.generate` with a `prompt`.
+- New PHOTO or ARTWORK from text: `image.generate` with a `prompt`. But to CREATE an infographic, diagram, chart, poster, or any image of text/data, do NOT use `image.generate` (it garbles text) — follow the `design` skill: write HTML/SVG and render it with `image_render`.
- These cost credits per image. For a batch, say how many and confirm first, then call `image.edit` once per file (e.g. saving into `edited/`).
- Verify the returned file exists and looks right (`files.describe` or open it), then report what was saved.
diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/video/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/video/SKILL.md
new file mode 100644
index 00000000..29324219
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/video/SKILL.md
@@ -0,0 +1,57 @@
+# Video
+
+id: video
+description: Generate a short video clip from a text prompt (or animate a still image) with a generative video model. Use when the user wants a video, clip, animation, or moving footage created from scratch.
+tags: video, generate, animation, clip, text-to-video, image-to-video
+keywords: video, clip, animation, animate, generate, create, make, footage, movie, scene, motion, text to video, image to video
+tools: user.choose, video.generate, shell_exec, files.describe
+
+When someone wants a video *made* — "make a video of …", "generate a clip of …", "animate
+this photo" — call `video.generate` with a `prompt` describing the scene, action, camera, and
+mood. Pass `inputPath` to animate a still image as the first frame (image-to-video). This is a
+generative model: it invents new footage, so it fits imaginative or cinematic asks, not exact
+text/data on screen.
+
+## Let the user pick speed/quality first
+Video generation is slow and costs real credits, and the trade-offs (speed vs quality, audio on/off)
+are the user's call — so DON'T just generate. First call `user.choose` to surface a small options
+panel, then read the picks and call `video.generate`. Always GUESS sensible defaults from the request
+so they can submit in one tap; only the *defaults* differ run to run.
+
+- **Speed & quality** — a `segmented` field `tier` with options like `fast` ("Quicker, lower cost"),
+ `standard` ("Balanced"), `high` ("Best quality, slower"). Default from the words: "quick"/"draft" →
+ `fast`; "cinematic"/"high quality"/"best" → `high`; otherwise `standard`.
+- **Audio** — a `toggle` field `audio`. Default on, unless they said "silent"/"no sound".
+- **Length** — a `segmented` field `length` with options like `4`, `6`, `8` (seconds). Default `8` (a
+ reasonable clip length); honor an explicit ask ("a 4 second clip" → default `4`).
+- **Aspect ratio** — a `dropdown` (or segmented) field `aspect` with `16:9` and `9:16`. Default `9:16`
+ for "reel"/"tiktok"/"short"/"story"/"phone", else `16:9`.
+
+The answer returns as `Selected options: tier=…, audio=…, length=…, aspect=…`. Map it straight onto the
+call: `video.generate prompt="…" tier=<tier> audio=<true|false> durationSeconds=<length> aspectRatio=<aspect>`.
+
+## The tool
+- `video.generate prompt="…"` writes one `.mp4` to `~/Downloads` and returns its path.
+- Optional knobs: `tier` (speed/quality), `audio` ("true"/"false"), `inputPath` (animate a still),
+ `aspectRatio` ("16:9" landscape, "9:16" portrait), `durationSeconds`, `negativePrompt`, `outDir`.
+- It takes up to a few minutes — the call waits for the clip, so issue it once and let it run;
+ do not fire it again thinking it stalled.
+- It costs video-generation credits per clip, and a clip is much pricier than an image. For more
+ than one clip, say how many and confirm first, then call once per clip.
+
+## Write a good prompt
+- Describe the subject, the action, the setting, the camera move, and the mood in one or two
+ vivid sentences ("a slow dolly-in on a lighthouse at dusk, waves crashing, moody and cinematic").
+- Use `negativePrompt` to exclude things ("no text, no people").
+- Match `aspectRatio` to where it'll be used — "9:16" for a phone/Reel, "16:9" for landscape.
+
+## Verify and present
+- Confirm the file exists and is real video before claiming success:
+ `ffprobe -v error -show_entries format=duration:format_name -of default=nw=1 <path>`.
+- A zero-byte file or an ffprobe error means it failed — report it, don't claim success.
+
+## When NOT to use this
+- Editing, trimming, transcoding, or subtitling an EXISTING video file → the `media` skill (ffmpeg).
+- Downloading a video from a URL → the `media` skill (yt-dlp).
+- A still photo or artwork → `image.generate`. A chart/infographic/poster → the `design` skill.
+- A slideshow of existing stills → assemble with the `media` skill (ffmpeg), not a generative model.
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/HarnessEval/fifa-standings-image/scenario.json b/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/HarnessEval/fifa-standings-image/scenario.json
index e741c6f2..055281de 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/HarnessEval/fifa-standings-image/scenario.json
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/Fixtures/HarnessEval/fifa-standings-image/scenario.json
@@ -4,7 +4,7 @@
"responses": [
{ "tool": "web.search", "summary": "FIFA Men's World Ranking (latest): 1 Argentina, 2 France, 3 Spain, 4 England, 5 Brazil, 6 Netherlands, 7 Portugal, 8 Belgium, 9 Italy, 10 Germany." },
{ "tool": "web.fetch", "summary": "FIFA/Coca-Cola Men's World Ranking. 1 Argentina 1862.71; 2 France 1859.78; 3 Spain 1853.07; 4 England 1819.20; 5 Brazil 1776.03; 6 Netherlands 1754.17." },
- { "tool": "image.generate", "summary": "Generated ~/Downloads/fifa-standings.png (1200x900).", "produces": ["~/Downloads/fifa-standings.png"] },
+ { "tool": "image_render", "summary": "Rendered PNG → ~/Downloads/fifa-standings.png.", "produces": ["~/Downloads/fifa-standings.png"] },
{ "contains": ["png"], "summary": "Wrote ~/Downloads/fifa-standings.png.", "produces": ["~/Downloads/fifa-standings.png"] }
],
"expect": {