Skip to content

Open source CapCut alternative.

TypeScript

feat(app): register web.automate and multimodal llm.generate harness tools

David Le3c4a3bd9da1b
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index cc689123..97b823d8 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -532,13 +532,20 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
harnessServices.imageGenerator = { request in
await imageGenerator.generate(request)
}
+ // Same boundary, multimodal arm: transcribe/translate/caption a local audio or video file
+ // (the media skill extracts audio and reaches for this to subtitle a clip).
+ harnessServices.mediaGenerator = { prompt, fileURL, mimeType in
+ await textGenerator.generate(prompt, attachmentPath: fileURL, mimeType: mimeType)
+ }
// 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.
let hostedWebSearch = HostedWebSearch(backend: backend)
let hostedWebFetch = HostedWebFetch(backend: backend)
+ let hostedWebAutomate = HostedWebAutomate(backend: backend)
harnessServices.webSearcher = { query in await hostedWebSearch.search(query) }
harnessServices.webFetcher = { url in await hostedWebFetch.fetch(url) }
+ harnessServices.webAutomator = { request in await hostedWebAutomate.run(request) }
// File understanding behind files.describe: OCR + dimensions for images/screenshots, text for
// PDFs, Foundation content for text files. Cached per file so the describe pass and any later
// operation reuse one understanding.
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
index 8f559898..b336aa5d 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
@@ -254,6 +254,40 @@ public struct HarnessImageGenerationResult: Sendable {
}
}
+/// The typed request for the `web.automate` hosted tool: a natural-language task,
+/// an optional starting URL, and an optional JSON-schema string for structured
+/// output. Declared in DonkeyHarness so the executor can pass it across the
+/// closure boundary without importing the DonkeyAI implementation.
+public struct HarnessWebAutomateRequest: Sendable {
+ public var task: String
+ public var startURL: String?
+ public var structuredOutputSchemaJSON: String?
+
+ public init(task: String, startURL: String? = nil, structuredOutputSchemaJSON: String? = nil) {
+ self.task = task
+ self.startURL = startURL
+ self.structuredOutputSchemaJSON = structuredOutputSchemaJSON
+ }
+}
+
+/// Outcome of the multimodal arm of `llm.generate` — a model call over a local audio/video file.
+/// Distinguishes the cases a caller can act on (re-chunk a truncated transcript, fix an unreadable,
+/// oversized, or non-media file) instead of collapsing every failure to a bare nil.
+public enum HarnessMediaGenerationOutcome: Sendable {
+ /// Non-empty generated text (e.g. an SRT transcript).
+ case text(String)
+ /// The output hit the model's token ceiling and was cut off — split the media into shorter chunks.
+ case truncated
+ /// The file could not be read.
+ case unreadableFile
+ /// The file is larger than can be sent inline — chunk it. Carries the byte size and the cap.
+ case tooLarge(bytes: Int, limit: Int)
+ /// The file's resolved type is not audio or video.
+ case unsupportedType(String)
+ /// The model returned no usable text (empty reply, timeout, or a content block).
+ case empty
+}
+
public struct HarnessBuiltInToolServices: Sendable {
public var memoryEntries: [HarnessMemoryEntry]
public var skillRegistry: HarnessSkillRegistry?
@@ -280,12 +314,23 @@ public struct HarnessBuiltInToolServices: Sendable {
/// failure). Backs the `llm.generate` tool, the model boundary the planner can reach for to
/// compose, transform, summarize, or massage text without leaving the harness.
public var textGenerator: (@Sendable (String) async -> String?)?
+ /// A one-off model call over a local media file (audio/video): a prompt and a file URL in, a typed
+ /// outcome out. Backs `llm.generate` when a `filePath` is supplied — the multimodal arm that
+ /// transcribes, translates, captions, or answers questions about media. The prompt decides the
+ /// output (e.g. an SRT transcript). The outcome distinguishes the failure modes a caller can act on
+ /// (re-chunk a truncated transcript, fix an unreadable or oversized file) rather than collapsing
+ /// them to nil. nil means the media arm is unwired and such calls fail cleanly.
+ public var mediaGenerator: (@Sendable (_ prompt: String, _ file: URL, _ mimeType: String?) async -> HarnessMediaGenerationOutcome)?
/// Web search: a query in, ranked results as text (title — url, then snippet, per result), or nil
/// on failure. Backs the `web.search` tool so the agent can find current facts.
public var webSearcher: (@Sendable (String) async -> String?)?
/// Web fetch/navigation: a URL in, the page's readable text out, or nil on failure. Backs the
/// `web.fetch` tool so the agent can read a page it found or was given.
public var webFetcher: (@Sendable (String) async -> String?)?
+ /// Agentic web automation: a task (navigate/click/fill/extract) in, the run's result as a text
+ /// block out (final output, status, any recording link), or nil on failure. Backs the
+ /// `web.automate` tool, which runs through the hosted Browser Use Cloud backend and bills credits.
+ public var webAutomator: (@Sendable (HarnessWebAutomateRequest) async -> String?)?
/// The file-understanding layer behind `files.describe`: a file URL in, a structured
/// `FileUnderstanding` out (OCR for images, text for PDFs, dimensions/metadata), or nil to fall
/// back to the built-in Foundation understanding. The runtime supplies this; without it the tool
@@ -310,8 +355,10 @@ public struct HarnessBuiltInToolServices: Sendable {
automationConsentGranted: (@Sendable (_ bundleIdentifier: String?) async -> Bool)? = nil,
commandExecutor: (@Sendable (HarnessToolExecutionContext) async -> HarnessToolResult?)? = nil,
textGenerator: (@Sendable (String) async -> String?)? = nil,
+ mediaGenerator: (@Sendable (_ prompt: String, _ file: URL, _ mimeType: String?) async -> HarnessMediaGenerationOutcome)? = nil,
webSearcher: (@Sendable (String) async -> String?)? = nil,
webFetcher: (@Sendable (String) async -> String?)? = nil,
+ webAutomator: (@Sendable (HarnessWebAutomateRequest) async -> String?)? = nil,
fileUnderstanding: (@Sendable (URL) async -> FileUnderstanding?)? = nil,
imageGenerator: (@Sendable (HarnessImageGenerationRequest) async -> HarnessImageGenerationResult?)? = nil
) {
@@ -328,8 +375,10 @@ public struct HarnessBuiltInToolServices: Sendable {
self.automationConsentGranted = automationConsentGranted
self.commandExecutor = commandExecutor
self.textGenerator = textGenerator
+ self.mediaGenerator = mediaGenerator
self.webSearcher = webSearcher
self.webFetcher = webFetcher
+ self.webAutomator = webAutomator
self.fileUnderstanding = fileUnderstanding
self.imageGenerator = imageGenerator
}
@@ -408,6 +457,8 @@ public enum BuiltInHarnessToolExecutors {
return await webSearch(context, services: services)
case "web.fetch":
return await webFetch(context, services: services)
+ case "web.automate":
+ return await webAutomate(context, services: services)
case "files.describe":
return await filesDescribe(context, services: services)
case "image.edit":
@@ -1624,21 +1675,53 @@ public enum BuiltInHarnessToolExecutors {
"app.lookup"
]
- /// Generic LLM call: compose/transform text via the model boundary. Long output can be written
- /// to a temp file (toFile=true) so the caller builds a note/document from the file instead of
- /// passing a huge string through a length-limited shell command.
+ /// Generic LLM call: compose/transform text via the model boundary, or — when a `filePath` is
+ /// given — transcribe/translate/analyze a local audio or video file through the media boundary.
+ /// Long output can be written to a temp file (toFile=true) so the caller builds a note, subtitle
+ /// file, or document from the file instead of passing a huge string through a length-limited shell
+ /// command.
private static func llmGenerate(
_ context: HarnessToolExecutionContext,
services: HarnessBuiltInToolServices
) async -> HarnessToolResult {
- guard let generator = services.textGenerator else {
- return failed(context, "No model boundary is wired for llm.generate.", reason: "textGeneratorUnavailable")
- }
guard let prompt = trimmed(context.call.input["prompt"]) else {
return invalidInput(context, "llm.generate requires a `prompt`.")
}
+
+ // Optional source text the prompt operates on — folded into the prompt for both the text and
+ // the media arm, so passing `input` alongside `filePath` (e.g. a glossary of names to spell) is
+ // not silently dropped.
let source = context.call.input["input"].map { "\n\nINPUT:\n\($0)" } ?? ""
- guard let text = await generator(prompt + source), !text.isEmpty else {
+ let generated: String?
+ if let filePath = trimmed(context.call.input["filePath"]) {
+ guard let mediaGenerator = services.mediaGenerator else {
+ return failed(context, "No media model boundary is wired for llm.generate with a filePath.", reason: "mediaGeneratorUnavailable")
+ }
+ let fileURL = URL(fileURLWithPath: filePath)
+ guard FileManager.default.fileExists(atPath: fileURL.path) else {
+ return invalidInput(context, "llm.generate `filePath` does not exist: \(filePath).")
+ }
+ switch await mediaGenerator(prompt + source, fileURL, trimmed(context.call.input["mimeType"])) {
+ case .text(let value):
+ generated = value
+ case .truncated:
+ return failed(context, "The transcript hit the model's output limit and was cut off — split the media into shorter chunks and transcribe each.", reason: "mediaOutputTruncated")
+ case .unreadableFile:
+ return failed(context, "Could not read the media file: \(filePath).", reason: "mediaFileUnreadable")
+ case .tooLarge(let bytes, let limit):
+ return failed(context, "The media file is \(bytes / 1_000_000)MB, over the \(limit / 1_000_000)MB inline limit — extract compact audio or split it into chunks.", reason: "mediaFileTooLarge")
+ case .unsupportedType(let mime):
+ return failed(context, "llm.generate `filePath` must be audio or video; got \(mime). Pass an explicit `mimeType` if the extension is unusual.", reason: "mediaUnsupportedType")
+ case .empty:
+ generated = nil
+ }
+ } else {
+ guard let generator = services.textGenerator else {
+ return failed(context, "No model boundary is wired for llm.generate.", reason: "textGeneratorUnavailable")
+ }
+ generated = await generator(prompt + source)
+ }
+ guard let text = generated, !text.isEmpty else {
return failed(context, "The model returned no text.", reason: "emptyGeneration")
}
@@ -1776,6 +1859,32 @@ public enum BuiltInHarnessToolExecutors {
)
}
+ private static func webAutomate(
+ _ context: HarnessToolExecutionContext,
+ services: HarnessBuiltInToolServices
+ ) async -> HarnessToolResult {
+ guard let automator = services.webAutomator else {
+ return failed(context, "Web automation is not configured.", reason: "webAutomateUnavailable")
+ }
+ guard let task = trimmed(context.call.input["task"]) else {
+ return invalidInput(context, "web.automate requires a `task` describing what to do.")
+ }
+ let request = HarnessWebAutomateRequest(
+ task: task,
+ startURL: trimmed(context.call.input["startUrl"]),
+ structuredOutputSchemaJSON: trimmed(context.call.input["schema"])
+ )
+ guard let result = await automator(request), !result.isEmpty else {
+ return failed(context, "The browser task did not complete.", reason: "webAutomateFailed")
+ }
+ return success(
+ context,
+ summary: result.count > 600 ? String(result.prefix(600)) + "…" : result,
+ facts: ["lastAcceptedTool": context.call.name],
+ metadata: ["text": result]
+ )
+ }
+
private static func timingWait(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {
let requested = context.call.input["seconds"].flatMap(Double.init) ?? 1
let seconds = min(max(requested, 0.1), 10)
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
index 6a34c0e2..d96ad79d 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
@@ -498,16 +498,19 @@ public enum BuiltInHarnessToolCatalog {
descriptor(
"llm.generate",
pluginID: "core.model",
- summary: "Run a one-off LLM call and return generated text. Use it to compose, transform, summarize, classify, rephrase, or massage text — e.g. produce a tracklist or a clean note body, or rewrite a raw status into a friendly one-line message. Set toFile=true for long output (a tracklist, lyrics, a long note body): the text is written to a temp file and the file path is returned, so it bypasses the shell command-length limit when you then build a note or document from it.",
+ summary: "Run a one-off LLM call and return generated text. Use it to compose, transform, summarize, classify, rephrase, or massage text — e.g. produce a tracklist or a clean note body, or rewrite a raw status into a friendly one-line message. Pass `filePath` to a local audio or video file to transcribe, translate, caption, or answer questions about it; the `prompt` decides the output (e.g. \"transcribe to SRT with timestamps\", \"transcribe and translate the text to Spanish, keep the timestamps\"). Set toFile=true for long output (a transcript, a tracklist, a long note body): the text is written to a temp file and the file path is returned, so it bypasses the shell command-length limit when you then build a subtitle file, note, or document from it.",
input: [
"prompt": "The instruction for the model (what to produce).",
"input": "Optional source text the prompt operates on.",
+ "filePath": "Optional path to a local audio/video file to transcribe, translate, or analyze. Hand over compact audio (extract it first) and chunk long media.",
+ "mimeType": "Optional MIME type for filePath (e.g. audio/mpeg, video/mp4); inferred from the file extension when omitted.",
"toFile": "\"true\" to write the result to a temp file and return its path instead of inline text."
],
output: [
"text": "The generated text (a short preview when written to a file).",
"filePath": "Path to the file holding the full output, when toFile=true."
],
+ optionalInputKeys: ["input", "filePath", "mimeType", "toFile"],
permissions: [],
safety: .sensitive,
verification: ["the returned text (or file) contains the requested content"],
@@ -600,6 +603,24 @@ public enum BuiltInHarnessToolCatalog {
verification: ["the fetched text matches the requested page"],
metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]
),
+ descriptor(
+ "web.automate",
+ pluginID: "core.web",
+ summary: "Run an agentic browser task in the cloud: navigate, click, fill forms, log in, and extract data across pages, then return the result. Use this only when reading (web.fetch) and local capture (web_snapshot) cannot do it — e.g. a multi-step flow, a site behind a login, or heavy bot-protection. This drives a real browser and SPENDS the user's credits, so confirm with the user before running anything that logs in, submits, or pays. Put the starting site in `task` or `startUrl`; pass a `schema` to get structured JSON back.",
+ input: [
+ "task": "Plain-language description of the whole browser task to accomplish.",
+ "startUrl": "Optional URL to start at (otherwise name the site in `task`).",
+ "schema": "Optional JSON Schema string; when set, the result is structured JSON conforming to it."
+ ],
+ output: [
+ "text": "The agent's final result — its output text or extracted data, with the run status and any recording link."
+ ],
+ optionalInputKeys: ["startUrl", "schema"],
+ permissions: [],
+ safety: .sensitive,
+ verification: ["the task's reported result satisfies the goal"],
+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]
+ ),
descriptor(
"state.verify",
pluginID: "core.verification",