Skip to content

Open source CapCut alternative.

TypeScript

refactor(ai): discover tools by doing; drop the capability probe and over-clarifying

David Leacaa1a5e8df6
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
index 9c792ad4..073a8bde 100644
--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift
@@ -663,7 +663,6 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
registry: registry
)
let plannerDescriptors = await registry.descriptors()
- let environmentSummary = await SystemToolCapabilityProbe.shared.summary()
// Every step, surface the other windows on screen (all apps/displays) to the planner so a
// request that lives in a window the user isn't looking at can be found and switched to. Donkey's
// own windows are filtered out by bundle id so the agent never targets its own overlay.
@@ -674,7 +673,6 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {
appName: appName,
appGuidance: appGuidance,
understanding: understanding,
- environmentSummary: environmentSummary,
skillCatalog: Self.installedSkillCatalog(),
trace: trace,
openWindows: {
diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
index 1a083f99..eb508dd8 100644
--- a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift
@@ -112,6 +112,10 @@ public enum DonkeyPrompts {
- needsClarification: set true ONLY when the request is genuinely ambiguous or missing detail
that you cannot reasonably resolve, or when it is destructive without a clear target. For an
under-specified but low-risk, reversible request, pick sensible specifics and set this false.
+ Do NOT ask for a detail the request already implies (the request named the language, the
+ source, or the file — use it), and do NOT ask the user to choose HOW to do the work or
+ whether some resource exists; deciding the method and finding things out yourself is your
+ job, not a question for the user.
- clarifyingQuestion: the single question to ask when needsClarification is true; otherwise empty.
- executionPreference: "background" or "foreground". Choose "foreground" ONLY when the point of
the request is for the user to watch or be shown the result on screen — e.g. "pull up…",
@@ -139,7 +143,6 @@ public enum DonkeyPrompts {
appName: String,
appGuidance: String?,
understanding: HarnessRequestUnderstanding?,
- environmentSummary: String?,
skillCatalog: String? = nil,
rollingContext: String? = nil,
retryNote: String? = nil,
@@ -165,10 +168,6 @@ public enum DonkeyPrompts {
+ "current work; do NOT restart from scratch or redo completed steps):\n"
+ String(followUpInstructions.prefix(800)) + "\n"
- let environmentBlock = (environmentSummary?.isEmpty == false)
- ? "\nENVIRONMENT (command-line tools on this Mac — only reach for what's installed):\n \(environmentSummary!)\n"
- : ""
-
let historyBlock = harnessStepHistoryBlock(task.toolHistory)
// Cross-turn conversation memory: recent conversation events plus a rolling summary of older
@@ -223,7 +222,7 @@ public enum DonkeyPrompts {
GOAL: \(goalText)
\(followUpBlock)\(understandingBlock)\(rollingContextBlock)
\(historyBlock)
- \(factsBlock)\(environmentBlock)\(guidanceBlock)\(skillCatalogBlock)\(windowsBlock)
+ \(factsBlock)\(guidanceBlock)\(skillCatalogBlock)\(windowsBlock)
\(elementsBlock)
AVAILABLE TOOLS:
@@ -235,6 +234,11 @@ public enum DonkeyPrompts {
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.
+ - Discover what's available by DOING, not by guessing or pre-checking. Run the command you
+ need by bare name; don't probe whether a tool exists first. If it fails with `command not
+ found`, adapt: reach for another tool that does the job, or — if the task genuinely needs
+ that one — report what's missing. Never install software or use a package manager (pip,
+ brew, npm, etc.); a missing tool is reported, not fetched.
- 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
@@ -275,7 +279,11 @@ public enum DonkeyPrompts {
- If the request is a question or chit-chat rather than an action, answer with
conversation.respond (set input.response), then run.complete.
- If a required detail is missing and you cannot safely proceed, use user.clarify
- (set input.question). Low-risk, reversible actions (play, open, search, draft, navigate)
+ (set input.question). Clarify only a genuinely missing, user-owned detail (which of two
+ accounts, which named file). Never ask the user to choose HOW to accomplish something, to
+ pick an intermediate format, or to confirm whether a resource exists — decide the method and
+ find out yourself. If the request already names the target, source, or language, use it
+ rather than asking again. Low-risk, reversible actions (play, open, search, draft, navigate)
need no confirmation — just do them. But before an action that is destructive, costly,
externally visible, or hard to undo (sending a message, posting, purchasing, deleting,
sharing private data) and goes beyond what the user explicitly asked for, confirm with
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
index 7c89e348..234e038c 100644
--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift
@@ -21,9 +21,6 @@ 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?
/// Compact catalog of every installed app skill (id, description, covered apps, validated scripts),
/// so the planner can route to an authoritative playbook even when no GUI app is the drive target —
/// e.g. playing music or saving a note by script. nil when no skills are installed.
@@ -79,7 +76,6 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
appName: String,
appGuidance: String?,
understanding: HarnessRequestUnderstanding? = nil,
- environmentSummary: String? = nil,
skillCatalog: String? = nil,
trace: (any HarnessTurnTracing)? = nil,
openWindows: @escaping @Sendable () -> [MacWindowTargetCandidate] = { [] },
@@ -91,7 +87,6 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
self.appName = appName
self.appGuidance = appGuidance
self.understanding = understanding
- self.environmentSummary = environmentSummary
self.skillCatalog = skillCatalog
self.trace = trace
self.openWindows = openWindows
@@ -383,7 +378,6 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {
appName: appName,
appGuidance: appGuidance,
understanding: understanding,
- environmentSummary: environmentSummary,
skillCatalog: skillCatalog,
rollingContext: rollingContext,
retryNote: retryNote,
diff --git a/apps/Donkey/Sources/DonkeyRuntime/SystemToolCapabilityProbe.swift b/apps/Donkey/Sources/DonkeyRuntime/SystemToolCapabilityProbe.swift
deleted file mode 100644
index d884dd4b..00000000
--- a/apps/Donkey/Sources/DonkeyRuntime/SystemToolCapabilityProbe.swift
+++ /dev/null
@@ -1,179 +0,0 @@
-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, and the
- /// tools Donkey bundles — ffmpeg, yt-dlp, qpdf, exiftool, lit — are always present,
- /// so the skills assert them directly rather than probing.)
- private static let probedTools = [
- "gh", "git", "jq", "python3", "node", "brew", "rg", "swift", "docker", "go", "cargo",
- "pandoc", "magick", "sqlite3", "pdftotext", "mlr"
- ]
-
- private let cacheURL: URL
- private let ttl: TimeInterval
- private let toolNames: [String]
- private var cached: (expires: Date, summary: String)?
- private var probeTask: Task<Void, Never>?
-
- 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.
- ///
- /// Never blocks on subprocesses: with no fresh cache it kicks the probe off
- /// in the background and returns an empty summary, so a user turn never
- /// waits on `which`/`--version` children. The next turn gets the cached line.
- 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
- }
- if probeTask == nil {
- let tools = toolNames
- probeTask = Task.detached(priority: .utility) { [weak self] in
- let summary = Self.probe(tools: tools)
- await self?.store(summary: summary)
- }
- }
- return ""
- }
-
- private func store(summary: String) {
- let entry = (expires: Date().addingTimeInterval(ttl), summary: summary)
- cached = entry
- saveToDisk(entry)
- probeTask = nil
- }
-
- // MARK: - Probing
-
- private static func probe(tools: [String]) -> String {
- var installed: [String] = []
- var missing: [String] = []
- for tool in tools {
- 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 static 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 subprocess and return trimmed stdout (nil on failure). The
- /// bound is real: a wedged child is killed at the deadline, and stderr is
- /// drained concurrently so a chatty tool can't fill the pipe and deadlock.
- private static func run(
- _ launchPath: String,
- _ arguments: [String],
- timeout: TimeInterval = 3
- ) -> String? {
- let process = Process()
- process.executableURL = URL(fileURLWithPath: launchPath)
- process.arguments = arguments
- let outPipe = Pipe()
- let errPipe = Pipe()
- process.standardOutput = outPipe
- process.standardError = errPipe
-
- let finished = DispatchSemaphore(value: 0)
- process.terminationHandler = { _ in finished.signal() }
- do {
- try process.run()
- } catch {
- return nil
- }
-
- DispatchQueue.global(qos: .utility).async {
- _ = errPipe.fileHandleForReading.readDataToEndOfFile()
- }
- if finished.wait(timeout: .now() + timeout) == .timedOut {
- process.terminate()
- if finished.wait(timeout: .now() + 1.0) == .timedOut {
- kill(process.processIdentifier, SIGKILL)
- finished.wait()
- }
- return nil
- }
-
- let data = outPipe.fileHandleForReading.readDataToEndOfFile()
- 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
- }
-}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift
index f529959e..db1313ae 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HarnessStepPromptTests.swift
@@ -22,7 +22,6 @@ struct HarnessStepPromptTests {
appName: "iTerm2",
appGuidance: nil,
understanding: nil,
- environmentSummary: nil,
skillCatalog: catalog
)
#expect(prompt.contains("authoritative playbooks for these apps/domains"))
@@ -39,7 +38,6 @@ struct HarnessStepPromptTests {
appName: "iTerm2",
appGuidance: nil,
understanding: nil,
- environmentSummary: nil,
skillCatalog: nil
)
#expect(!prompt.contains("authoritative playbooks for these apps/domains"))
@@ -65,7 +63,6 @@ struct HarnessStepPromptTests {
appName: "Notes",
appGuidance: nil,
understanding: nil,
- environmentSummary: nil,
openWindows: [window(app: "Safari", title: "GitHub", frontmost: true)]
)
#expect(prompt.contains("OPEN WINDOWS"))
@@ -83,7 +80,6 @@ struct HarnessStepPromptTests {
appName: "iTerm2",
appGuidance: nil,
understanding: nil,
- environmentSummary: nil,
openWindows: []
)
#expect(!prompt.contains("OPEN WINDOWS"))
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/SystemToolCapabilityProbeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/SystemToolCapabilityProbeTests.swift
deleted file mode 100644
index a949cb05..00000000
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/SystemToolCapabilityProbeTests.swift
+++ /dev/null
@@ -1,33 +0,0 @@
-import DonkeyRuntime
-import Foundation
-import Testing
-
-@Suite
-struct SystemToolCapabilityProbeTests {
- @Test
- func summaryNeverBlocksOnFirstUseAndServesTheBackgroundResultAfter() async throws {
- let cacheURL = FileManager.default.temporaryDirectory
- .appendingPathComponent("probe-tests-\(UUID().uuidString)", isDirectory: true)
- .appendingPathComponent("tool-capabilities.json")
- defer { try? FileManager.default.removeItem(at: cacheURL.deletingLastPathComponent()) }
-
- // zsh ships with macOS, so the probe has one deterministic hit.
- let probe = SystemToolCapabilityProbe(cacheURL: cacheURL, toolNames: ["zsh"])
-
- // First call must not wait on subprocesses — it kicks the probe off and
- // returns an empty environment line.
- #expect(await probe.summary() == "")
-
- // The background probe lands shortly and subsequent calls serve it.
- var summary = ""
- for _ in 0..<100 where summary.isEmpty {
- try await Task.sleep(nanoseconds: 100_000_000)
- summary = await probe.summary()
- }
- #expect(summary.contains("zsh"))
-
- // The result is persisted: a fresh instance reads it without re-probing.
- let second = SystemToolCapabilityProbe(cacheURL: cacheURL, toolNames: ["zsh"])
- #expect(await second.summary() == summary)
- }
-}