Open source CapCut alternative.
TypeScript
feat(app): generic llm.generate tool for composing and transforming text
David Lef17ed91a27e8
diff --git a/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift b/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swiftindex 12bd7901..dccbd037 100644--- a/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift+++ b/apps/Donkey/Sources/Donkey/GeminiLiveVoiceController.swift@@ -75,20 +75,35 @@ final class GeminiLiveVoiceController {self.configuration = configurationself.systemInstruction = systemInstructionself.visionAuthProvider = visionAuthProvider- let services = HarnessBuiltInToolServices(commandExecutor: DonkeyCommandBackends.makeExecutor())+ // Wire the generic LLM tool into the fast path too, so the Live model can compose/transform+ // text mid-task (a tracklist, a clean note body) through the hosted route.+ var services = HarnessBuiltInToolServices(commandExecutor: DonkeyCommandBackends.makeExecutor())+ if let backendConfiguration = try? DonkeyBackendInferenceConfiguration.fromEnvironment() {+ let textGenerator = HostedTextGenerator(+ backend: DonkeyBackendInferenceClient(configuration: backendConfiguration)+ )+ services.textGenerator = { await textGenerator.generate($0) }+ }+ let llmDescriptors = BuiltInHarnessToolCatalog.descriptors.filter { $0.name == "llm.generate" }+ let liveDescriptors = DonkeyCommandLayer.descriptors + llmDescriptors+ self.liveToolDescriptors = liveDescriptorsself.registry = HarnessToolRegistry(tools: BuiltInHarnessToolExecutors.tools(- descriptors: DonkeyCommandLayer.descriptors,+ descriptors: liveDescriptors,services: services))}+ /// The harness-registered tools the Live session exposes (command layer + the generic LLM tool).+ /// Vision/agent escalation descriptors are added on top when the session starts.+ private let liveToolDescriptors: [HarnessToolDescriptor]+func start() async {guard configuration.enabled, session == nil else { return }let session = GeminiLiveSession(systemInstruction: systemInstruction,- functionDescriptors: DonkeyCommandLayer.descriptors + [Self.visionControlDescriptor, Self.agentRunDescriptor],+ functionDescriptors: liveToolDescriptors + [Self.visionControlDescriptor, Self.agentRunDescriptor],connectionProvider: Self.makeConnectionProvider())self.session = sessiondiff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swiftindex 9358c875..4ccbb7ee 100644--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift@@ -345,6 +345,12 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {harnessServices.appleScriptGenerator = { request inawait appleScriptGenerationAdapter.generateAppleScript(request)}+ // Generic LLM tool: lets the planner compose/transform text mid-task (build a tracklist,+ // a clean note body, a friendly status line) through the same hosted route.+ let textGenerator = HostedTextGenerator(backend: backend)+ harnessServices.textGenerator = { prompt in+ await textGenerator.generate(prompt)+ }let granted = Self.userQueryGrantedPermissionslet replacedBuiltIns: Set<String> = ["screen.observe", "elements.get", "element.perform", "text.enter", "keyboard.press"]let builtInDescriptors = BuiltInHarnessToolCatalog.descriptors.filter { descriptor indiff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swiftindex 7e6adad9..5e489787 100644--- a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift@@ -64,7 +64,12 @@ public enum DonkeyPrompts {steps. If the skill says the app needs vision, or scripting it fails, call \vision_control with the app and goal; a vision agent will operate the screen. For \multi-step work the fast tools can't finish, call agent_run with the goal; the \- desktop agent reports to the user itself. Discover before guessing rather than \+ desktop agent reports to the user itself. To compose or transform text — build a \+ list or tracklist, write a summary, clean up a body, produce long content for a \+ note — use the llm.generate tool; for anything long, set its toFile=true and build \+ the note/document from the returned file so the content never has to fit in one \+ shell command. Don't refuse a big task as \"too long\" — generate to a file and \+ assemble it. Discover before guessing rather than \inventing names or values. Run a real feedback loop on EVERY task, whatever skill \it uses: read each tool's output, and when an approach fails or you can't confirm \it worked, ADJUST and try another — broaden the query, switch to AppleScript, or if \diff --git a/apps/Donkey/Sources/DonkeyAI/HostedTextGenerator.swift b/apps/Donkey/Sources/DonkeyAI/HostedTextGenerator.swiftnew file mode 100644index 00000000..ea80759f--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/HostedTextGenerator.swift@@ -0,0 +1,55 @@+import DonkeyContracts+import DonkeyHarness+import Foundation++/// The model boundary behind the generic `llm.generate` harness tool: one prompt in, generated text+/// out. It composes, transforms, summarizes, or massages text through the same hosted inference route+/// the rest of the harness uses, so a planner can reach for the model mid-task (build a tracklist,+/// clean up a note body, rewrite a raw status into a friendly line) without any provider details+/// leaking past this adapter.+public struct HostedTextGenerator: Sendable {+ private let backend: DonkeyBackendInferenceClient+ private let maxOutputTokens: Int+ private let timeoutSeconds: TimeInterval++ public init(+ backend: DonkeyBackendInferenceClient,+ maxOutputTokens: Int = 4_000,+ timeoutSeconds: TimeInterval = 45+ ) {+ self.backend = backend+ self.maxOutputTokens = maxOutputTokens+ self.timeoutSeconds = timeoutSeconds+ }++ /// Returns the model's text for `prompt`, or nil on any failure (the tool turns nil into a typed+ /// failure the harness already handles).+ public func generate(_ prompt: String) async -> String? {+ let request = RemoteInferenceResponseCreateRequest(+ input: .array([+ .object([+ "role": .string("user"),+ "content": .array([+ .object(["type": .string("input_text"), "text": .string(prompt)])+ ])+ ])+ ]),+ store: false,+ metadata: ["source": "hosted-text-generator", "prompt_version": "llm-generate-v1"],+ parameters: [+ "temperature": .number(0.4),+ "max_output_tokens": .number(Double(maxOutputTokens)),+ "thinking_budget": .number(0)+ ]+ )+ let backend = self.backend+ guard let response = try? await AIDeadline.enforce(seconds: timeoutSeconds, {+ try await backend.createResponse(request)+ }) else {+ return nil+ }+ let text = RemoteInferenceResponseHelpers.outputText(from: response)?+ .trimmingCharacters(in: .whitespacesAndNewlines)+ return (text?.isEmpty == false) ? text : nil+ }+}diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swiftindex b155d8ca..ff7286aa 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift@@ -191,6 +191,10 @@ public struct HarnessBuiltInToolServices: Sendable {/// Native Donkey Command Layer backend. Returns a result for a recognized/// command, or `nil` to let dispatch fall through to `unknownTool`.public var commandExecutor: (@Sendable (HarnessToolExecutionContext) async -> HarnessToolResult?)?+ /// A one-off model completion: given a fully-formed prompt, return generated text (or nil on+ /// 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?)?public init(memoryEntries: [HarnessMemoryEntry] = [],@@ -201,7 +205,8 @@ public struct HarnessBuiltInToolServices: Sendable {appleScriptGenerator: (@Sendable (HarnessScriptGenerationRequest) async -> HarnessScriptGenerationOutcome)? = nil,appleScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)? = nil,skillScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)? = nil,- commandExecutor: (@Sendable (HarnessToolExecutionContext) async -> HarnessToolResult?)? = nil+ commandExecutor: (@Sendable (HarnessToolExecutionContext) async -> HarnessToolResult?)? = nil,+ textGenerator: (@Sendable (String) async -> String?)? = nil) {self.memoryEntries = memoryEntriesself.skillRegistry = skillRegistry@@ -212,6 +217,7 @@ public struct HarnessBuiltInToolServices: Sendable {self.appleScriptExecutor = appleScriptExecutorself.skillScriptExecutor = skillScriptExecutorself.commandExecutor = commandExecutor+ self.textGenerator = textGenerator}}@@ -282,6 +288,8 @@ public enum BuiltInHarnessToolExecutors {return await applicationLearningSaveSkillPack(context, services: services)case "state.verify":return stateVerify(context)+ case "llm.generate":+ return await llmGenerate(context, services: services)case "wait":return await timingWait(context)case "run.pause", "run.resume", "run.recover", "run.cancel", "run.complete", "run.failSafe":@@ -1237,6 +1245,49 @@ 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.+ 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`.")+ }+ let source = context.call.input["input"].map { "\n\nINPUT:\n\($0)" } ?? ""+ guard let text = await generator(prompt + source), !text.isEmpty else {+ return failed(context, "The model returned no text.", reason: "emptyGeneration")+ }++ let toFile = (context.call.input["toFile"] ?? "").lowercased() == "true"+ if toFile {+ let url = FileManager.default.temporaryDirectory+ .appendingPathComponent("donkey-llm-\(context.call.id).txt")+ do {+ try text.write(to: url, atomically: true, encoding: .utf8)+ } catch {+ return failed(context, "Could not write generated text to a file: \(error)", reason: "fileWriteFailed")+ }+ let preview = String(text.prefix(200))+ return success(+ context,+ summary: "Generated \(text.count) characters → \(url.path)",+ facts: ["lastAcceptedTool": context.call.name],+ metadata: ["filePath": url.path, "text": preview, "characterCount": String(text.count)]+ )+ }+ return success(+ context,+ summary: text.count > 400 ? String(text.prefix(400)) + "…" : text,+ facts: ["lastAcceptedTool": context.call.name],+ metadata: ["text": text, "characterCount": String(text.count)]+ )+ }+private static func timingWait(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {let requested = context.call.input["seconds"].flatMap(Double.init) ?? 1let seconds = min(max(requested, 0.1), 10)diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swiftindex d6f44e7c..97f2df14 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift@@ -485,6 +485,24 @@ public enum BuiltInHarnessToolCatalog {requiredContext: ["distilled application profile", "validated generated scripts when included"],verification: ["skill pack includes SKILL.md, app-profile.json, workflows.json, evidence index, and only validated scripts"]),+ 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.",+ input: [+ "prompt": "The instruction for the model (what to produce).",+ "input": "Optional source text the prompt operates on.",+ "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."+ ],+ permissions: [],+ safety: .sensitive,+ verification: ["the returned text (or file) contains the requested content"],+ metadata: [HarnessToolDescriptor.resultIsEvidenceMetadataKey: "true"]+ ),descriptor("state.verify",pluginID: "core.verification",diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/notes/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/notes/SKILL.mdindex 3e22266f..089a9091 100644--- a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/notes/SKILL.md+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/notes/SKILL.md@@ -15,6 +15,13 @@ Notes is fully scriptable; almost every "save … to Notes" step is one `osascri- Always give a concrete `name` — it is the note's title. Compose the full finished body yourself; never save placeholder text.- Escape any double quotes inside the text for the AppleScript string literal.+## Long content (a tracklist, a list, lyrics, anything big)+- A note body that won't fit in one short command — "all the songs from an album", "each song with its lyrics", a long summary — must NOT be jammed into one `osascript` string; shell commands are length-limited and the escaping breaks.+- Instead, generate the content with the `llm.generate` tool and set `toFile=true`. It returns a `filePath` holding the full text. For knowledge content (an album's tracklist, lyrics), the prompt is e.g. `List every song on Taylor Swift's latest album, one per line` or `For each of these songs, write the title then its lyrics`.+- Then create the note FROM that file (the command stays short, so no length limit), turning newlines into `<br>` so Notes renders the lines:+ `osascript -e 'set f to (read POSIX file "/tmp/donkey-llm-XXX.txt" as «class utf8»)' -e 'set AppleScript'"'"'s text item delimiters to (ASCII character 10)' -e 'set parts to text items of f' -e 'set AppleScript'"'"'s text item delimiters to "<br>"' -e 'tell application "Notes" to make new note with properties {name:"Title", body:(parts as text)}'`+- This is the general pattern for any "note with a lot in it": llm.generate(toFile) → read the file into the body. Build it up rather than giving up because "the list is too long".+## Putting computed values (date, battery, system state) in a note- Do this in two plain steps, not one fragile command. First READ each value with its own simple command (`date '+%Y-%m-%d'`, `pmset -g batt | grep -o '[0-9]*%' | head -1`, `df -h /`), look at the output, then create the note with those literal values pasted into the body.- Do NOT nest command substitutions (`$( … )`) inside the osascript string — the parentheses and quoting are error-prone and the parens also trip the safety classifier. Read first, then write the finished literal body.diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swiftindex 9ccce08f..e32eb67f 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift@@ -211,6 +211,52 @@ struct GenericHarnessTests {#expect(finalTask?.status == .completed)}+ @Test+ func llmGenerateReturnsInlineTextFromTheModelBoundary() async {+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(+ services: HarnessBuiltInToolServices(+ textGenerator: { prompt in "RESULT for: \(prompt)" }+ )+ )+ let result = await registry.execute(+ HarnessToolCall(name: "llm.generate", input: ["prompt": "list 3 songs", "input": "Album X"]),+ taskID: "t", worldModel: HarnessWorldModel(), grantedPermissions: []+ )+ #expect(result.status == .succeeded)+ #expect(result.metadata["text"]?.contains("RESULT for: list 3 songs") == true)+ // The input is folded into the prompt the generator sees.+ #expect(result.metadata["text"]?.contains("Album X") == true)+ }++ @Test+ func llmGenerateWritesLongOutputToAFileToBypassCommandLimits() async throws {+ let long = String(repeating: "Song line\n", count: 500)+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(+ services: HarnessBuiltInToolServices(textGenerator: { _ in long })+ )+ let result = await registry.execute(+ HarnessToolCall(name: "llm.generate", input: ["prompt": "tracklist", "toFile": "true"]),+ taskID: "t", worldModel: HarnessWorldModel(), grantedPermissions: []+ )+ #expect(result.status == .succeeded)+ let path = try #require(result.metadata["filePath"])+ let written = try String(contentsOfFile: path, encoding: .utf8)+ #expect(written == long)+ #expect(result.metadata["characterCount"] == String(long.count))+ try? FileManager.default.removeItem(atPath: path)+ }++ @Test+ func llmGenerateFailsCleanlyWithoutAModelBoundary() async {+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()+ let result = await registry.execute(+ HarnessToolCall(name: "llm.generate", input: ["prompt": "hi"]),+ taskID: "t", worldModel: HarnessWorldModel(), grantedPermissions: []+ )+ #expect(result.status == .failed)+ #expect(result.metadata["reason"] == "textGeneratorUnavailable")+ }+@Testfunc runStopsWhenThePlannerLoopsOnTheSameCall() async {// A planner that keeps choosing the identical observation never converges. The runtime must