Skip to content

Open source CapCut alternative.

TypeScript

feat(media): implement media pipeline, caption orchestrator, and subtitle translation

David Lea5d20bdde066
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedSubtitleTranslator.swift b/apps/Donkey/Sources/DonkeyAI/HostedSubtitleTranslator.swift
new file mode 100644
index 00000000..4d354d8f
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/HostedSubtitleTranslator.swift
@@ -0,0 +1,89 @@
+import DonkeyContracts
+import Foundation
+
+/// The model boundary behind `media.caption`'s translation: a list of subtitle lines and a target language
+/// in, the same lines translated (in the same order, same count) out. This is the ONE model call the caption
+/// pipeline makes when a translation is asked for — the timings come from on-device transcription and the SRT
+/// is assembled in code, so the model only ever supplies text, never an SRT it can format wrong. Returns nil
+/// (or a wrong-length array, which the caller rejects) on failure; the orchestrator turns that into a clean
+/// "could not translate" outcome.
+public struct HostedSubtitleTranslator: Sendable {
+ private let backend: DonkeyBackendInferenceClient
+ private let maxOutputTokens: Int
+ private let timeoutSeconds: TimeInterval
+
+ public init(
+ backend: DonkeyBackendInferenceClient,
+ maxOutputTokens: Int = 4_000,
+ timeoutSeconds: TimeInterval = 120
+ ) {
+ self.backend = backend
+ self.maxOutputTokens = maxOutputTokens
+ self.timeoutSeconds = timeoutSeconds
+ }
+
+ public func translate(lines: [String], to targetLanguage: String) async -> [String]? {
+ guard !lines.isEmpty else { return [] }
+ let request = RemoteInferenceResponseCreateRequest(
+ input: .array([
+ .object([
+ "role": .string("user"),
+ "content": .array([
+ .object(["type": .string("input_text"), "text": .string(Self.prompt(lines: lines, targetLanguage: targetLanguage))])
+ ])
+ ])
+ ]),
+ store: false,
+ metadata: ["source": "hosted-subtitle-translator", "prompt_version": "caption-translate-v1"],
+ parameters: [
+ // Deterministic: the same lines should translate the same way each run.
+ "temperature": .number(0),
+ "max_output_tokens": .number(Double(maxOutputTokens)),
+ "thinking_level": .string("low"),
+ "response_format": .object(["type": .string("json_object")])
+ ]
+ )
+ let backend = self.backend
+ for attempt in 0..<3 {
+ if attempt > 0 { try? await Task.sleep(nanoseconds: 800_000_000) }
+ guard let response = try? await AIDeadline.enforce(seconds: timeoutSeconds, {
+ try await backend.createResponse(request)
+ }) else { continue }
+ guard let text = RemoteInferenceResponseHelpers.outputText(from: response),
+ let translated = Self.decode(from: text, expectedCount: lines.count) else { continue }
+ return translated
+ }
+ return nil
+ }
+
+ /// Pull `{"lines":[...]}` out of the reply — tolerant of surrounding prose or a code fence — and accept it
+ /// only when it carries exactly the expected number of strings, so a dropped or merged line can't shift
+ /// every later cue's timing.
+ static func decode(from text: String, expectedCount: Int) -> [String]? {
+ guard let start = text.firstIndex(of: "{"), let end = text.lastIndex(of: "}"), start < end,
+ let data = String(text[start...end]).data(using: .utf8),
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let raw = object["lines"] as? [Any] else {
+ return nil
+ }
+ let strings = raw.map { value -> String? in value as? String }
+ guard !strings.contains(nil) else { return nil }
+ let lines = strings.compactMap { $0 }
+ return lines.count == expectedCount ? lines : nil
+ }
+
+ private static func prompt(lines: [String], targetLanguage: String) -> String {
+ let numbered = lines.enumerated().map { "\($0.offset + 1). \($0.element)" }.joined(separator: "\n")
+ return """
+ Translate each subtitle line below into \(targetLanguage). Keep each translation concise enough to \
+ read as a subtitle, and translate line-by-line so the order and count stay identical.
+
+ Return ONLY a strict JSON object {"lines": [...]} containing EXACTLY \(lines.count) translated strings, \
+ in the same order as the input — one translation per input line, no extra lines, no numbering, no prose, \
+ no code fence.
+
+ LINES:
+ \(numbered)
+ """
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/CaptionOrchestrator.swift b/apps/Donkey/Sources/DonkeyRuntime/CaptionOrchestrator.swift
new file mode 100644
index 00000000..4b9b112b
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/CaptionOrchestrator.swift
@@ -0,0 +1,184 @@
+import DonkeyHarness
+import Foundation
+
+/// The deterministic pipeline behind `media.caption`: take a video (optionally a clipped span of one),
+/// transcribe it on-device, optionally translate the text with ONE model call, build the SRT in code, and
+/// burn it in with a known-good encoder — then verify. This is the captioning/subtitling/translation family
+/// done as fixed code instead of through the planner loop.
+///
+/// It exists because that recipe, left to the planner, is where runs explode: a model-authored SRT comes
+/// back messy, so the planner re-cleans it, writes a Python filter, re-runs it; the burn fails on a default
+/// encoder, so it probes `ffmpeg -encoders`; a `-c copy` trim of a webm yields the wrong duration, so it
+/// runs eight `ffprobe`s to debug — every probe a full-context LLM round-trip. Here the timings come from
+/// on-device transcription, the SRT is built from them (never parsed back from a model), the trim re-encodes
+/// for an accurate span, and the burn pins `libx264 -pix_fmt yuv420p -c:a aac` so the video stream is never
+/// dropped. The only model call is the optional translation.
+///
+/// ```
+/// resolve source (yt-dlp, with --download-sections for a URL span)
+/// → [trim local span] → extract audio → transcribe (on-device)
+/// → [translate cue texts] ← the ONE model call, only when a language is asked for
+/// → build SRT in code → burn (libx264/yuv420p/aac) → verify
+/// ```
+public struct CaptionOrchestrator: Sendable {
+ public typealias TranslateCues = @Sendable (_ lines: [String], _ targetLanguage: String) async -> [String]?
+ public typealias Transcribe = @Sendable (HarnessTranscriptionRequest) async -> HarnessTranscriptionResult?
+
+ private let translateCues: TranslateCues
+ private let transcribe: Transcribe
+ private let runTool: MediaPipeline.ToolRunner
+
+ public init(
+ translateCues: @escaping TranslateCues,
+ transcribe: @escaping Transcribe,
+ runTool: @escaping MediaPipeline.ToolRunner = MediaPipeline.bundledToolRunner
+ ) {
+ self.translateCues = translateCues
+ self.transcribe = transcribe
+ self.runTool = runTool
+ }
+
+ public func caption(_ request: HarnessCaptionRequest) async -> HarnessCaptionOutcome {
+ let workdir = DonkeyCommandBackends.resolvedWorkingDirectoryPath(request.workingDirectory)
+ func path(_ name: String) -> String { (workdir as NSString).appendingPathComponent(name) }
+
+ let startSec = request.clipStart.flatMap(Self.parseSeconds)
+ let durationSec = request.clipDuration.flatMap(Self.parseSeconds)
+
+ // 1. Resolve to a local video, applying the requested span as we go (a URL span downloads only that
+ // range; a local span is trimmed with an accurate re-encode, never `-c copy`).
+ let base: String
+ switch resolveBase(request.source, startSec: startSec, durationSec: durationSec, workdir: workdir, makePath: path) {
+ case .ok(let resolved): base = resolved
+ case .failed(let reason): return Self.fail(reason)
+ }
+
+ // 2. Extract compact audio and transcribe on-device — the timings the cues are built from. Free.
+ let audio = path("caption_audio.mp3")
+ let audioStep = MediaPipeline.runStep(
+ "ffmpeg",
+ ["-y", "-i", base, "-vn", "-ac", "1", "-c:a", "libmp3lame", "-b:a", "64k", audio],
+ workingDirectory: workdir, expecting: audio, using: runTool
+ )
+ if case let .failed(reason) = audioStep {
+ return Self.fail("Could not read audio from the video: \(reason)")
+ }
+ guard let transcript = await transcribe(HarnessTranscriptionRequest(filePath: audio)),
+ transcript.failureReason == nil, !transcript.words.isEmpty else {
+ return Self.fail("Could not transcribe the video to build captions.")
+ }
+
+ // 3. Build cues from the timings. Optionally translate the cue TEXTS (one model call) while keeping
+ // the exact timings — so a translation never disturbs sync and the SRT is never model-authored.
+ var cues = MediaSubtitles.cues(from: transcript.words)
+ var translatedNote = ""
+ if let language = request.translateTo, !language.isEmpty {
+ guard let translated = await translateCues(cues.map(\.text), language),
+ translated.count == cues.count else {
+ return Self.fail("Could not translate the captions to \(language).")
+ }
+ for index in cues.indices { cues[index].text = translated[index] }
+ translatedNote = " translated to \(language)"
+ }
+
+ // 4. Write the SRT (built in code — valid by construction) and burn it in with a known-good encoder.
+ let srtPath = path("captions.srt")
+ guard (try? MediaSubtitles.srt(from: cues).write(toFile: srtPath, atomically: true, encoding: .utf8)) != nil else {
+ return Self.fail("Could not write the captions file.")
+ }
+ let output = path("captioned.mp4")
+ let burn = MediaPipeline.runStep(
+ "ffmpeg",
+ ["-y", "-i", base, "-vf", "subtitles=\((srtPath as NSString).lastPathComponent)",
+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", output],
+ workingDirectory: workdir, expecting: output, using: runTool
+ )
+ if case .ok = burn {
+ return HarnessCaptionOutcome(text: "Captioned\(translatedNote): \(output)", succeeded: true, producedFiles: [output])
+ }
+ // libass missing → deliver a toggleable soft track instead of burned-in text (no re-encode needed).
+ let soft = MediaPipeline.runStep(
+ "ffmpeg",
+ ["-y", "-i", base, "-i", srtPath, "-c", "copy", "-c:s", "mov_text", output],
+ workingDirectory: workdir, expecting: output, using: runTool
+ )
+ if case let .failed(reason) = soft {
+ return Self.fail("Could not burn the captions in: \(reason)")
+ }
+ return HarnessCaptionOutcome(
+ text: "Added a soft caption track\(translatedNote) (burn-in unavailable): \(output)",
+ succeeded: true, producedFiles: [output]
+ )
+ }
+
+ // MARK: - Source + span
+
+ private func resolveBase(
+ _ source: String, startSec: Double?, durationSec: Double?, workdir: String,
+ makePath: (String) -> String
+ ) -> MediaStepResult {
+ let trimmed = source.trimmingCharacters(in: .whitespacesAndNewlines)
+ let lower = trimmed.lowercased()
+ if lower.hasPrefix("http://") || lower.hasPrefix("https://") {
+ var arguments = ["-o", makePath("source.%(ext)s"), "--no-simulate", "--print", "after_move:filepath",
+ "--retries", "5", "--extractor-retries", "3"]
+ // A URL with a span downloads ONLY that range, so we never pull a whole long video to clip a minute.
+ if let startSec, let durationSec {
+ arguments.append(contentsOf: ["--download-sections", "*\(Int(startSec))-\(Int(startSec + durationSec))"])
+ }
+ arguments.append(trimmed)
+ let result = runTool("yt-dlp", arguments, workdir)
+ guard result.exitCode == 0 else {
+ let why = result.stderr.isEmpty ? result.stdout : result.stderr
+ return .failed(reason: "yt-dlp could not download the source: \(MediaPipeline.lastLines(why))")
+ }
+ let printed = result.stdout
+ .split(whereSeparator: \.isNewline)
+ .map { $0.trimmingCharacters(in: .whitespaces) }
+ .last(where: { !$0.isEmpty })
+ guard let downloaded = printed, FileManager.default.fileExists(atPath: downloaded) else {
+ return .failed(reason: "yt-dlp finished but its downloaded file path could not be determined.")
+ }
+ return .ok(producedPath: downloaded)
+ }
+
+ let expanded = (trimmed as NSString).expandingTildeInPath
+ let resolved = (expanded as NSString).isAbsolutePath
+ ? expanded
+ : (workdir as NSString).appendingPathComponent(expanded)
+ guard FileManager.default.fileExists(atPath: resolved) else {
+ return .failed(reason: "No source video at \(source).")
+ }
+ // A local span is trimmed with an accurate re-encode (seek after -i, real codec) — never `-c copy`,
+ // which snaps to a keyframe and yields the wrong duration (the bug the planner used to debug by hand).
+ guard let startSec, let durationSec else { return .ok(producedPath: resolved) }
+ let clip = makePath("clip.mp4")
+ let trim = MediaPipeline.runStep(
+ "ffmpeg",
+ ["-y", "-i", resolved, "-ss", MediaSubtitles.seconds(startSec), "-t", MediaSubtitles.seconds(durationSec),
+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-c:a", "aac", clip],
+ workingDirectory: workdir, expecting: clip, using: runTool
+ )
+ if case let .failed(reason) = trim { return .failed(reason: "Could not cut the requested span: \(reason)") }
+ return .ok(producedPath: clip)
+ }
+
+ private static func fail(_ text: String) -> HarnessCaptionOutcome {
+ HarnessCaptionOutcome(text: text, succeeded: false, producedFiles: [])
+ }
+
+ /// Parse a time spec to seconds: a bare number, or `M:SS` / `H:MM:SS`.
+ static func parseSeconds(_ value: String) -> Double? {
+ let trimmed = value.trimmingCharacters(in: .whitespaces)
+ if trimmed.isEmpty { return nil }
+ if !trimmed.contains(":") { return Double(trimmed) }
+ let parts = trimmed.split(separator: ":").map { Double($0) }
+ if parts.contains(nil) { return nil }
+ let numbers = parts.compactMap { $0 }
+ switch numbers.count {
+ case 2: return numbers[0] * 60 + numbers[1]
+ case 3: return numbers[0] * 3600 + numbers[1] * 60 + numbers[2]
+ default: return nil
+ }
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/MediaPipeline.swift b/apps/Donkey/Sources/DonkeyRuntime/MediaPipeline.swift
new file mode 100644
index 00000000..2f6ecce6
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/MediaPipeline.swift
@@ -0,0 +1,87 @@
+import Foundation
+
+/// The result of one deterministic pipeline step that runs a bundled tool and expects an output file.
+/// `.ok` carries the produced file; `.failed` carries a human-readable reason drawn from the tool's own
+/// stderr — no model call is needed to interpret it.
+public enum MediaStepResult: Sendable {
+ case ok(producedPath: String)
+ case failed(reason: String)
+}
+
+/// The result of one fanned-out item's sub-pipeline: the files it produced, or a reason it could not
+/// finish. A plain enum rather than `Result` because the failure is a human-readable string, not an Error.
+public enum PipelineItemOutcome: Sendable {
+ case produced([String])
+ case failed(reason: String)
+}
+
+/// Shared machinery for deterministic capability pipelines (shorts today, more later): run a fixed
+/// sequence of bundled-tool steps with NO planner round-trip between them, and fan a sub-pipeline out over
+/// a list while isolating per-item failures. The model is called only at the few genuine decision points
+/// the orchestrator owns — never to advance from one fixed step to the next, which is what turns a
+/// dozens-of-calls planner loop into a single decision plus local rendering.
+public enum MediaPipeline {
+ /// A bundled-tool runner: name + args + working directory in, the process result out. Defaults to
+ /// `DonkeyCommandBackends.runBundledTool`; injectable so a pipeline's control flow is unit-testable
+ /// without real ffmpeg/reframe on the machine.
+ public typealias ToolRunner = @Sendable (
+ _ name: String,
+ _ arguments: [String],
+ _ workingDirectory: String?
+ ) -> (exitCode: Int32, stdout: String, stderr: String)
+
+ /// The production runner, as a plain closure value so it can be a default argument.
+ public static let bundledToolRunner: ToolRunner = { name, arguments, workingDirectory in
+ DonkeyCommandBackends.runBundledTool(name, arguments, workingDirectory: workingDirectory)
+ }
+
+ /// Run a bundled tool and confirm it produced `outputPath` on disk. A non-zero exit or a missing file
+ /// is a clean `.failed` carrying the tool's stderr (or stdout when stderr is empty), so the caller
+ /// short-circuits in code instead of handing the failure back to the planner to interpret.
+ public static func runStep(
+ _ tool: String,
+ _ arguments: [String],
+ workingDirectory: String?,
+ expecting outputPath: String,
+ using run: ToolRunner
+ ) -> MediaStepResult {
+ let result = run(tool, arguments, workingDirectory)
+ guard result.exitCode == 0 else {
+ let why = result.stderr.isEmpty ? result.stdout : result.stderr
+ return .failed(reason: "\(tool) exited \(result.exitCode): \(lastLines(why))")
+ }
+ guard FileManager.default.fileExists(atPath: outputPath) else {
+ return .failed(reason: "\(tool) reported success but wrote no file at \(outputPath)")
+ }
+ return .ok(producedPath: outputPath)
+ }
+
+ /// Run `body` for each item in order, isolating failures: one item's reason is recorded and the rest
+ /// still run, so a 3-clip job where clip 2 fails still delivers clips 1 and 3. Returns every produced
+ /// file path and a per-item note for whatever failed.
+ public static func fanOut<Item: Sendable>(
+ _ items: [Item],
+ _ body: @Sendable (_ index: Int, _ item: Item) async -> PipelineItemOutcome
+ ) async -> (produced: [String], failures: [String]) {
+ var produced: [String] = []
+ var failures: [String] = []
+ for (index, item) in items.enumerated() {
+ switch await body(index, item) {
+ case .produced(let paths): produced.append(contentsOf: paths)
+ case .failed(let reason): failures.append(reason)
+ }
+ }
+ return (produced, failures)
+ }
+
+ /// The last couple of non-empty lines of a tool's output, bounded — enough to explain a failure in the
+ /// trace without dumping a full ffmpeg log.
+ static func lastLines(_ text: String) -> String {
+ let lines = text
+ .split(whereSeparator: \.isNewline)
+ .map(String.init)
+ .filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty }
+ let tail = lines.suffix(2).joined(separator: " ")
+ return tail.count > 240 ? String(tail.suffix(240)) : tail
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/MediaSubtitles.swift b/apps/Donkey/Sources/DonkeyRuntime/MediaSubtitles.swift
new file mode 100644
index 00000000..1c86ae0b
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/MediaSubtitles.swift
@@ -0,0 +1,67 @@
+import DonkeyHarness
+import Foundation
+
+/// A single subtitle cue: a time span (milliseconds) and its text. Built from precise on-device per-word
+/// timings; the text can be replaced by a translation while the timing stays exact.
+public struct SubtitleCue: Sendable {
+ public var startMS: Int
+ public var endMS: Int
+ public var text: String
+
+ public init(startMS: Int, endMS: Int, text: String) {
+ self.startMS = startMS
+ self.endMS = endMS
+ self.text = text
+ }
+}
+
+/// Shared subtitle and media-time helpers for the deterministic media pipelines (shorts, caption).
+///
+/// Building the SRT in CODE from precise on-device timings is the point: a captioning run that hands SRT
+/// authoring to the model falls into a cleanup loop — the model emits a messy SRT (stray prose, wrong
+/// language, broken cues), so the planner re-cleans it, writes a Python filter, re-runs it, and so on, a
+/// fresh LLM round-trip each time. Code that groups timed words into valid cues never produces that mess.
+public enum MediaSubtitles {
+ /// Group per-word timings into cues of up to ~7 words / ~3.2s, breaking early on a long pause or a
+ /// sentence-ending punctuation mark.
+ public static func cues(from words: [HarnessTranscriptionWord]) -> [SubtitleCue] {
+ var cues: [SubtitleCue] = []
+ var current: [HarnessTranscriptionWord] = []
+ func flush() {
+ guard let first = current.first, let last = current.last else { return }
+ let text = current.map(\.text).joined(separator: " ").trimmingCharacters(in: .whitespaces)
+ if !text.isEmpty { cues.append(SubtitleCue(startMS: first.startMS, endMS: last.endMS, text: text)) }
+ current = []
+ }
+ for word in words {
+ if let last = current.last, word.startMS - last.endMS > 700 { flush() }
+ current.append(word)
+ let durationMS = (current.last?.endMS ?? 0) - (current.first?.startMS ?? 0)
+ let endsSentence = word.text.last.map { ".!?".contains($0) } ?? false
+ if current.count >= 7 || durationMS >= 3200 || endsSentence { flush() }
+ }
+ flush()
+ return cues
+ }
+
+ /// Render cues as a valid SRT document: 1-based indices, `HH:MM:SS,mmm` timestamps.
+ public static func srt(from cues: [SubtitleCue]) -> String {
+ var out = ""
+ for (index, cue) in cues.enumerated() {
+ out += "\(index + 1)\n\(srtTime(cue.startMS)) --> \(srtTime(cue.endMS))\n\(cue.text)\n\n"
+ }
+ return out
+ }
+
+ /// `HH:MM:SS,mmm` SRT timestamp.
+ public static func srtTime(_ ms: Int) -> String {
+ let total = max(0, ms)
+ return String(
+ format: "%02d:%02d:%02d,%03d",
+ total / 3_600_000, (total % 3_600_000) / 60_000, (total % 60_000) / 1000, total % 1000
+ )
+ }
+
+ /// ffmpeg accepts a bare-seconds time spec for `-ss`/`-t`; three decimals is well under frame precision.
+ public static func seconds(_ value: Double) -> String { String(format: "%.3f", max(0, value)) }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/media/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/media/SKILL.md
index ad58580c..577c00b1 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/media/SKILL.md
+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/media/SKILL.md
@@ -4,7 +4,7 @@ id: media
description: Expert audio and video — download from a URL with yt-dlp, transcode/trim/extract/grab frames with ffmpeg, transcribe/subtitle/translate, cut filler words or silence with word-level timing, and reframe landscape to vertical 9:16 that tracks the active speaker.
tags: video, audio, media, download, convert, youtube, subtitles, transcribe, edit, reframe, vertical
keywords: video, audio, download, youtube, vimeo, mp4, mp3, convert, trim, clip, extract audio, transcode, frame, subtitle, subtitles, caption, captions, transcribe, transcript, translate, srt, vtt, filler words, remove silence, um, uh, jump cut, tighten, reframe, vertical, 9:16, portrait, tiktok, reels, shorts, crop to vertical, active speaker, follow speaker
-tools: shell_exec, transcribe, llm.generate, files.write
+tools: media.caption, shell_exec, transcribe, llm.generate, files.write
`yt-dlp` and `ffmpeg`/`ffprobe` are bundled, signed, and on the PATH, so use them
by bare name. They are first-party capability tools: downloading from the user's
@@ -40,23 +40,20 @@ case say the media tools are still installing and stop. Do not try to install an
- **`transcribe` (on-device, word-level).** Runs Apple's local speech engine on an audio file and writes a JSON file holding the plain `text` plus `words` — every word with a `start`/`end` in seconds, accurate to a fraction of a second. Private, no credits. Use it whenever you need to know *exactly when* words are spoken: cutting filler words or silence, finding a quoted moment, chaptering. Hand it compact audio (extract it from a video first); if it reports no transcript, extract audio and retry.
- **`llm.generate` SRT (the model).** Sentence-level cues with approximate timing — fine for subtitles, not precise enough to cut individual words. Use it for translation or when you just need readable captions.
-## Subtitles & transcription
-Get the subtitle text, then apply it. Prefer the cheapest source that gives correct timing.
+## Subtitles, captions, and translation
+**Use the `media.caption` tool — it does the whole job in one call.** Give it the video (a local path or a
+URL), and optionally a language to `translateTo` (e.g. "Korean") and a `clipStart`/`clipDuration` to caption
+just a span. It transcribes on-device for exact timings, translates with one model call when asked, builds a
+clean SRT in code, and burns the captions in with a known-good encoder — then returns the captioned file.
-1. **Reuse the video's own captions first (free — no model call).** Many videos already ship captions; pull them as a sidecar `.srt`:
- `yt-dlp --write-subs --write-auto-subs --sub-langs 'en.*' --convert-subs srt --skip-download -P ~/Downloads 'URL'` (drop `--skip-download` to grab the video too).
-2. **Otherwise transcribe with the model.** Timing matters: **clip first, then transcribe the clip** so timestamps start at zero and line up. Extract compact mono audio, then call `llm.generate` with that file:
- - `ffmpeg -i clip.mp4 -vn -ac 1 -c:a libmp3lame -b:a 64k clip.mp3`
- - `llm.generate filePath=clip.mp3 prompt="Transcribe this audio to SRT with timestamps, one cue per sentence" toFile=true` → the returned file ALREADY holds your SRT text. Use that path directly (or `mv` it to `subs.srt`); never re-type its contents into a `cat`/`echo` heredoc — that re-typing is the most common way this task stalls.
-3. **Translate** by asking in the same call: `prompt="Transcribe this audio and translate the text to Spanish; output SRT, keep the timestamps"`.
-4. **Long media — chunk it.** Inline audio is size-limited (`llm.generate` rejects a file that is too large or a transcript it had to truncate — both mean "use smaller chunks"). Split, transcribe each zero-based, then shift by each segment's *real* start:
- - `ffmpeg -i audio.mp3 -f segment -segment_time 600 -reset_timestamps 1 -c copy seg_%03d.mp3` splits into ~10-min pieces.
- - `-c copy` cuts on frame boundaries, so a segment's real length is not exactly 600s. Read each one's true duration with `ffprobe -v error -show_entries format=duration -of csv=p=0 seg_000.mp3` and accumulate; that running sum is the next segment's start offset — do not assume `index × 600`.
- - Transcribe each segment with a plain zero-based prompt (`"Transcribe to SRT with timestamps"`), then add the accumulated offset to every cue in that segment's SRT and concatenate in order, renumbering cue indices. Sanity-check that timestamps only increase. Persist the assembled SRT with `files.write path=~/Downloads/subs.srt content=…` (the whole multi-line file in one call) — not a shell heredoc.
-5. **Apply to the video (ffmpeg):**
- - Burn-in (default for a shareable clip — always-visible, what social players expect): `ffmpeg -i clip.mp4 -vf "subtitles=subs.srt" -c:a copy out.mp4`. Donkey's bundled ffmpeg includes libass, so this works by default. If you ever do hit a filtergraph error — `No such filter: 'subtitles'`, `Error parsing filterchain 'subtitles=…'`, or `No option name near '…'` — that is an ffmpeg without libass, **not** a path problem: don't retry the same command or fiddle with absolute-vs-relative paths or escaping. Switch straight to the soft track below (no libass needed) and tell the user you delivered a toggleable subtitle track instead of burned-in text.
- - Soft, toggleable track (the reliable fallback, and fine for an archive copy): `ffmpeg -i clip.mp4 -i subs.srt -c copy -c:s mov_text out.mp4`. This muxes the translation into the file as a real subtitle stream with no libass and no re-encode, so it works even when burn-in can't.
-- Model timestamps are approximate (good enough for subtitles); always extract audio before transcribing, and chunk long files.
+Do **not** hand-build the transcribe → SRT → burn pipeline with `llm.generate` and `ffmpeg`. A model-authored
+SRT comes back messy (stray prose, the wrong language, broken cues), so you end up re-cleaning it, writing a
+filter script, and debugging encoders and durations — dozens of round-trips for a one-call job. `media.caption`
+is built to avoid exactly that.
+
+Reach for raw ffmpeg only to apply a subtitle file the user already has:
+- Burn-in: `ffmpeg -i clip.mp4 -vf "subtitles=subs.srt" -c:v libx264 -pix_fmt yuv420p -c:a aac out.mp4`.
+- Soft, toggleable track (no libass, no re-encode): `ffmpeg -i clip.mp4 -i subs.srt -c copy -c:s mov_text out.mp4`.
## Cut filler words or silence
Use the **`media.cut`** tool — a deterministic, frame-accurate editor. It does the span math and the ffmpeg render itself; you only say what to remove. Do NOT hand-build select/trim/concat ffmpeg for this.
diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/shorts/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/shorts/SKILL.md
index e27312c2..461120ac 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/shorts/SKILL.md
+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/shorts/SKILL.md
@@ -4,33 +4,34 @@ id: shorts
description: Turn a long video or podcast into vertical short-form clips for TikTok, Reels, and Shorts — pick the strong moments, crop to 9:16 tracking whoever is speaking, and burn in captions.
tags: shorts, tiktok, reels, vertical, clips, highlights, podcast, captions, social
keywords: tiktok, reels, shorts, vertical video, 9:16, portrait, clip, clips, highlight, highlights, snippet, snippets, podcast clip, social media clip, captions, subtitles, reframe, repurpose, turn into clips, best moments
+tools: shorts.make, user.choose
-Turn a long recording into short vertical clips ready to post. This skill orchestrates the
-pieces — the actual download/transcribe/cut/caption commands live in the `media` skill, and the
-landscape→vertical speaker-tracking crop is the bundled `reframe` tool. Reach for it on asks like
+Turn a long recording into short vertical clips ready to post. Reach for this skill on asks like
"make TikToks from this podcast", "cut this interview into Reels", "vertical clips with subtitles".
-## The pipeline
-1. **Get the source.** A local file is ready to use. A URL: download it with `yt-dlp` (see `media`).
- For a long source, also pull the transcript/captions — reuse the video's own captions when it has
- them (free), otherwise transcribe (see `media`). You need text with timestamps to choose moments.
-2. **Pick the moments.** Read the timestamped transcript and choose self-contained spans that land —
- a complete thought with a hook and a payoff, usually 15–60s. Don't cut mid-sentence. Propose the
- moments (with timestamps) and, when the user hasn't said how many, confirm how many clips they want.
-3. **Cut each span.** Trim it out with `ffmpeg` (see `media`). Transcribe the *clip* (not the whole
- source) so caption timestamps start at zero and line up.
-4. **Reframe to vertical.** Run `reframe --input clip.mp4 --output clip_v.mp4 --aspect 9:16` — it
- crops to 9:16 and follows whoever is talking (a still listener is ignored, and it cuts on scene
- changes). Pass a generous `timeoutSeconds`. This is the step that makes a landscape two-person
- podcast watchable on a phone.
-5. **Caption it.** Burn the clip's subtitles onto the vertical file (see `media`), so the text is
- sized to the 9:16 frame. Burned-in captions are what social players expect.
-
-Output one `*_v.mp4` per moment, captioned, in the user's Downloads (or a folder they name).
-
-## Keep in mind
-- Reframe first, caption second — captions burned before reframing would get cropped or shrunk.
-- A talking-head or multi-person conversation is the sweet spot. Heavy B-roll or fast cutting has no
- single speaker to follow; `reframe` falls back to a centered crop, so a fixed `ffmpeg` crop is just
- as good there — say so rather than implying it tracked a subject.
-- Picking the moment is judgment, not a formula: favor a strong opening line and a clear payoff.
+## Use `shorts.make` — it runs the whole pipeline in one call
+
+`shorts.make` does the entire job end-to-end: it transcribes the source on-device, picks the strongest
+self-contained moments, cuts each one, reframes it to vertical 9:16 following whoever is speaking, and
+burns in captions — then returns the finished clip files. Do this in **one** tool call. Do **not** drive
+`yt-dlp`/`ffmpeg`/`transcribe`/`reframe` yourself step by step: that path costs a model round-trip at
+every step and clip, and `shorts.make` is the supported way to make shorts.
+
+- `source` — a local video path, or a URL (it downloads with `yt-dlp` itself).
+- `count` — how many clips. **If the user didn't say how many, ask with `user.choose` before calling.**
+ Picking the count is the user's call; everything after it is automatic.
+- `aspect` — defaults to `9:16`. Pass `aspect="original"` to caption a clip **without** reframing, e.g.
+ "just add subtitles to this video".
+
+The finished `*_captioned.mp4` files come back in the conversation's folder, one per moment.
+
+## What it handles for you
+
+- A talking-head or multi-person conversation is the sweet spot — reframe follows the active speaker and
+ cuts on scene changes. Heavy B-roll with no single speaker falls back to a centered crop.
+- Captions are burned in (what social players expect); if a clip can't be captioned it still ships,
+ reframed, and the summary says which clips fell back.
+- Reframe happens before captions, so the text is sized to the 9:16 frame.
+
+For one-off lower-level media work that isn't the full shorts pipeline — a plain trim, a format convert,
+reusing a video's existing caption track — see the `media` skill.
diff --git a/apps/Donkey/Sources/DonkeyRuntime/ShortsOrchestrator.swift b/apps/Donkey/Sources/DonkeyRuntime/ShortsOrchestrator.swift
new file mode 100644
index 00000000..1a64d0c0
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/ShortsOrchestrator.swift
@@ -0,0 +1,265 @@
+import DonkeyHarness
+import Foundation
+
+/// One clip-worthy span of the source, in seconds, chosen by the single model call the shorts pipeline
+/// makes. `title` is a short human label used only for the summary.
+public struct MomentSpan: Sendable {
+ public var startSec: Double
+ public var endSec: Double
+ public var title: String
+
+ public init(startSec: Double, endSec: Double, title: String = "") {
+ self.startSec = startSec
+ self.endSec = endSec
+ self.title = title
+ }
+
+ public var durationSec: Double { max(0, endSec - startSec) }
+}
+
+/// The deterministic pipeline behind `shorts.make`: source → ONE model call to pick the moments → per clip
+/// cut, transcribe on-device, reframe to vertical, burn captions — all in fixed code. `selectMoments` is the
+/// only model call; transcription is on-device and the cut/reframe/caption steps are bundled tools, so once
+/// the moments are chosen the clips are produced without ever returning to the planner. That is what turns a
+/// ~37-call, dollar-plus run into a single decision plus local rendering.
+///
+/// ```
+/// resolve source (yt-dlp if URL)
+/// → extract audio → transcribe whole source (on-device)
+/// → selectMoments ← the ONE model call
+/// → fan out per moment, all deterministic:
+/// cut span → transcribe clip → reframe 9:16 → burn captions
+/// ```
+public struct ShortsOrchestrator: Sendable {
+ public typealias SelectMoments = @Sendable (_ timestampedTranscript: String, _ desiredCount: Int?) async -> [MomentSpan]?
+ public typealias Transcribe = @Sendable (HarnessTranscriptionRequest) async -> HarnessTranscriptionResult?
+
+ private let selectMoments: SelectMoments
+ private let transcribe: Transcribe
+ private let runTool: MediaPipeline.ToolRunner
+
+ public init(
+ selectMoments: @escaping SelectMoments,
+ transcribe: @escaping Transcribe,
+ runTool: @escaping MediaPipeline.ToolRunner = MediaPipeline.bundledToolRunner
+ ) {
+ self.selectMoments = selectMoments
+ self.transcribe = transcribe
+ self.runTool = runTool
+ }
+
+ public func make(_ request: HarnessShortsRequest) async -> HarnessShortsOutcome {
+ // Working directory: the conversation's own folder when present, else home — same rule as shell_exec
+ // and the form filler, so produced clips land beside the rest of the task's output.
+ let workdir = DonkeyCommandBackends.resolvedWorkingDirectoryPath(request.workingDirectory)
+
+ // 1. Resolve the source to a local file (download a URL with yt-dlp first). Resolve ONCE — a second
+ // call would re-download the URL.
+ let sourcePath: String
+ switch resolveSource(request.source, workdir: workdir) {
+ case .ok(let resolved): sourcePath = resolved
+ case .failed(let reason): return Self.fail(reason)
+ }
+
+ // 2. Extract compact audio and transcribe the whole source on-device — the timing the moment
+ // selection reads. Free and private; no model call.
+ let sourceAudio = (workdir as NSString).appendingPathComponent("source_audio.mp3")
+ let audioStep = MediaPipeline.runStep(
+ "ffmpeg",
+ ["-y", "-i", sourcePath, "-vn", "-ac", "1", "-c:a", "libmp3lame", "-b:a", "64k", sourceAudio],
+ workingDirectory: workdir, expecting: sourceAudio, using: runTool
+ )
+ if case let .failed(reason) = audioStep {
+ return Self.fail("Could not read audio from the source: \(reason)")
+ }
+ guard let fullTranscript = await transcribe(HarnessTranscriptionRequest(filePath: sourceAudio)),
+ fullTranscript.failureReason == nil, !fullTranscript.words.isEmpty else {
+ return Self.fail("Could not transcribe the source to choose moments.")
+ }
+
+ // 3. THE ONE MODEL CALL: choose the clip-worthy spans from the timestamped transcript.
+ let timestamped = Self.timestampedTranscript(fullTranscript.words)
+ guard let moments = await selectMoments(timestamped, request.desiredCount), !moments.isEmpty else {
+ return Self.fail("Could not find clip-worthy moments in the source.")
+ }
+ let chosen = request.desiredCount.map { Array(moments.prefix(max(1, $0))) } ?? moments
+
+ // 4. Per clip, all deterministic — no planner round-trip between any of these.
+ let aspect = (request.aspect?.isEmpty == false) ? request.aspect! : "9:16"
+ let reframeWanted = !["original", "keep", "none", "source"].contains(aspect.lowercased())
+ let result = await MediaPipeline.fanOut(chosen) { index, moment in
+ await makeClip(
+ index: index, moment: moment, sourcePath: sourcePath,
+ workdir: workdir, aspect: aspect, reframe: reframeWanted
+ )
+ }
+
+ guard !result.produced.isEmpty else {
+ return Self.fail("Shorts pipeline produced no clips: \(result.failures.first ?? "no clip could be rendered")")
+ }
+ let kind = reframeWanted ? "vertical " : ""
+ var summary = "Made \(result.produced.count) captioned \(kind)clip\(result.produced.count == 1 ? "" : "s")."
+ if !result.failures.isEmpty {
+ summary += " \(result.failures.count) clip\(result.failures.count == 1 ? "" : "s") could not be finished."
+ }
+ return HarnessShortsOutcome(text: summary, succeeded: true, producedFiles: result.produced)
+ }
+
+ // MARK: - Per-clip pipeline
+
+ /// Cut one span, caption it from an on-device transcription of the clip, reframe to vertical, and burn
+ /// the captions on. Captioning and reframing degrade gracefully — a clip with no transcript or a reframe
+ /// that fails still ships, so one weak moment never sinks the whole job.
+ private func makeClip(
+ index: Int, moment: MomentSpan, sourcePath: String,
+ workdir: String, aspect: String, reframe: Bool
+ ) async -> PipelineItemOutcome {
+ let n = index + 1
+ func path(_ name: String) -> String { (workdir as NSString).appendingPathComponent(name) }
+
+ // a. Cut the span. Accurate seek (after -i) and a clean re-encode, so the clip is frame-accurate
+ // rather than snapped to the nearest keyframe.
+ let clip = path("clip_\(n).mp4")
+ let cut = MediaPipeline.runStep(
+ "ffmpeg",
+ ["-y", "-i", sourcePath, "-ss", Self.seconds(moment.startSec), "-t", Self.seconds(max(0.5, moment.durationSec)),
+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-c:a", "aac", clip],
+ workingDirectory: workdir, expecting: clip, using: runTool
+ )
+ if case let .failed(reason) = cut { return .failed(reason: "clip \(n): could not cut the span — \(reason)") }
+
+ // b. Transcribe the clip (zero-based) for caption timings and write an SRT. Best-effort.
+ let srtPath = await captionSRT(forClip: clip, index: n, workdir: workdir)
+
+ // c. Reframe to vertical, following the active speaker. On failure keep the original framing.
+ var base = clip
+ if reframe {
+ let vertical = path("clip_\(n)_v.mp4")
+ let reframed = MediaPipeline.runStep(
+ "reframe",
+ ["--input", clip, "--output", vertical, "--aspect", aspect, "--height", "1920"],
+ workingDirectory: workdir, expecting: vertical, using: runTool
+ )
+ if case .ok = reframed { base = vertical }
+ }
+
+ // d. Burn the captions on; fall back to a soft track if this ffmpeg lacks libass, and to the
+ // uncaptioned clip if even that fails.
+ guard let srt = srtPath else { return .produced([base]) }
+ let final = path("clip_\(n)_captioned.mp4")
+ let burn = MediaPipeline.runStep(
+ "ffmpeg",
+ ["-y", "-i", base, "-vf", "subtitles=\((srt as NSString).lastPathComponent)", "-c:a", "copy", final],
+ workingDirectory: workdir, expecting: final, using: runTool
+ )
+ if case .ok = burn { return .produced([final]) }
+ let soft = MediaPipeline.runStep(
+ "ffmpeg",
+ ["-y", "-i", base, "-i", srt, "-c", "copy", "-c:s", "mov_text", final],
+ workingDirectory: workdir, expecting: final, using: runTool
+ )
+ if case .ok = soft { return .produced([final]) }
+ return .produced([base])
+ }
+
+ /// Extract compact audio from the clip, transcribe it on-device (timings zero-based to the clip), and
+ /// write an SRT next to it. Returns the SRT path, or nil when the clip has no usable transcript.
+ private func captionSRT(forClip clip: String, index n: Int, workdir: String) async -> String? {
+ let clipAudio = (workdir as NSString).appendingPathComponent("clip_\(n).mp3")
+ let audio = MediaPipeline.runStep(
+ "ffmpeg",
+ ["-y", "-i", clip, "-vn", "-ac", "1", "-c:a", "libmp3lame", "-b:a", "64k", clipAudio],
+ workingDirectory: workdir, expecting: clipAudio, using: runTool
+ )
+ guard case .ok = audio,
+ let transcript = await transcribe(HarnessTranscriptionRequest(filePath: clipAudio)),
+ transcript.failureReason == nil, !transcript.words.isEmpty else {
+ return nil
+ }
+ let srtPath = (workdir as NSString).appendingPathComponent("clip_\(n).srt")
+ guard (try? Self.makeSRT(transcript.words).write(toFile: srtPath, atomically: true, encoding: .utf8)) != nil else {
+ return nil
+ }
+ return srtPath
+ }
+
+ // MARK: - Source resolution
+
+ private func resolveSource(_ source: String, workdir: String) -> MediaStepResult {
+ let trimmed = source.trimmingCharacters(in: .whitespacesAndNewlines)
+ let lower = trimmed.lowercased()
+ if lower.hasPrefix("http://") || lower.hasPrefix("https://") {
+ // Pin the output path and force a real download (--no-simulate), then read the exact final path
+ // yt-dlp prints, so later steps never hunt for the file.
+ let template = (workdir as NSString).appendingPathComponent("source.%(ext)s")
+ let result = runTool(
+ "yt-dlp",
+ ["-o", template, "--no-simulate", "--print", "after_move:filepath",
+ "--retries", "5", "--extractor-retries", "3", trimmed],
+ workdir
+ )
+ guard result.exitCode == 0 else {
+ let why = result.stderr.isEmpty ? result.stdout : result.stderr
+ return .failed(reason: "yt-dlp could not download the source: \(MediaPipeline.lastLines(why))")
+ }
+ let printed = result.stdout
+ .split(whereSeparator: \.isNewline)
+ .map { $0.trimmingCharacters(in: .whitespaces) }
+ .last(where: { !$0.isEmpty })
+ if let printed, FileManager.default.fileExists(atPath: printed) {
+ return .ok(producedPath: printed)
+ }
+ return .failed(reason: "yt-dlp finished but its downloaded file path could not be determined.")
+ }
+ let expanded = (trimmed as NSString).expandingTildeInPath
+ let resolved = (expanded as NSString).isAbsolutePath
+ ? expanded
+ : (workdir as NSString).appendingPathComponent(expanded)
+ if FileManager.default.fileExists(atPath: resolved) {
+ return .ok(producedPath: resolved)
+ }
+ return .failed(reason: "No source video at \(source).")
+ }
+
+ // MARK: - Formatting helpers
+
+ private static func fail(_ text: String) -> HarnessShortsOutcome {
+ HarnessShortsOutcome(text: text, succeeded: false, producedFiles: [])
+ }
+
+ /// ffmpeg accepts a bare-seconds time spec for `-ss`/`-t`; three decimals is well under frame precision.
+ static func seconds(_ value: Double) -> String { MediaSubtitles.seconds(value) }
+
+ /// Render the transcript one line per ~12 words, each prefixed with its `[m:ss]` start, so the moment
+ /// selector can name spans by time.
+ static func timestampedTranscript(_ words: [HarnessTranscriptionWord]) -> String {
+ var lines: [String] = []
+ var current: [HarnessTranscriptionWord] = []
+ func flush() {
+ guard let first = current.first else { return }
+ lines.append("[\(clock(first.startMS))] " + current.map(\.text).joined(separator: " "))
+ current = []
+ }
+ for word in words {
+ current.append(word)
+ let endsSentence = word.text.last.map { ".!?".contains($0) } ?? false
+ if current.count >= 12 || endsSentence { flush() }
+ }
+ flush()
+ return lines.joined(separator: "\n")
+ }
+
+ /// Build an SRT from per-word timings — cue grouping and rendering shared with the caption pipeline.
+ static func makeSRT(_ words: [HarnessTranscriptionWord]) -> String {
+ MediaSubtitles.srt(from: MediaSubtitles.cues(from: words))
+ }
+
+ /// `m:ss` clock for the transcript markers the selector reads.
+ static func clock(_ ms: Int) -> String {
+ let total = max(0, ms) / 1000
+ return String(format: "%d:%02d", total / 60, total % 60)
+ }
+
+ /// `HH:MM:SS,mmm` SRT timestamp.
+ static func srtTime(_ ms: Int) -> String { MediaSubtitles.srtTime(ms) }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/CaptionOrchestratorTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/CaptionOrchestratorTests.swift
new file mode 100644
index 00000000..0fc88a68
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/CaptionOrchestratorTests.swift
@@ -0,0 +1,127 @@
+import Foundation
+import Testing
+@testable import DonkeyHarness
+@testable import DonkeyRuntime
+
+/// The caption pipeline's point: subtitling a video is ONE call (or zero when no translation is asked for),
+/// with the SRT built in code and the burn done with a fixed encoder — no per-tool planner round-trips and no
+/// model-authored-SRT cleanup loop.
+@Suite
+struct CaptionOrchestratorTests {
+ private final class Recorder: @unchecked Sendable {
+ private let lock = NSLock()
+ private(set) var translateCalls = 0
+ private(set) var toolRuns: [String] = []
+
+ func recordTranslate() { lock.lock(); translateCalls += 1; lock.unlock() }
+ func recordTool(_ name: String) { lock.lock(); toolRuns.append(name); lock.unlock() }
+ }
+
+ private static func stubRunner(_ recorder: Recorder) -> MediaPipeline.ToolRunner {
+ { name, arguments, _ in
+ recorder.recordTool(name)
+ for argument in arguments where argument.hasPrefix("/") {
+ if ["mp4", "mp3", "srt"].contains((argument as NSString).pathExtension.lowercased()) {
+ FileManager.default.createFile(atPath: argument, contents: Data())
+ }
+ }
+ return (0, "", "")
+ }
+ }
+
+ private static func words(_ count: Int) -> [HarnessTranscriptionWord] {
+ (0..<count).map { HarnessTranscriptionWord(text: "word\($0)", startMS: $0 * 400, endMS: $0 * 400 + 300) }
+ }
+
+ private func makeWorkdir() -> String {
+ let dir = (NSTemporaryDirectory() as NSString).appendingPathComponent("caption-test-\(UUID().uuidString)")
+ try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
+ return dir
+ }
+
+ @Test
+ func translatingCaptionsMakesExactlyOneModelCall() async throws {
+ let recorder = Recorder()
+ let workdir = makeWorkdir()
+ defer { try? FileManager.default.removeItem(atPath: workdir) }
+ let source = (workdir as NSString).appendingPathComponent("input.mp4")
+ FileManager.default.createFile(atPath: source, contents: Data())
+
+ let orchestrator = CaptionOrchestrator(
+ translateCues: { lines, language in
+ recorder.recordTranslate()
+ return lines.map { "[\(language)] \($0)" }
+ },
+ transcribe: { _ in HarnessTranscriptionResult(text: "x", words: Self.words(20), backend: "stub") },
+ runTool: Self.stubRunner(recorder)
+ )
+
+ let outcome = await orchestrator.caption(
+ HarnessCaptionRequest(source: source, translateTo: "Korean", workingDirectory: workdir)
+ )
+
+ #expect(outcome.succeeded)
+ #expect(outcome.producedFiles.count == 1)
+ #expect(recorder.translateCalls == 1)
+ // A captions file was actually written in code (no model-authored SRT).
+ #expect(FileManager.default.fileExists(atPath: (workdir as NSString).appendingPathComponent("captions.srt")))
+ }
+
+ @Test
+ func captioningWithoutTranslationMakesNoModelCalls() async throws {
+ let recorder = Recorder()
+ let workdir = makeWorkdir()
+ defer { try? FileManager.default.removeItem(atPath: workdir) }
+ let source = (workdir as NSString).appendingPathComponent("input.mp4")
+ FileManager.default.createFile(atPath: source, contents: Data())
+
+ let orchestrator = CaptionOrchestrator(
+ translateCues: { _, _ in recorder.recordTranslate(); return nil },
+ transcribe: { _ in HarnessTranscriptionResult(text: "x", words: Self.words(12), backend: "stub") },
+ runTool: Self.stubRunner(recorder)
+ )
+
+ let outcome = await orchestrator.caption(
+ HarnessCaptionRequest(source: source, workingDirectory: workdir)
+ )
+ #expect(outcome.succeeded)
+ #expect(outcome.producedFiles.count == 1)
+ #expect(recorder.translateCalls == 0)
+ }
+
+ @Test
+ func missingSourceFailsCleanly() async throws {
+ let recorder = Recorder()
+ let workdir = makeWorkdir()
+ defer { try? FileManager.default.removeItem(atPath: workdir) }
+
+ let orchestrator = CaptionOrchestrator(
+ translateCues: { _, _ in recorder.recordTranslate(); return nil },
+ transcribe: { _ in HarnessTranscriptionResult(text: "x", words: Self.words(8), backend: "stub") },
+ runTool: Self.stubRunner(recorder)
+ )
+ let outcome = await orchestrator.caption(
+ HarnessCaptionRequest(source: "/no/such/file.mp4", translateTo: "Korean", workingDirectory: workdir)
+ )
+ #expect(outcome.succeeded == false)
+ #expect(recorder.translateCalls == 0)
+ }
+
+ @Test
+ func parseSecondsHandlesBareAndClockForms() {
+ #expect(CaptionOrchestrator.parseSeconds("90") == 90)
+ #expect(CaptionOrchestrator.parseSeconds("1:30") == 90)
+ #expect(CaptionOrchestrator.parseSeconds("1:00:00") == 3600)
+ #expect(CaptionOrchestrator.parseSeconds("") == nil)
+ }
+
+ @Test
+ func mediaSubtitlesBuildsValidSRT() {
+ let cues = MediaSubtitles.cues(from: Self.words(16))
+ #expect(!cues.isEmpty)
+ let srt = MediaSubtitles.srt(from: cues)
+ #expect(srt.hasPrefix("1\n"))
+ #expect(srt.contains(" --> "))
+ #expect(srt.contains("00:00:00,000"))
+ }
+}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/ShortsOrchestratorTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/ShortsOrchestratorTests.swift
new file mode 100644
index 00000000..01544915
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/ShortsOrchestratorTests.swift
@@ -0,0 +1,183 @@
+import Foundation
+import Testing
+@testable import DonkeyHarness
+@testable import DonkeyRuntime
+
+/// The shorts pipeline's whole point: a multi-clip run makes exactly ONE model call (moment selection) and
+/// renders the clips deterministically, with no planner round-trip between steps. These tests stub the
+/// bundled tools and the two injected boundaries so the control flow is verified without real ffmpeg.
+@Suite
+struct ShortsOrchestratorTests {
+ /// Thread-safe recorder for the synchronous tool runner and the async decision closure.
+ private final class Recorder: @unchecked Sendable {
+ private let lock = NSLock()
+ private(set) var selectMomentsCalls = 0
+ private(set) var transcribeCalls = 0
+ private(set) var toolRuns: [String] = []
+
+ func recordSelect() { lock.lock(); selectMomentsCalls += 1; lock.unlock() }
+ func recordTranscribe() { lock.lock(); transcribeCalls += 1; lock.unlock() }
+ func recordTool(_ name: String) { lock.lock(); toolRuns.append(name); lock.unlock() }
+ }
+
+ /// A tool runner that touches every path-like argument (so `runStep`'s file-existence check passes) and
+ /// always succeeds — standing in for ffmpeg/reframe without running them.
+ private static func stubRunner(_ recorder: Recorder) -> MediaPipeline.ToolRunner {
+ { name, arguments, workingDirectory in
+ recorder.recordTool(name)
+ for argument in arguments where argument.hasPrefix("/") {
+ let ext = (argument as NSString).pathExtension.lowercased()
+ if ["mp4", "mp3", "srt", "wav", "m4a"].contains(ext) {
+ FileManager.default.createFile(atPath: argument, contents: Data())
+ }
+ }
+ return (0, "", "")
+ }
+ }
+
+ private static func words(_ count: Int) -> [HarnessTranscriptionWord] {
+ (0..<count).map { i in
+ HarnessTranscriptionWord(text: "word\(i)", startMS: i * 500, endMS: i * 500 + 400)
+ }
+ }
+
+ private func makeWorkdir() -> String {
+ let dir = (NSTemporaryDirectory() as NSString)
+ .appendingPathComponent("shorts-test-\(UUID().uuidString)")
+ try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
+ return dir
+ }
+
+ @Test
+ func multiClipRunMakesExactlyOneModelCall() async throws {
+ let recorder = Recorder()
+ let workdir = makeWorkdir()
+ defer { try? FileManager.default.removeItem(atPath: workdir) }
+ let source = (workdir as NSString).appendingPathComponent("input.mp4")
+ FileManager.default.createFile(atPath: source, contents: Data())
+
+ let orchestrator = ShortsOrchestrator(
+ selectMoments: { _, _ in
+ recorder.recordSelect()
+ return [
+ MomentSpan(startSec: 0, endSec: 20, title: "One"),
+ MomentSpan(startSec: 30, endSec: 55, title: "Two")
+ ]
+ },
+ transcribe: { _ in
+ recorder.recordTranscribe()
+ return HarnessTranscriptionResult(text: "hello world", words: Self.words(8), backend: "stub")
+ },
+ runTool: Self.stubRunner(recorder)
+ )
+
+ let outcome = await orchestrator.make(
+ HarnessShortsRequest(source: source, desiredCount: nil, aspect: "9:16", workingDirectory: workdir)
+ )
+
+ #expect(outcome.succeeded)
+ #expect(outcome.producedFiles.count == 2)
+ // The whole guarantee: ONE model call for the two-clip job, no matter how many tools ran.
+ #expect(recorder.selectMomentsCalls == 1)
+ // On-device transcription is free: once for the source + once per clip.
+ #expect(recorder.transcribeCalls == 3)
+ // reframe ran once per clip; ffmpeg ran several times — all without returning to the planner.
+ #expect(recorder.toolRuns.filter { $0 == "reframe" }.count == 2)
+ for path in outcome.producedFiles {
+ #expect(FileManager.default.fileExists(atPath: path))
+ }
+ }
+
+ @Test
+ func desiredCountCapsTheClips() async throws {
+ let recorder = Recorder()
+ let workdir = makeWorkdir()
+ defer { try? FileManager.default.removeItem(atPath: workdir) }
+ let source = (workdir as NSString).appendingPathComponent("input.mp4")
+ FileManager.default.createFile(atPath: source, contents: Data())
+
+ let orchestrator = ShortsOrchestrator(
+ selectMoments: { _, _ in
+ recorder.recordSelect()
+ return (0..<5).map { MomentSpan(startSec: Double($0) * 60, endSec: Double($0) * 60 + 20) }
+ },
+ transcribe: { _ in
+ HarnessTranscriptionResult(text: "x", words: Self.words(6), backend: "stub")
+ },
+ runTool: Self.stubRunner(recorder)
+ )
+
+ let outcome = await orchestrator.make(
+ HarnessShortsRequest(source: source, desiredCount: 2, workingDirectory: workdir)
+ )
+ #expect(outcome.succeeded)
+ #expect(outcome.producedFiles.count == 2)
+ }
+
+ @Test
+ func aspectOriginalSkipsReframe() async throws {
+ let recorder = Recorder()
+ let workdir = makeWorkdir()
+ defer { try? FileManager.default.removeItem(atPath: workdir) }
+ let source = (workdir as NSString).appendingPathComponent("input.mp4")
+ FileManager.default.createFile(atPath: source, contents: Data())
+
+ let orchestrator = ShortsOrchestrator(
+ selectMoments: { _, _ in [MomentSpan(startSec: 0, endSec: 30)] },
+ transcribe: { _ in HarnessTranscriptionResult(text: "x", words: Self.words(6), backend: "stub") },
+ runTool: Self.stubRunner(recorder)
+ )
+
+ let outcome = await orchestrator.make(
+ HarnessShortsRequest(source: source, aspect: "original", workingDirectory: workdir)
+ )
+ #expect(outcome.succeeded)
+ #expect(recorder.toolRuns.contains("reframe") == false)
+ }
+
+ @Test
+ func missingSourceFailsCleanly() async throws {
+ let recorder = Recorder()
+ let workdir = makeWorkdir()
+ defer { try? FileManager.default.removeItem(atPath: workdir) }
+
+ let orchestrator = ShortsOrchestrator(
+ selectMoments: { _, _ in recorder.recordSelect(); return [MomentSpan(startSec: 0, endSec: 10)] },
+ transcribe: { _ in HarnessTranscriptionResult(text: "x", words: Self.words(4), backend: "stub") },
+ runTool: Self.stubRunner(recorder)
+ )
+
+ let outcome = await orchestrator.make(
+ HarnessShortsRequest(source: "/no/such/file.mp4", workingDirectory: workdir)
+ )
+ #expect(outcome.succeeded == false)
+ #expect(outcome.producedFiles.isEmpty)
+ // No source means no model call at all.
+ #expect(recorder.selectMomentsCalls == 0)
+ }
+
+ @Test
+ func srtTimeFormatsAsHoursMinutesSecondsMillis() {
+ #expect(ShortsOrchestrator.srtTime(0) == "00:00:00,000")
+ #expect(ShortsOrchestrator.srtTime(1_500) == "00:00:01,500")
+ #expect(ShortsOrchestrator.srtTime(3_661_250) == "01:01:01,250")
+ }
+
+ @Test
+ func makeSRTBreaksOnSentencePunctuationAndLength() {
+ let words = [
+ HarnessTranscriptionWord(text: "Hello", startMS: 0, endMS: 400),
+ HarnessTranscriptionWord(text: "there.", startMS: 450, endMS: 900),
+ HarnessTranscriptionWord(text: "How", startMS: 1_000, endMS: 1_200),
+ HarnessTranscriptionWord(text: "are", startMS: 1_250, endMS: 1_400),
+ HarnessTranscriptionWord(text: "you?", startMS: 1_450, endMS: 1_800)
+ ]
+ let srt = ShortsOrchestrator.makeSRT(words)
+ #expect(srt.contains("Hello there."))
+ #expect(srt.contains("How are you?"))
+ #expect(srt.contains("00:00:00,000 --> 00:00:00,900"))
+ // Two cues, numbered.
+ #expect(srt.contains("\n1\n") || srt.hasPrefix("1\n"))
+ #expect(srt.contains("2\n"))
+ }
+}