Open source CapCut alternative.
TypeScript
feat(app): add provider-neutral image.edit/image.generate harness tools
David Lea071dc92cdae
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swiftindex 9b4718e9..cc689123 100644--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift@@ -525,6 +525,13 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {harnessServices.textGenerator = { prompt inawait textGenerator.generate(prompt)}+ // Generative image editing/generation behind image.edit / image.generate. Provider stays+ // unset so the backend routes kind=image to its configured image model; this adapter only+ // encodes inputs and writes the returned files.+ let imageGenerator = HostedImageGenerator(backend: backend)+ harnessServices.imageGenerator = { request in+ await imageGenerator.generate(request)+ }// Web research goes through the backend on the service-account credential — no key in the// app. Search uses Google Search grounding; fetch reads a page and returns clean markdown// (nav/ads/boilerplate stripped server-side) so the model gets the article, not raw HTML.diff --git a/apps/Donkey/Sources/DonkeyAI/HostedImageGenerator.swift b/apps/Donkey/Sources/DonkeyAI/HostedImageGenerator.swiftnew file mode 100644index 00000000..472c9f92--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/HostedImageGenerator.swift@@ -0,0 +1,208 @@+import CoreGraphics+import DonkeyContracts+import DonkeyHarness+import DonkeyRuntime+import Foundation+import ImageIO++/// The model boundary behind the generic `image.edit` / `image.generate` harness tools. It encodes+/// the source image(s), asks the hosted asset API for an image generation (provider AND model unset,+/// so the backend routes to its configured image model), waits for the result, and writes the output+/// file(s) to disk — keeping every provider/model detail behind the backend, not the app.+public struct HostedImageGenerator: Sendable {+ private let backend: DonkeyBackendInferenceClient+ private let timeoutSeconds: TimeInterval+ private let maxPixelSize: Int+ private let maxPollAttempts: Int++ public init(+ backend: DonkeyBackendInferenceClient,+ timeoutSeconds: TimeInterval = 120,+ maxPixelSize: Int = 2_048,+ maxPollAttempts: Int = 30+ ) {+ self.backend = backend+ self.timeoutSeconds = timeoutSeconds+ self.maxPixelSize = maxPixelSize+ self.maxPollAttempts = maxPollAttempts+ }++ public func generate(+ _ request: HarnessImageGenerationRequest+ ) async -> HarnessImageGenerationResult? {+ // Encode inputs: the first path (an edit's source) is required if present; extra reference+ // paths are best-effort — an unreadable reference is skipped, not fatal to the whole edit.+ var images: [RemoteInferenceJSONValue] = []+ for (index, path) in request.inputImagePaths.enumerated() {+ if let encoded = Self.encodedImage(atPath: path, maxPixelSize: maxPixelSize) {+ images.append(.object([+ "data": .string(encoded.base64),+ "mimeType": .string(encoded.mimeType)+ ]))+ } else if index == 0 {+ return HarnessImageGenerationResult(+ savedPaths: [],+ failureReason: "Could not read the source image at \(path)."+ )+ }+ }+ var inputs: RemoteInferenceJSONObject = [:]+ if !images.isEmpty {+ inputs["images"] = .array(images)+ }++ let trimmedModel = request.model?.trimmingCharacters(in: .whitespaces)+ let assetRequest = RemoteInferenceAssetGenerationRequest(+ kind: .image,+ provider: nil,+ model: (trimmedModel?.isEmpty == false) ? trimmedModel : nil,+ prompt: request.prompt,+ inputs: inputs,+ metadata: ["source": "image-tool"]+ )+ let outputDirectory = Self.resolvedOutputDirectory(+ request.outputDirectory,+ inputImagePaths: request.inputImagePaths+ )++ let backend = self.backend+ let maxPollAttempts = self.maxPollAttempts+ // One deadline over the whole call (create + poll + write); the request was synchronous in+ // practice, but polling/writing stay bounded so the harness step can't hang.+ let outcome = try? await AIDeadline.enforce(seconds: timeoutSeconds) {+ () -> HarnessImageGenerationResult 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: 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 HarnessImageGenerationResult(+ savedPaths: [],+ failureReason: Self.failureReason(from: record)+ )+ }+ let saved = await Self.writeOutputs(record.outputs, to: outputDirectory)+ return HarnessImageGenerationResult(+ savedPaths: saved,+ failureReason: saved.isEmpty ? "The image model returned no image." : nil+ )+ }++ return outcome ?? HarnessImageGenerationResult(+ savedPaths: [],+ failureReason: "Image generation timed out or could not reach the model."+ )+ }++ /// 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).+ static func resolvedOutputDirectory(+ _ outDir: String?,+ inputImagePaths: [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)++ guard let outDir, !outDir.trimmingCharacters(in: .whitespaces).isEmpty else {+ return sourceDir ?? downloads+ }+ let expanded = (outDir as NSString).expandingTildeInPath+ if expanded.hasPrefix("/") {+ return URL(fileURLWithPath: expanded, isDirectory: true)+ }+ return (sourceDir ?? downloads).appendingPathComponent(expanded, isDirectory: true)+ }++ private static func writeOutputs(+ _ outputs: [RemoteInferenceOutputRef],+ to directory: URL+ ) async -> [String] {+ try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ var saved: [String] = []+ var used = Set<String>()+ for (index, output) in outputs.enumerated() {+ guard let data = await outputData(output) else { continue }+ let preferred = output.filename ?? "image-\(index).png"+ var name = preferred+ var suffix = 1+ while used.contains(name) {+ let base = (preferred as NSString).deletingPathExtension+ let ext = (preferred as NSString).pathExtension+ name = ext.isEmpty ? "\(base)-\(suffix)" : "\(base)-\(suffix).\(ext)"+ suffix += 1+ }+ used.insert(name)+ let fileURL = directory.appendingPathComponent(name, isDirectory: false)+ if (try? data.write(to: fileURL, options: [.atomic])) != nil {+ saved.append(fileURL.path)+ }+ }+ return saved+ }++ private static func outputData(_ output: RemoteInferenceOutputRef) async -> Data? {+ if let base64 = output.dataBase64, let data = Data(base64Encoded: base64) {+ return data+ }+ if let urlString = output.url, let url = URL(string: urlString) {+ return try? Data(contentsOf: url)+ }+ return nil+ }++ private static func failureReason(from record: RemoteInferenceGenerationRecord) -> String {+ if let detail = errorText(record.error) {+ return "Image generation \(record.status.rawValue): \(detail)"+ }+ return "Image 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+ }+ }++ /// Loads an image from disk, downscales it to at most `maxPixelSize` on its longest edge, and+ /// re-encodes it as JPEG so the request body stays small. Returns the base64 payload and MIME+ /// type, or nil when the file can't be read as an image.+ static func encodedImage(+ atPath path: String,+ maxPixelSize: Int+ ) -> (base64: String, mimeType: String)? {+ let url = URL(fileURLWithPath: (path as NSString).expandingTildeInPath)+ guard let source = CGImageSourceCreateWithURL(url as CFURL, nil),+ let encoded = ScreenshotCompression.downscaledJPEG(+ from: source,+ maxPixelDimension: maxPixelSize,+ jpegQuality: 0.9+ )+ else {+ return nil+ }+ return (encoded.data.base64EncodedString(), "image/jpeg")+ }+}diff --git a/apps/Donkey/Sources/DonkeyContracts/RemoteInferenceContracts.swift b/apps/Donkey/Sources/DonkeyContracts/RemoteInferenceContracts.swiftindex 89eb26c5..a6641fe8 100644--- a/apps/Donkey/Sources/DonkeyContracts/RemoteInferenceContracts.swift+++ b/apps/Donkey/Sources/DonkeyContracts/RemoteInferenceContracts.swift@@ -224,7 +224,9 @@ public struct RemoteInferenceAssetGenerationRequest: Codable, Equatable, Sendablpublic var generationId: String?public var kind: RemoteInferenceAssetKindpublic var provider: String?- public var model: String+ /// Optional: omit to let the selected provider pick its default model (the image tools do this,+ /// staying model-neutral). Synthesized encoding drops the key when nil.+ public var model: String?public var prompt: Stringpublic var inputs: RemoteInferenceJSONObjectpublic var parameters: RemoteInferenceJSONObject@@ -234,7 +236,7 @@ public struct RemoteInferenceAssetGenerationRequest: Codable, Equatable, SendablgenerationId: String? = nil,kind: RemoteInferenceAssetKind,provider: String? = nil,- model: String,+ model: String? = nil,prompt: String,inputs: RemoteInferenceJSONObject = [:],parameters: RemoteInferenceJSONObject = [:],diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swiftindex e65e3283..8f559898 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift@@ -220,6 +220,40 @@ public actor HarnessGeneratedScriptStore {}}+/// A request to a generative image model behind the `image.edit` / `image.generate` tools.+/// `inputImagePaths` is empty for generation-from-scratch, the source image first (then any+/// reference images) for an edit. Kept provider-neutral: the adapter that fulfills it names the model.+public struct HarnessImageGenerationRequest: Sendable {+ public var prompt: String+ public var inputImagePaths: [String]+ public var model: String?+ public var outputDirectory: String?++ public init(+ prompt: String,+ inputImagePaths: [String] = [],+ model: String? = nil,+ outputDirectory: String? = nil+ ) {+ self.prompt = prompt+ self.inputImagePaths = inputImagePaths+ self.model = model+ self.outputDirectory = outputDirectory+ }+}++public struct HarnessImageGenerationResult: Sendable {+ public var savedPaths: [String]+ /// Set when no image was produced — the provider/model's reason, surfaced to the planner so it+ /// can adjust (e.g. reword the prompt) rather than being told a flat "no image, do not retry".+ public var failureReason: String?++ public init(savedPaths: [String], failureReason: String? = nil) {+ self.savedPaths = savedPaths+ self.failureReason = failureReason+ }+}+public struct HarnessBuiltInToolServices: Sendable {public var memoryEntries: [HarnessMemoryEntry]public var skillRegistry: HarnessSkillRegistry?@@ -257,6 +291,10 @@ public struct HarnessBuiltInToolServices: Sendable {/// back to the built-in Foundation understanding. The runtime supplies this; without it the tool/// still understands text files from their content.public var fileUnderstanding: (@Sendable (URL) async -> FileUnderstanding?)?+ /// Generative image editing/generation behind `image.edit` and `image.generate`: a request in,+ /// the saved output file paths out (or nil on failure). The runtime supplies an adapter that+ /// routes through the hosted asset API to an image model; without it the tools report unavailable.+ public var imageGenerator: (@Sendable (HarnessImageGenerationRequest) async -> HarnessImageGenerationResult?)?public init(memoryEntries: [HarnessMemoryEntry] = [],@@ -274,7 +312,8 @@ public struct HarnessBuiltInToolServices: Sendable {textGenerator: (@Sendable (String) async -> String?)? = nil,webSearcher: (@Sendable (String) async -> String?)? = nil,webFetcher: (@Sendable (String) async -> String?)? = nil,- fileUnderstanding: (@Sendable (URL) async -> FileUnderstanding?)? = nil+ fileUnderstanding: (@Sendable (URL) async -> FileUnderstanding?)? = nil,+ imageGenerator: (@Sendable (HarnessImageGenerationRequest) async -> HarnessImageGenerationResult?)? = nil) {self.memoryEntries = memoryEntriesself.skillRegistry = skillRegistry@@ -292,6 +331,7 @@ public struct HarnessBuiltInToolServices: Sendable {self.webSearcher = webSearcherself.webFetcher = webFetcherself.fileUnderstanding = fileUnderstanding+ self.imageGenerator = imageGenerator}}@@ -370,6 +410,10 @@ public enum BuiltInHarnessToolExecutors {return await webFetch(context, services: services)case "files.describe":return await filesDescribe(context, services: services)+ case "image.edit":+ return await imageGenerate(context, services: services, requiresInput: true)+ case "image.generate":+ return await imageGenerate(context, services: services, requiresInput: false)case "wait":return await timingWait(context)case "run.pause", "run.resume", "run.recover", "run.cancel", "run.complete", "run.failSafe":@@ -1623,6 +1667,58 @@ public enum BuiltInHarnessToolExecutors {)}+ private static func imageGenerate(+ _ context: HarnessToolExecutionContext,+ services: HarnessBuiltInToolServices,+ requiresInput: Bool+ ) async -> HarnessToolResult {+ guard let generator = services.imageGenerator else {+ return failed(context, "No image model is wired for \(context.call.name).", reason: "imageGeneratorUnavailable")+ }+ guard let prompt = trimmed(context.call.input["prompt"]) else {+ return invalidInput(context, "\(context.call.name) requires a `prompt` describing the image.")+ }+ var inputPaths: [String] = []+ if let inputPath = trimmed(context.call.input["inputPath"]) {+ inputPaths.append(inputPath)+ }+ if let references = trimmed(context.call.input["referencePaths"]) {+ inputPaths.append(contentsOf: references+ .split(whereSeparator: { $0 == "," || $0 == "\n" || $0 == "\r" })+ .map { $0.trimmingCharacters(in: .whitespaces) }+ .filter { !$0.isEmpty })+ }+ if requiresInput && inputPaths.isEmpty {+ return invalidInput(context, "image.edit requires an `inputPath` to the image to edit.")+ }+ let request = HarnessImageGenerationRequest(+ prompt: prompt,+ inputImagePaths: inputPaths,+ model: trimmed(context.call.input["model"]),+ outputDirectory: trimmed(context.call.input["outDir"])+ )+ guard let result = await generator(request) else {+ return failed(context, "The image model is unavailable right now.", reason: "imageGeneratorUnavailable")+ }+ guard !result.savedPaths.isEmpty else {+ return failed(+ context,+ result.failureReason ?? "The image model returned no image.",+ reason: "imageGenerationFailed"+ )+ }+ let joined = result.savedPaths.joined(separator: ", ")+ return success(+ context,+ summary: "Saved \(result.savedPaths.count) image(s) → \(joined)",+ facts: ["lastAcceptedTool": context.call.name],+ metadata: [+ "paths": result.savedPaths.joined(separator: "\n"),+ "count": String(result.savedPaths.count)+ ]+ )+ }+private static func webSearch(_ context: HarnessToolExecutionContext,services: HarnessBuiltInToolServicesdiff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swiftindex 6aebd3c0..6a34c0e2 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift@@ -532,6 +532,46 @@ public enum BuiltInHarnessToolCatalog {verification: ["the returned understanding covers the requested files"],metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]),+ descriptor(+ "image.edit",+ pluginID: "core.image",+ summary: "Edit an existing image with a generative image model: describe the change in `prompt` and pass the source `inputPath`. Use it for semantic edits that sips/magick cannot do — remove or replace a background, add or remove an object, restyle, relight, or change a scene. To match a reference photo's look, pass the reference(s) as `referencePaths` and ask to match them. Writes a NEW image file and returns its path; it never overwrites the source. Costs image-generation credits per image, so for a batch confirm with the user first, then call once per file.",+ input: [+ "prompt": "What to change, in plain words (e.g. \"remove the background\", \"make the sky a sunset\").",+ "inputPath": "Path to the source image to edit.",+ "referencePaths": "Optional comma/newline-separated reference image paths to condition on (e.g. a style/look reference).",+ "model": "Optional model id override; omit to use the default image model.",+ "outDir": "Optional output directory; a relative path like `edited` lands beside the source image. Omit to save next to the source."+ ],+ output: [+ "paths": "Newline-separated paths to the saved image file(s).",+ "count": "How many images were saved."+ ],+ optionalInputKeys: ["referencePaths", "model", "outDir"],+ permissions: [],+ safety: .reversible,+ verification: ["the returned image file exists and reflects the requested edit"],+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]+ ),+ descriptor(+ "image.generate",+ pluginID: "core.image",+ summary: "Generate a brand-new image from a text `prompt` with a generative image model — use when there is no source image to edit. Writes a new image file and returns its path. Costs image-generation credits per image.",+ input: [+ "prompt": "Description of the image to create.",+ "model": "Optional model id override; omit to use the default image model.",+ "outDir": "Optional output directory for the result; omit to save to Downloads."+ ],+ output: [+ "paths": "Newline-separated paths to the saved image file(s).",+ "count": "How many images were saved."+ ],+ optionalInputKeys: ["model", "outDir"],+ permissions: [],+ safety: .reversible,+ verification: ["the returned image file exists"],+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]+ ),descriptor("web.search",pluginID: "core.web",diff --git a/apps/Donkey/Sources/DonkeyRuntime/ScreenshotCompression.swift b/apps/Donkey/Sources/DonkeyRuntime/ScreenshotCompression.swiftindex 2929c24b..47f2766e 100644--- a/apps/Donkey/Sources/DonkeyRuntime/ScreenshotCompression.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/ScreenshotCompression.swift@@ -36,9 +36,31 @@ public enum ScreenshotCompression {contentType: "image/png",pixelSize: HotLoopSize(width: Double(screenshot.imageWidth), height: Double(screenshot.imageHeight), space: .window))- guard let source = CGImageSourceCreateWithData(screenshot.pngData as CFData, nil) else {+ guard let source = CGImageSourceCreateWithData(screenshot.pngData as CFData, nil),+ let encoded = downscaledJPEG(+ from: source,+ maxPixelDimension: maxPixelDimension,+ jpegQuality: jpegQuality+ )+ else {return fallback}+ return CompressedScreenshot(+ data: encoded.data,+ contentType: "image/jpeg",+ pixelSize: HotLoopSize(width: Double(encoded.width), height: Double(encoded.height), space: .window)+ )+ }++ /// Downscale the first image in a `CGImageSource` to at most `maxPixelDimension` on its longest+ /// edge (never upscaling) and JPEG-encode it. Shared by screenshot compression and the image+ /// tools so every downscale-and-encode goes through one path. Returns nil if decoding/encoding+ /// fails.+ public static func downscaledJPEG(+ from source: CGImageSource,+ maxPixelDimension: Int,+ jpegQuality: Double+ ) -> (data: Data, width: Int, height: Int)? {let thumbnailOptions: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true,kCGImageSourceShouldCacheImmediately: true,@@ -49,18 +71,14 @@ public enum ScreenshotCompression {let encoded = NSMutableData() as CFMutableData?,let destination = CGImageDestinationCreateWithData(encoded, UTType.jpeg.identifier as CFString, 1, nil)else {- return fallback+ return nil}CGImageDestinationAddImage(destination, image, [kCGImageDestinationLossyCompressionQuality: jpegQuality] as CFDictionary)guard CGImageDestinationFinalize(destination) else {- return fallback+ return nil}- return CompressedScreenshot(- data: encoded as Data,- contentType: "image/jpeg",- pixelSize: HotLoopSize(width: Double(image.width), height: Double(image.height), space: .window)- )+ return (encoded as Data, image.width, image.height)}}