Open source CapCut alternative.
TypeScript
feat(app): make the planner a system-tools-first power user
David Le806c26946290
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swiftindex 9ead6582..6e2fb806 100644--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift@@ -11,8 +11,10 @@ import Foundationpublic struct HarnessRequestUnderstanding: Sendable, Equatable {/// The user's request restated as one concrete imperative goal.public var restatedGoal: String- /// The macOS app the request is about, or nil/empty when it is pure conversation or clearly about- /// whatever app is already frontmost.+ /// The macOS app the request needs to operate through its GUI. Left nil/empty for pure+ /// conversation, for whatever app is already frontmost, and for tasks an expert would do with+ /// system tools (finding files, launching/quitting apps, reading or changing settings/state) —+ /// those have no GUI target and the planner drives them with shell_exec.public var targetAppName: String?/// Structured parameters extracted from the request (e.g. title, recipient, query).public var parameters: [String: String]@@ -188,9 +190,11 @@ public final class HostedHarnessRequestUnderstanding {Fill the fields:- restatedGoal: one concrete imperative sentence capturing exactly what to accomplish.- - targetAppName: the macOS app the request is about. If the request names or clearly implies an- app, use that app's name. If it is clearly about the current app, use "\(frontmostAppName)".- Leave empty only for pure conversation with no desktop action.+ - targetAppName: the macOS app that must be driven through its GUI to do this. Set it only when+ the task genuinely needs a specific app's interface (e.g. composing in Mail, editing in a+ design app). LEAVE IT EMPTY when an expert would use system tools instead — finding files,+ opening or quitting apps, reading or changing settings or state — and for pure conversation.+ If it clearly concerns the current app's UI, use "\(frontmostAppName)".- parameters: the concrete details needed to do it (e.g. title, recipient, query, value), asstring key/values. Omit what is not specified.- successCriteria: what would be visible on screen once the goal is done.diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swiftindex 4dc0e75e..0af457ad 100644--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift@@ -21,6 +21,9 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {/// clarify gate. nil when the upfront understanding call was skipped or failed, in which case the/// planner falls back to the raw task goal.private let understanding: HarnessRequestUnderstanding?+ /// One-line summary of which command-line tools are installed on this Mac (and versions), so the+ /// planner only reaches for tools that exist. Empty when the probe was skipped or found nothing.+ private let environmentSummary: String?private let uptimeMS: @Sendable () -> Double/// Uptime (ms) at which the planner first chose an *action* tool (something that changes app@@ -43,6 +46,7 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {appName: String,appGuidance: String?,understanding: HarnessRequestUnderstanding? = nil,+ environmentSummary: String? = nil,uptimeMS: @escaping @Sendable () -> Double = { ProcessInfo.processInfo.systemUptime * 1_000 }) {self.backend = backend@@ -50,6 +54,7 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {self.appName = appNameself.appGuidance = appGuidanceself.understanding = understanding+ self.environmentSummary = environmentSummaryself.uptimeMS = uptimeMSself.readOnlyToolNames = Set(descriptors.filter { $0.safetyClass == .readOnly }.map(\.name))}@@ -239,6 +244,10 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {: "\nKnown state:\n" + task.worldModel.facts.sorted { $0.key < $1.key }.map { " \($0.key) = \($0.value)" }.joined(separator: "\n") + "\n"+ let environmentBlock = (environmentSummary?.isEmpty == false)+ ? "\nENVIRONMENT (command-line tools on this Mac — only reach for what's installed):\n \(environmentSummary!)\n"+ : ""+let history = task.toolHistory.suffix(12).map { " \($0.call.name): \($0.summary)" }let historyBlock = history.isEmpty? "Nothing has been done yet."@@ -270,32 +279,36 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {let understandingBlock = self.understandingBlock()return """- You operate the macOS app "\(appName)" by choosing ONE tool to run next, then you will see the- result and choose again. Work toward the goal in small, verifiable steps. If the goal targets a- different app than the one in front, focus it first with app.openOrFocus.+ You are an expert macOS power user. Choose ONE tool to run next, then you will see the result+ and choose again. Work toward the goal in small, verifiable steps. Many tasks are solved+ entirely with system tools and have no on-screen UI target; reach for the GUI only when the task+ truly needs it.GOAL: \(goalText)\(understandingBlock)\(historyBlock)- \(factsBlock)\(guidanceBlock)+ \(factsBlock)\(environmentBlock)\(guidanceBlock)\(elementsBlock)AVAILABLE TOOLS:\(toolsBlock)Guidance:- - SEE before you act. Prefer ax.observe (fast, structured) for native apps; use vision.capture- when Accessibility is missing or insufficient (e.g. canvas/Electron content).- - To act on a specific element, pass its id from the list above in "input".- - Before an irreversible or destructive action (sending, deleting, purchasing, posting, moving- to trash, or overwriting), first ask the user to confirm with user.clarify (set- input.question), and only perform it after they approve.- - If the request is a question or chit-chat rather than a desktop action, answer with+ - Solve it the way an expert terminal user would. Prefer shell_exec with system tools to find+ files (mdfind, ls -t, find), launch or quit apps (open -a, osascript), read state (date,+ pmset -g batt, system_profiler, defaults read), and change settings (defaults write,+ networksetup). Read-only commands run instantly; state-changing ones ask the user for+ one-time or always-allow consent, so propose them freely rather than avoiding them.+ - Only operate the GUI when the task genuinely needs it (canvas/Electron/proprietary UI, or no+ system-tool equivalent). When you do: SEE before you act — prefer ax.observe (fast,+ structured) for native apps; use vision.capture when Accessibility is missing or insufficient+ — then act on a specific element by passing its id from the list above in "input".+ - If the request is a question or chit-chat rather than an action, answer withconversation.respond (set input.response), then run.complete.- If a required detail is missing and you cannot safely proceed, use user.clarify(set input.question).- - Verification must be evidence-backed: after acting, re-observe (ax.observe/vision.capture) or- state.verify and confirm the effect BEFORE choosing run.complete. A focused app is not- evidence; only complete once the goal is confirmed by what you can see.+ - Verification must be evidence-backed: after acting, confirm the effect (a shell command's+ output/exit code, a re-observe, or state.verify) BEFORE choosing run.complete. A focused app+ is not evidence; only complete once the goal is confirmed by what you can see.Return JSON: {"tool": "<one tool name>", "input": {"key": "value", ...}, "reason": "<one sentence>"}."""}diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/system-tools/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/system-tools/SKILL.mdnew file mode 100644index 00000000..79c5776c--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/system-tools/SKILL.md@@ -0,0 +1,37 @@+# System Tools++id: system-tools+description: Operate macOS like an expert power user through shell_exec — find files, launch and quit apps, read state, and change settings with native command-line tools instead of screenshots.+tags: shell, system, files, settings, power-user, terminal, local-app+keywords: find, file, open, launch, quit, settings, defaults, battery, wifi, clipboard, finder, spotlight, version, dark mode, volume, network+tools: shell_exec, apps_list++Use `shell_exec` as the first choice for anything an expert terminal user would do without touching the GUI. Read-only commands run immediately; state-changing ones ask the user for one-time or always-allow consent, so propose them directly rather than falling back to clicking. Keep each command to a single line.++## Find and inspect files+- Spotlight search by name or content: `mdfind -name report.pdf`, `mdfind "kMDItemTextContent == '*invoice*'"`.+- Newest / largest in a folder: `ls -t ~/Downloads/*.pdf | head -1`, `ls -S ~/Downloads | head`.+- Walk a tree: `find ~/Documents -name '*.key' -mtime -7`.+- Read metadata or contents: `mdls file.pdf`, `stat -f '%Sm %N' file`, `cat file`, `head -50 file`.++## Open, launch, and quit+- Open a file in its default app: `open ~/Downloads/report.pdf`.+- Launch or focus an app: `open -a "Spotify"`; reveal in Finder: `open -R ~/file`; open a URL: `open https://example.com`.+- Quit an app cleanly: `osascript -e 'quit app "Safari"'`; force a hung app: `killall Safari`.+- List installed/running apps to target exact names: prefer the `apps_list` tool.++## Read system and app state+- Battery / power: `pmset -g batt`. Hardware/software: `system_profiler SPHardwareDataType`, `sw_vers`.+- Disk: `df -h`. Network: `networksetup -getairportpower en0`, `networksetup -getinfo Wi-Fi`.+- A preference's current value: `defaults read com.apple.dock autohide`.+- Tool availability/version (to decide what's possible): `which gh`, `python3 --version`.++## Change settings (asks for consent first)+- App/UI preferences: `defaults write com.apple.dock autohide -bool true` then `killall Dock` to apply.+- Dark mode: `osascript -e 'tell app "System Events" to tell appearance preferences to set dark mode to true'`.+- Wi-Fi power: `networksetup -setairportpower en0 off`.+- Clipboard: `pbcopy < file.txt`, `pbpaste`. Image convert/resize: `sips -Z 800 image.png`.++## Boundaries+- Security- and privacy-sensitive changes (TCC/privacy, FileVault, login window, passwords, keychain) and destructive or privileged commands (`sudo`, `rm`, `dd`, piping into a shell) ask every time and are never remembered.+- Use the GUI (ax.observe / vision.capture and clicks) only when there is no system-tool equivalent — canvas, Electron, or proprietary interfaces.diff --git a/apps/Donkey/Sources/DonkeyRuntime/SystemToolCapabilityProbe.swift b/apps/Donkey/Sources/DonkeyRuntime/SystemToolCapabilityProbe.swiftnew file mode 100644index 00000000..475dc207--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/SystemToolCapabilityProbe.swift@@ -0,0 +1,139 @@+import Foundation++/// Probes which command-line tools are installed on *this* Mac (and their+/// versions), so the planner reaches only for tools that actually exist and can+/// adapt to version differences instead of guessing.+///+/// The probe is read-only (`which` + a version flag), runs at most once per TTL,+/// and caches its summary to disk next to the other harness state. The summary+/// is a compact line injected into the planner's ENVIRONMENT block.+public actor SystemToolCapabilityProbe {+ public static let shared = SystemToolCapabilityProbe()++ /// Curated tools an expert might reach for that are NOT guaranteed present.+ /// (Ubiquitous system tools like `mdfind`/`defaults`/`open` are assumed.)+ private static let probedTools = [+ "gh", "git", "jq", "python3", "node", "brew", "rg", "swift", "ffmpeg", "docker", "go", "cargo"+ ]++ private let cacheURL: URL+ private let ttl: TimeInterval+ private let toolNames: [String]+ private var cached: (expires: Date, summary: String)?++ public init(+ cacheURL: URL? = nil,+ ttl: TimeInterval = 24 * 60 * 60,+ toolNames: [String]? = nil+ ) {+ self.cacheURL = cacheURL ?? Self.defaultCacheURL()+ self.ttl = ttl+ self.toolNames = toolNames ?? Self.probedTools+ }++ private static func defaultCacheURL() -> URL {+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]+ .appendingPathComponent("Donkey", isDirectory: true)+ .appendingPathComponent("HarnessStore", isDirectory: true)+ .appendingPathComponent("tool-capabilities.json")+ }++ /// A one-line summary of installed vs missing tools, e.g.+ /// `Installed: git 2.43, jq 1.7, python3 3.12.2. Not installed: node, ffmpeg.`+ /// Cached in memory and on disk; recomputed only after the TTL lapses.+ public func summary(now: Date = Date()) async -> String {+ if let cached, cached.expires > now { return cached.summary }+ if let disk = loadFromDisk(), disk.expires > now {+ cached = disk+ return disk.summary+ }+ let summary = probe()+ let entry = (expires: now.addingTimeInterval(ttl), summary: summary)+ cached = entry+ saveToDisk(entry)+ return summary+ }++ // MARK: - Probing++ private func probe() -> String {+ var installed: [String] = []+ var missing: [String] = []+ for tool in toolNames {+ guard let path = run("/usr/bin/which", [tool]), !path.isEmpty else {+ missing.append(tool)+ continue+ }+ if let version = version(of: tool) {+ installed.append("\(tool) \(version)")+ } else {+ installed.append(tool)+ }+ }+ var parts: [String] = []+ if !installed.isEmpty { parts.append("Installed: \(installed.joined(separator: ", ")).") }+ if !missing.isEmpty { parts.append("Not installed: \(missing.joined(separator: ", ")).") }+ return parts.joined(separator: " ")+ }++ /// Best-effort version string from the tool's own version flag.+ private func version(of tool: String) -> String? {+ guard let raw = run("/usr/bin/env", [tool, "--version"]) ?? run("/usr/bin/env", [tool, "version"]) else {+ return nil+ }+ let firstLine = raw.split(separator: "\n").first.map(String.init) ?? raw+ // Pull the first dotted numeric token (e.g. "git version 2.43.0" -> "2.43.0").+ for token in firstLine.split(whereSeparator: { $0 == " " || $0 == "," }) {+ let candidate = token.trimmingCharacters(in: CharacterSet(charactersIn: "v()"))+ if candidate.contains("."), candidate.first?.isNumber == true {+ return candidate+ }+ }+ return nil+ }++ /// Run a short, bounded subprocess and return trimmed stdout (nil on failure).+ private func run(_ launchPath: String, _ arguments: [String]) -> String? {+ let process = Process()+ process.executableURL = URL(fileURLWithPath: launchPath)+ process.arguments = arguments+ let outPipe = Pipe()+ process.standardOutput = outPipe+ process.standardError = Pipe()+ do {+ try process.run()+ } catch {+ return nil+ }+ let data = outPipe.fileHandleForReading.readDataToEndOfFile()+ process.waitUntilExit()+ guard process.terminationStatus == 0 else { return nil }+ let text = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""+ return text.isEmpty ? nil : text+ }++ // MARK: - Persistence++ private func loadFromDisk() -> (expires: Date, summary: String)? {+ guard let data = try? Data(contentsOf: cacheURL),+ let decoded = try? JSONDecoder().decode(PersistedProbe.self, from: data) else {+ return nil+ }+ return (decoded.expires, decoded.summary)+ }++ private func saveToDisk(_ entry: (expires: Date, summary: String)) {+ let payload = PersistedProbe(expires: entry.expires, summary: entry.summary)+ guard let data = try? JSONEncoder().encode(payload) else { return }+ try? FileManager.default.createDirectory(+ at: cacheURL.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )+ try? data.write(to: cacheURL, options: .atomic)+ }++ private struct PersistedProbe: Codable {+ var expires: Date+ var summary: String+ }+}