Skip to content

Open source CapCut alternative.

TypeScript

Add native Donkey command layer

David Le634e26b2d46e
diff --git a/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift b/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift
new file mode 100644
index 00000000..180d5fa8
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyHarness/DonkeyCommandLayer.swift
@@ -0,0 +1,65 @@
+import Foundation
+
+/// The Donkey Command Layer: fast, deterministic, native commands the model can
+/// call directly without screenshots or Accessibility. Descriptors live here in
+/// the (Foundation-only) harness module; the native side effects are injected as
+/// a `commandExecutor` closure on `HarnessBuiltInToolServices`, with the concrete
+/// implementation in `DonkeyRuntime`.
+public enum DonkeyCommandLayer {
+ public static let pluginID = "donkey.command"
+
+ /// Single source of truth for the command names shared between the descriptors
+ /// here and the runtime backend that executes them.
+ public enum Command: String, CaseIterable, Sendable {
+ case shellExec = "shell_exec"
+ case appsList = "apps.list"
+ case musicPlay = "music.play"
+ }
+
+ public static var descriptors: [HarnessToolDescriptor] {
+ [
+ // Primary, general-purpose tool — listed first so the model reaches
+ // for it by default.
+ HarnessToolDescriptor(
+ name: Command.shellExec.rawValue,
+ pluginID: pluginID,
+ summary: "Run a safe, single-line shell command on the user's Mac and return its output. General-purpose: open/activate or quit apps (e.g. `open -a Spotify`), drive apps and the system — including via `osascript -e '…'` — and read state (e.g. `date`, `pmset -g batt`). Avoid destructive, privileged (`sudo`), raw-disk, network-download, or pipe-to-shell commands.",
+ inputSchema: ["command": "A safe, single-line shell command, e.g. `open -a Notes`, `osascript -e 'tell application \"Spotify\" to play'`, or `date`."],
+ outputSchema: [
+ "stdout": "Captured standard output (trimmed).",
+ "exitCode": "Process exit code."
+ ],
+ requiredPermissions: [.appControl, .input],
+ safetyClass: .guardedInput,
+ verificationHints: ["the command exits with code 0"]
+ ),
+ HarnessToolDescriptor(
+ name: Command.appsList.rawValue,
+ pluginID: pluginID,
+ summary: "List installed and currently-running applications (display names + bundle ids). Call this to discover exact app names before opening, quitting, or scripting an app instead of guessing.",
+ inputSchema: ["filter": "Case-insensitive substring to narrow the results."],
+ optionalInputKeys: ["filter"],
+ outputSchema: [
+ "installed": "Comma-separated installed app names.",
+ "running": "Comma-separated running app names."
+ ],
+ requiredPermissions: [.appLookup],
+ safetyClass: .readOnly
+ ),
+ HarnessToolDescriptor(
+ name: Command.musicPlay.rawValue,
+ pluginID: pluginID,
+ summary: "Search for and play media in a music app (Spotify or Apple Music) without screenshots.",
+ inputSchema: [
+ "query": "Track, artist, album, or playlist to search and play.",
+ "app": "Music app: Spotify or Music. Defaults to the user's available music app."
+ ],
+ optionalInputKeys: ["app"],
+ outputSchema: ["status": "Playback status reported by the music app."],
+ requiredPermissions: [.appControl, .input],
+ safetyClass: .guardedInput,
+ verificationHints: ["the music app reports that playback started"]
+ )
+ ]
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
index c706224c..446755d2 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessBuiltInToolExecutors.swift
@@ -214,6 +214,9 @@ public struct HarnessBuiltInToolServices: Sendable {
public var appleScriptGenerator: (@Sendable (HarnessScriptGenerationRequest) async -> HarnessScriptGenerationOutcome)?
public var appleScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)?
public var skillScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)?
+ /// 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?)?
public init(
memoryEntries: [HarnessMemoryEntry] = [],
@@ -224,7 +227,8 @@ public struct HarnessBuiltInToolServices: Sendable {
applicationSkillPackWriter: HarnessApplicationSkillPackWriter? = nil,
appleScriptGenerator: (@Sendable (HarnessScriptGenerationRequest) async -> HarnessScriptGenerationOutcome)? = nil,
appleScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)? = nil,
- skillScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)? = nil
+ skillScriptExecutor: (@Sendable (HarnessGeneratedScriptArtifact, HarnessToolExecutionContext) async -> HarnessScriptExecutionOutcome)? = nil,
+ commandExecutor: (@Sendable (HarnessToolExecutionContext) async -> HarnessToolResult?)? = nil
) {
self.memoryEntries = memoryEntries
self.appEntries = appEntries
@@ -235,6 +239,7 @@ public struct HarnessBuiltInToolServices: Sendable {
self.appleScriptGenerator = appleScriptGenerator
self.appleScriptExecutor = appleScriptExecutor
self.skillScriptExecutor = skillScriptExecutor
+ self.commandExecutor = commandExecutor
}
}
@@ -312,6 +317,10 @@ public enum BuiltInHarnessToolExecutors {
case "run.pause", "run.resume", "run.recover", "run.cancel", "run.complete", "run.failSafe":
return lifecycle(context)
default:
+ if let commandExecutor = services.commandExecutor,
+ let result = await commandExecutor(context) {
+ return result
+ }
return HarnessToolResult(
callID: context.call.id,
toolName: context.call.name,
diff --git a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
index 662c69f6..b00e5350 100644
--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessToolRegistry.swift
@@ -5,6 +5,11 @@ public struct HarnessToolDescriptor: Codable, Equatable, Sendable {
public var pluginID: String
public var summary: String
public var inputSchema: [String: String]
+ /// Input keys that are optional. Anything in `inputSchema` not listed here is
+ /// treated as required. Declared structurally rather than inferred from the
+ /// human-readable description text. (Property default keeps Codable decoding
+ /// of older payloads that lack the key tolerant.)
+ public var optionalInputKeys: [String] = []
public var outputSchema: [String: String]
public var requiredPermissions: [HarnessPermission]
public var safetyClass: HarnessToolSafetyClass
@@ -17,6 +22,7 @@ public struct HarnessToolDescriptor: Codable, Equatable, Sendable {
pluginID: String,
summary: String,
inputSchema: [String: String] = [:],
+ optionalInputKeys: [String] = [],
outputSchema: [String: String] = [:],
requiredPermissions: [HarnessPermission] = [],
safetyClass: HarnessToolSafetyClass,
@@ -28,6 +34,7 @@ public struct HarnessToolDescriptor: Codable, Equatable, Sendable {
self.pluginID = pluginID
self.summary = summary
self.inputSchema = inputSchema
+ self.optionalInputKeys = optionalInputKeys
self.outputSchema = outputSchema
self.requiredPermissions = requiredPermissions
self.safetyClass = safetyClass
@@ -544,7 +551,7 @@ public enum BuiltInHarnessToolCatalog {
permissions: [.lifecycle],
safety: .readOnly
)
- ]
+ ] + DonkeyCommandLayer.descriptors
}
public static func registryWithBuiltInExecutors(
diff --git a/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift
new file mode 100644
index 00000000..63dc1477
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyRuntime/DonkeyCommandBackends.swift
@@ -0,0 +1,324 @@
+import AppKit
+import DonkeyContracts
+import DonkeyHarness
+import Foundation
+
+/// Native implementations for the Donkey Command Layer (`DonkeyCommandLayer`).
+///
+/// These run in-process using AppKit / the bundled AppleScript backend — no
+/// screenshots, no Accessibility tree — so the model can act in well under
+/// 500ms. The executor is injected into the harness as
+/// `HarnessBuiltInToolServices.commandExecutor`.
+public enum DonkeyCommandBackends {
+ /// Build the closure wired into `HarnessBuiltInToolServices.commandExecutor`.
+ /// Returns a result for a recognized command, or `nil` so harness dispatch
+ /// falls through to its `unknownTool` handling.
+ public static func makeExecutor() -> @Sendable (HarnessToolExecutionContext) async -> HarnessToolResult? {
+ { context in await execute(context) }
+ }
+
+ @MainActor
+ static func execute(_ context: HarnessToolExecutionContext) async -> HarnessToolResult? {
+ guard let command = DonkeyCommandLayer.Command(rawValue: context.call.name) else {
+ return nil
+ }
+ switch command {
+ case .shellExec:
+ return await shellExec(context)
+ case .appsList:
+ return listApps(context)
+ case .musicPlay:
+ return await playMusic(context)
+ }
+ }
+
+ // MARK: - apps.list
+
+ @MainActor
+ private static func listApps(_ context: HarnessToolExecutionContext) -> HarnessToolResult {
+ let filter = trimmed(context.call.input["filter"])?.lowercased()
+
+ func passesFilter(_ value: String) -> Bool {
+ guard let filter else { return true }
+ return value.lowercased().contains(filter)
+ }
+
+ // Reuse the shared Spotlight-backed catalog (names + bundle ids, all the
+ // standard search roots) instead of a duplicated directory scan.
+ let installed = MacLocalAppAvailabilityProvider.installedApplications()
+ .filter { passesFilter($0.appName) || ($0.bundleIdentifier.map(passesFilter) ?? false) }
+ .map { candidate -> String in
+ guard let bundleID = candidate.bundleIdentifier, !bundleID.isEmpty else { return candidate.appName }
+ return "\(candidate.appName) (\(bundleID))"
+ }
+ .sorted { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending }
+
+ let running = NSWorkspace.shared.runningApplications
+ .filter { $0.activationPolicy == .regular }
+ .compactMap(\.localizedName)
+ .filter(passesFilter)
+ .sorted { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending }
+
+ return success(
+ context,
+ summary: "Installed (\(installed.count)): \(capped(installed))\nRunning (\(running.count)): \(capped(running))",
+ facts: ["installedAppCount": String(installed.count)],
+ metadata: [
+ "installed": capped(installed),
+ "running": capped(running)
+ ]
+ )
+ }
+
+ /// Join names, capped so the model response stays bounded.
+ private static func capped(_ names: [String], limit: Int = 3_000) -> String {
+ var result = ""
+ for name in names {
+ let next = result.isEmpty ? name : "\(result), \(name)"
+ if next.count > limit {
+ return result.isEmpty ? String(name.prefix(limit)) : "\(result), …"
+ }
+ result = next
+ }
+ return result
+ }
+
+ // MARK: - music.play
+
+ private static func playMusic(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {
+ guard trimmed(context.call.input["query"]) != nil else {
+ return invalidInput(context, "music.play requires a `query`.")
+ }
+ guard let artifact = LocalAppUserQueryHarnessServices
+ .builtInValidatedScriptArtifacts()
+ .first(where: { $0.id == "scripts-play-media-by-search" }) else {
+ return failed(context, "The bundled music playback skill is unavailable.", reason: "musicSkillUnavailable")
+ }
+ let outcome = await LocalAppUserQueryHarnessServices.executeSkillScript(artifact: artifact, context: context)
+ if outcome.metadata["clarification.required"] == "true" {
+ return HarnessToolResult(
+ callID: context.call.id,
+ toolName: context.call.name,
+ status: .waitingForUser,
+ summary: "The music app needs clarification before playing.",
+ question: outcome.metadata["clarification.question"] ?? "What would you like me to play?",
+ metadata: outcome.metadata.merging(["gate": "clarification"]) { current, _ in current }
+ )
+ }
+ guard outcome.succeeded else {
+ return failed(context, outcome.summary, reason: outcome.metadata["failureReason"] ?? "musicPlayFailed")
+ }
+ return success(
+ context,
+ summary: outcome.summary,
+ facts: ["musicStatus": outcome.metadata["status"] ?? "played"],
+ metadata: outcome.metadata
+ )
+ }
+
+ // MARK: - shell_exec
+
+ /// Max characters accepted for a one-line command.
+ private static let shellCommandMaxLength = 400
+ /// Seconds before a command is terminated.
+ private static let shellTimeout: TimeInterval = 12
+ /// Max stdout characters returned to the model.
+ private static let shellOutputMaxLength = 4_000
+
+ /// Executables that are unsafe in any position. Matched against the leading
+ /// token of each pipeline/command segment (path-stripped, dequoted), so a
+ /// bare `rm file`, `/bin/rm`, or a denied command inside `$(…)` is caught —
+ /// unlike substring matching, which both missed these and false-positived on
+ /// benign text.
+ private static let shellDeniedExecutables: Set<String> = [
+ "sudo", "su", "doas",
+ "rm", "rmdir", "mv", "dd", "mkfs", "fdisk", "diskutil", "shred", "srm",
+ "chmod", "chown", "chflags",
+ "shutdown", "reboot", "halt", "killall", "pkill", "kill",
+ "launchctl", "csrutil", "spctl", "nvram", "pmset",
+ "scp", "sftp", "ssh", "telnet", "nc", "ncat", "curl", "wget",
+ "eval", "source", "security"
+ ]
+
+ /// Dangerous regardless of position (shell-level constructs / sensitive
+ /// redirect targets / privilege-escalation phrases).
+ private static let shellDeniedSubstrings: [String] = [
+ "do shell script", ":(){", "| sh", "|sh", "| bash", "|bash",
+ "> /dev", ">/dev", "> /system", ">/system", "> /usr", ">/usr",
+ "> /etc", ">/etc", "defaults delete"
+ ]
+
+ /// Returns the matched unsafe token if the command should be refused, else nil.
+ static func unsafeShellReason(_ command: String) -> String? {
+ let lowered = command.lowercased()
+ for substring in shellDeniedSubstrings where lowered.contains(substring) {
+ return substring.trimmingCharacters(in: .whitespaces)
+ }
+ // Split into command segments on shell separators and substitution
+ // boundaries, then check each segment's leading executable.
+ let separators = CharacterSet(charactersIn: ";|&\n`(")
+ for segment in lowered.components(separatedBy: separators) {
+ let trimmedSegment = segment.trimmingCharacters(in: .whitespaces)
+ guard let firstToken = trimmedSegment.split(separator: " ").first.map(String.init) else { continue }
+ let executable = (firstToken.split(separator: "/").last.map(String.init) ?? firstToken)
+ .trimmingCharacters(in: CharacterSet(charactersIn: "\\'\"$"))
+ if shellDeniedExecutables.contains(executable) {
+ return executable
+ }
+ }
+ return nil
+ }
+
+ private static func shellExec(_ context: HarnessToolExecutionContext) async -> HarnessToolResult {
+ guard let command = trimmed(context.call.input["command"]) ?? trimmed(context.call.input["cmd"]) else {
+ return invalidInput(context, "shell_exec requires a one-line `command`.")
+ }
+ guard !command.contains("\n"), !command.contains("\r") else {
+ return invalidInput(context, "shell_exec only runs a single-line command.")
+ }
+ guard command.count <= shellCommandMaxLength else {
+ return invalidInput(context, "shell_exec command is too long.")
+ }
+ if let blocked = unsafeShellReason(command) {
+ return failed(
+ context,
+ "Refused an unsafe shell command (matched \"\(blocked)\").",
+ reason: "blockedCommand"
+ )
+ }
+
+ let result = await Task.detached(priority: .userInitiated) {
+ runShellSync(command, timeout: shellTimeout)
+ }.value
+
+ let stdout = String(result.stdout.prefix(shellOutputMaxLength))
+ guard result.exitCode == 0 else {
+ return HarnessToolResult(
+ callID: context.call.id,
+ toolName: context.call.name,
+ status: .failed,
+ summary: "Command exited with code \(result.exitCode).",
+ metadata: [
+ "executor": "donkeyCommandLayer",
+ "reason": result.timedOut ? "timedOut" : "nonZeroExit",
+ "exitCode": String(result.exitCode),
+ "stdout": stdout,
+ "stderr": String(result.stderr.prefix(shellOutputMaxLength))
+ ]
+ )
+ }
+ return success(
+ context,
+ summary: stdout.isEmpty ? "Command ran (no output)." : stdout,
+ facts: ["lastShellExitCode": "0"],
+ metadata: ["stdout": stdout, "exitCode": "0"]
+ )
+ }
+
+ private struct ShellResult: Sendable {
+ var exitCode: Int32
+ var stdout: String
+ var stderr: String
+ var timedOut: Bool
+ }
+
+ /// Run a one-line command via `/bin/zsh -c`, bounded by `timeout`. Blocking;
+ /// always called off the main actor via `Task.detached`.
+ private static func runShellSync(_ command: String, timeout: TimeInterval) -> ShellResult {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/bin/zsh")
+ process.arguments = ["-c", command]
+ let outPipe = Pipe()
+ let errPipe = Pipe()
+ process.standardOutput = outPipe
+ process.standardError = errPipe
+
+ // Signalled by the OS when the process actually exits — the only
+ // reliable completion signal (reading the pipes first can deadlock if the
+ // child fills the 64KB buffer and blocks on write).
+ let finished = DispatchSemaphore(value: 0)
+ process.terminationHandler = { _ in finished.signal() }
+
+ do {
+ try process.run()
+ } catch {
+ return ShellResult(exitCode: 127, stdout: "", stderr: error.localizedDescription, timedOut: false)
+ }
+
+ var timedOut = false
+ if finished.wait(timeout: .now() + timeout) == .timedOut {
+ timedOut = true
+ process.terminate() // SIGTERM
+ // Escalate to SIGKILL if it ignores SIGTERM, so the bound is real.
+ if finished.wait(timeout: .now() + 1.0) == .timedOut {
+ kill(process.processIdentifier, SIGKILL)
+ finished.wait()
+ }
+ }
+
+ // The process has exited, so the pipe write ends are closed and these
+ // reads return promptly without deadlocking.
+ let outData = outPipe.fileHandleForReading.readDataToEndOfFile()
+ let errData = errPipe.fileHandleForReading.readDataToEndOfFile()
+
+ return ShellResult(
+ exitCode: process.terminationStatus,
+ stdout: String(data: outData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "",
+ stderr: String(data: errData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "",
+ timedOut: timedOut
+ )
+ }
+
+ // MARK: - Result helpers
+
+ private static func success(
+ _ context: HarnessToolExecutionContext,
+ summary: String,
+ facts: [String: String],
+ metadata: [String: String]
+ ) -> HarnessToolResult {
+ var allFacts = facts
+ allFacts["lastAcceptedTool"] = context.call.name
+ return HarnessToolResult(
+ callID: context.call.id,
+ toolName: context.call.name,
+ status: .succeeded,
+ summary: summary,
+ observations: HarnessObservationDelta(facts: allFacts),
+ metadata: metadata.merging(["executor": "donkeyCommandLayer"]) { current, _ in current }
+ )
+ }
+
+ private static func failed(
+ _ context: HarnessToolExecutionContext,
+ _ summary: String,
+ reason: String
+ ) -> HarnessToolResult {
+ HarnessToolResult(
+ callID: context.call.id,
+ toolName: context.call.name,
+ status: .failed,
+ summary: summary,
+ metadata: ["executor": "donkeyCommandLayer", "reason": reason]
+ )
+ }
+
+ private static func invalidInput(
+ _ context: HarnessToolExecutionContext,
+ _ summary: String
+ ) -> HarnessToolResult {
+ HarnessToolResult(
+ callID: context.call.id,
+ toolName: context.call.name,
+ status: .invalidInput,
+ summary: summary,
+ metadata: ["executor": "donkeyCommandLayer", "reason": "invalidInput"]
+ )
+ }
+
+ private static func trimmed(_ value: String?) -> String? {
+ guard let value else { return nil }
+ let result = value.trimmingCharacters(in: .whitespacesAndNewlines)
+ return result.isEmpty ? nil : result
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swift
index 7f5887e1..9e28557f 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppUserQueryHarnessServices.swift
@@ -12,7 +12,11 @@ public enum LocalAppUserQueryHarnessServices {
},
skillScriptExecutor: { artifact, context in
await executeSkillScript(artifact: artifact, context: context)
- }
+ },
+ // The Command Layer (incl. shell_exec) is intentionally available to
+ // the local planner as well as the Gemini Live session; both go
+ // through the same DonkeyCommandBackends guardrails.
+ commandExecutor: DonkeyCommandBackends.makeExecutor()
)
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
index 628e19bf..3cb7b549 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift
@@ -393,6 +393,125 @@ struct GenericHarnessTests {
#expect(result.metadata["reason"] == "unknownTool")
}
+ @Test
+ func donkeyCommandLayerDescriptorsAreSurfaced() {
+ let descriptors = BuiltInHarnessToolCatalog.descriptors
+ let names = Set(descriptors.map(\.name))
+ for command in DonkeyCommandLayer.Command.allCases {
+ #expect(names.contains(command.rawValue))
+ }
+ // Command Layer tools must not be sensitive/destructive, or the planner
+ // tool-name filter would drop them from the model's tool list.
+ let commandDescriptors = descriptors.filter { $0.pluginID == DonkeyCommandLayer.pluginID }
+ #expect(commandDescriptors.count == DonkeyCommandLayer.Command.allCases.count)
+ for descriptor in commandDescriptors {
+ #expect(descriptor.safetyClass != .sensitive)
+ #expect(descriptor.safetyClass != .destructive)
+ }
+ }
+
+ @Test
+ func donkeyCommandLayerDiscoversAppsAndFallsThrough() async {
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(
+ services: HarnessBuiltInToolServices(commandExecutor: DonkeyCommandBackends.makeExecutor())
+ )
+
+ // apps.list is read-only discovery and always succeeds.
+ let apps = await registry.execute(
+ HarnessToolCall(id: "apps-1", name: "apps.list"),
+ taskID: "task-apps",
+ worldModel: HarnessWorldModel(),
+ grantedPermissions: [.appLookup]
+ )
+ #expect(apps.status == .succeeded)
+ #expect(apps.metadata["installed"] != nil)
+
+ // shell_exec with no command is rejected without side effects.
+ let emptyShell = await registry.execute(
+ HarnessToolCall(id: "sh-empty", name: "shell_exec"),
+ taskID: "task-sh-empty",
+ worldModel: HarnessWorldModel(),
+ grantedPermissions: [.appControl, .input]
+ )
+ #expect(emptyShell.status == .invalidInput)
+
+ // Delegation must still fall through to unknownTool for names the
+ // Command Layer does not own.
+ let unknown = await registry.execute(
+ HarnessToolCall(id: "x-1", name: "not.a.command"),
+ taskID: "task-unknown",
+ worldModel: HarnessWorldModel(),
+ grantedPermissions: [.appControl]
+ )
+ #expect(unknown.status == .unknownTool)
+ }
+
+ @Test
+ func shellExecRunsSafeCommandsAndBlocksDangerousOnes() async {
+ let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(
+ services: HarnessBuiltInToolServices(commandExecutor: DonkeyCommandBackends.makeExecutor())
+ )
+ let permissions: Set<HarnessPermission> = [.appControl, .input]
+
+ let ok = await registry.execute(
+ HarnessToolCall(id: "sh-1", name: "shell_exec", input: ["command": "echo donkey-ok"]),
+ taskID: "task-sh-ok",
+ worldModel: HarnessWorldModel(),
+ grantedPermissions: permissions
+ )
+ #expect(ok.status == .succeeded)
+ #expect(ok.metadata["stdout"] == "donkey-ok")
+ #expect(ok.metadata["exitCode"] == "0")
+
+ let blocked = await registry.execute(
+ HarnessToolCall(id: "sh-2", name: "shell_exec", input: ["command": "sudo rm -rf /"]),
+ taskID: "task-sh-blocked",
+ worldModel: HarnessWorldModel(),
+ grantedPermissions: permissions
+ )
+ #expect(blocked.status == .failed)
+ #expect(blocked.metadata["reason"] == "blockedCommand")
+
+ let multiline = await registry.execute(
+ HarnessToolCall(id: "sh-3", name: "shell_exec", input: ["command": "echo a\necho b"]),
+ taskID: "task-sh-multiline",
+ worldModel: HarnessWorldModel(),
+ grantedPermissions: permissions
+ )
+ #expect(multiline.status == .invalidInput)
+
+ // Hardened guardrail: a bare `rm` (no flags) is caught as a command word.
+ let bareRm = await registry.execute(
+ HarnessToolCall(id: "sh-4", name: "shell_exec", input: ["command": "rm ~/Documents/notes.txt"]),
+ taskID: "task-sh-rm",
+ worldModel: HarnessWorldModel(),
+ grantedPermissions: permissions
+ )
+ #expect(bareRm.status == .failed)
+ #expect(bareRm.metadata["reason"] == "blockedCommand")
+
+ // The osascript `do shell script` escape hatch is blocked.
+ let osaShell = await registry.execute(
+ HarnessToolCall(id: "sh-5", name: "shell_exec", input: ["command": "osascript -e 'do shell script \"rm -rf ~/x\"'"]),
+ taskID: "task-sh-osa",
+ worldModel: HarnessWorldModel(),
+ grantedPermissions: permissions
+ )
+ #expect(osaShell.status == .failed)
+ #expect(osaShell.metadata["reason"] == "blockedCommand")
+
+ // A benign redirect to a temp path is NOT a false positive (the old `> /`
+ // rule wrongly blocked this).
+ let redirect = await registry.execute(
+ HarnessToolCall(id: "sh-6", name: "shell_exec", input: ["command": "echo donkey > /tmp/donkey-review-test.txt"]),
+ taskID: "task-sh-redirect",
+ worldModel: HarnessWorldModel(),
+ grantedPermissions: permissions
+ )
+ #expect(redirect.status == .succeeded)
+ try? FileManager.default.removeItem(atPath: "/tmp/donkey-review-test.txt")
+ }
+
@Test
func builtInExecutorsRetrieveMemoryAndResolveApps() async {
let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors(