Open source CapCut alternative.
TypeScript
feat(app): richer planner prompt, honest failure handling, Live shell/app doctrine
David Lec034233a1a2d
diff --git a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swiftindex 0e199b92..b61e24ce 100644--- a/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift+++ b/apps/Donkey/Sources/DonkeyAI/DonkeyPrompts.swift@@ -37,19 +37,29 @@ public enum DonkeyPrompts {public static let realtimeCommandSystemInstruction = """You are Donkey, a fast macOS assistant — an expert computer user sitting next \to the user. Act directly and immediately with the registered tools, preferring \- shell_exec for anything the more specific tools don't cover. When a task targets \- a specific app, call app_skill first unless you already know how to drive it: \- the installed skill is the authority on how that app is operated (scripting, \- vision, known workflows) and overrides your assumptions. When a skill \- advertises a validated script that covers the task, execute it with skill_run \- instead of reinventing the 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 inventing names or values. Read each tool's returned \- output and retry or adjust on failure. Always end your turn by telling the user \- the answer or what you did, concretely and briefly — e.g. name the files you \- found, confirm the app you opened.+ shell_exec for anything the more specific tools don't cover. To read or change \+ content inside a Mac app (a note, mail, a calendar event, a contact, the current \+ browser tab), drive it with AppleScript (`osascript -e 'tell application "App" to \+ …'`), NEVER an invented app URL scheme like `notes://` or `bear://` — those \+ silently fail on macOS; use `open` only to open files/URLs or launch an app. When \+ a task targets a specific app, call app_skill first unless you are just launching \+ it: the installed skill is the authority on how to operate that app and overrides \+ remembered schemes or shortcuts. For shell technique the built-in `system-tools` \+ skill is the authority (safe file-finding, settings); consult it when a command \+ errors — and note shell_exec runs under zsh, where a glob matching nothing aborts \+ with `no matches found`, which never means "no such files exist": widen the search \+ (e.g. `ls -t ~/Downloads | grep -iE '\\.png$|\\.jpg$' | head -1`) and avoid \+ parentheses, which trip the safety classifier. When a skill advertises a validated \+ script that covers the task, execute it with skill_run instead of reinventing the \+ 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 \+ inventing names or values. Read each tool's returned output and retry or adjust on \+ failure; if an approach errors, do not repeat the same command — switch to \+ AppleScript or app_skill. Always end your turn by telling the user the answer or \+ what you did, concretely and briefly — e.g. name the files you found, confirm the \+ app you opened."""// MARK: - Request understanding (once per turn, before the loop)@@ -89,24 +99,20 @@ public enum DonkeyPrompts {/// (highest-signal first).public static let harnessStepMaxElements = 150+ /// The most recent steps rendered with their full one-line summaries; everything older is+ /// condensed to "tool → status" so the model never loses sight of its own earlier trajectory.+ public static let harnessStepMaxDetailedHistorySteps = 12+public static func harnessStep(task: HarnessTaskState,descriptors: [HarnessToolDescriptor],appName: String,appGuidance: String?,understanding: HarnessRequestUnderstanding?,- environmentSummary: String?+ environmentSummary: String?,+ retryNote: String? = nil) -> String {- let elements = task.worldModel.elements- let elementsBlock: String- if elements.isEmpty {- elementsBlock = "No on-screen elements have been observed. That is normal for system-tool tasks (shell_exec needs no observation). Only if the task needs the GUI, use a SEE tool (ax.observe or vision.capture) before acting on an element."- } else {- let lines = elements.prefix(harnessStepMaxElements).map { element -> String in- " \(element.id): [\(element.role)] \"\(element.label)\""- }.joined(separator: "\n")- elementsBlock = "Elements currently observed (id: [role] \"label\"):\n\(lines)"- }+ let elementsBlock = harnessStepElementsBlock(task.worldModel.elements)let factsBlock = task.worldModel.facts.isEmpty? ""@@ -117,10 +123,7 @@ public enum DonkeyPrompts {? "\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."- : "Steps already taken (most recent last):\n" + history.joined(separator: "\n")+ let historyBlock = harnessStepHistoryBlock(task.toolHistory)let toolsBlock = descriptors.sorted { $0.name < $1.name }@@ -181,10 +184,105 @@ public enum DonkeyPrompts {- Verification must be evidence-backed: after acting, confirm the effect (a shell command'soutput/exit code, a re-observe, or state.verify) BEFORE choosing run.complete. A focused appis 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>"}.+ Return JSON: {"tool": "<one tool name>", "input": {"key": "value", ...}, "reason": "<one sentence>"}.\(retryNote.map { "\nIMPORTANT: \($0)" } ?? "")+ """+ }++ /// Renders observed elements in reading order with the geometry and state the observation already+ /// captured — position (from `ax.frame.*` screen points or `vision.bbox.*` capture pixels), value,+ /// and click eligibility — so the model can reason spatially ("the field under the Subject label")+ /// instead of guessing from bare labels. Over the cap, clickable controls are kept first and the+ /// drop is announced rather than silent.+ public static func harnessStepElementsBlock(_ elements: [HarnessWorldElement]) -> String {+ guard !elements.isEmpty else {+ return "No on-screen elements have been observed. That is normal for system-tool tasks (shell_exec needs no observation). Only if the task needs the GUI, use a SEE tool (ax.observe or vision.capture) before acting on an element."+ }+ let ordered = readingOrder(elements)+ var kept = ordered+ var omitted = 0+ if ordered.count > harnessStepMaxElements {+ let clickable = ordered.filter(\.isActionEligible)+ let rest = ordered.filter { !$0.isActionEligible }+ kept = readingOrder(Array((clickable + rest).prefix(harnessStepMaxElements)))+ omitted = ordered.count - kept.count+ }+ let lines = kept.map(elementLine).joined(separator: "\n")+ let omittedLine = omitted > 0 ? "\n (+\(omitted) more element(s) not shown; clickable controls were kept)" : ""+ return """+ Elements currently observed, in reading order (id: [role] "label" @(x,y wxh) — use the \+ positions to reason about layout: above/below/left/right):+ \(lines)\(omittedLine)"""}+ private static func elementLine(_ element: HarnessWorldElement) -> String {+ var line = " \(element.id): [\(element.role)] \"\(element.label)\""+ if let frame = frame(of: element) {+ line += " @(\(Int(frame.x)),\(Int(frame.y)) \(Int(frame.width))x\(Int(frame.height)))"+ }+ if let value = element.metadata["ax.value"], !value.isEmpty {+ line += " value=\"\(String(value.prefix(80)))\""+ }+ if !element.isActionEligible {+ line += " (not clickable)"+ }+ return line+ }++ private struct ElementFrame {+ var x: Double+ var y: Double+ var width: Double+ var height: Double+ }++ /// Both observation producers stash geometry in element metadata: AX observations under+ /// `ax.frame.*` (screen points) and vision parses under `vision.bbox.*` (capture-image pixels).+ /// One observation always uses a single source, so positions stay mutually comparable.+ private static func frame(of element: HarnessWorldElement) -> ElementFrame? {+ for prefix in ["ax.frame", "vision.bbox"] {+ if let x = element.metadata["\(prefix).x"].flatMap(Double.init),+ let y = element.metadata["\(prefix).y"].flatMap(Double.init),+ let width = element.metadata["\(prefix).width"].flatMap(Double.init),+ let height = element.metadata["\(prefix).height"].flatMap(Double.init) {+ return ElementFrame(x: x, y: y, width: width, height: height)+ }+ }+ return nil+ }++ /// Top-to-bottom, then left-to-right; elements without geometry keep their original order at the end.+ private static func readingOrder(_ elements: [HarnessWorldElement]) -> [HarnessWorldElement] {+ elements.enumerated().sorted { lhs, rhs in+ switch (frame(of: lhs.element), frame(of: rhs.element)) {+ case let (left?, right?):+ return (left.y, left.x) < (right.y, right.x)+ case (.some, .none):+ return true+ case (.none, .some):+ return false+ case (.none, .none):+ return lhs.offset < rhs.offset+ }+ }.map(\.element)+ }++ /// Detailed one-line summaries for the most recent steps, preceded by a condensed+ /// "tool → status" trail of everything older, so a long run never forgets where it has been.+ public static func harnessStepHistoryBlock(_ toolHistory: [HarnessToolCallRecord]) -> String {+ guard !toolHistory.isEmpty else { return "Nothing has been done yet." }+ let recent = Array(toolHistory.suffix(harnessStepMaxDetailedHistorySteps))+ let evicted = toolHistory.dropLast(recent.count)+ var lines: [String] = []+ if !evicted.isEmpty {+ let condensed = evicted.map { "\($0.call.name) → \($0.resultStatus.rawValue)" }+ .joined(separator: "; ")+ lines.append(" Earlier steps 1-\(evicted.count) (condensed): \(condensed)")+ }+ lines += recent.map { " \($0.call.name): \($0.summary)" }+ return "Steps already taken (most recent last):\n" + lines.joined(separator: "\n")+ }+/// A compact, high-signal block describing the parsed request, rendered every step so the planner/// keeps the precise target, parameters, and success criteria in view. Empty when no understanding/// was produced.diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swiftindex 5140dcbb..861373a7 100644--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift@@ -69,20 +69,35 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {descriptors.contains(where: { $0.name == "user.clarify" }) {return HarnessToolCall(name: "user.clarify", input: ["question": question])}- let decision: Decision- do {- decision = try await decide(task: task)- } catch {- return HarnessToolCall(name: "run.failSafe", input: ["reason": "harnessPlanFailed"])- }- lastNarration = decision.reason.flatMap { $0.isEmpty ? nil : $0 } ?? lastNarration- guard let toolName = decision.tool.flatMap({ $0.isEmpty ? nil : $0 }) else {- return HarnessToolCall(name: "run.complete", input: ["reason": decision.reason ?? "Goal satisfied."])- }- if !readOnlyToolNames.contains(toolName), firstActionUptimeMS == nil {- firstActionUptimeMS = uptimeMS()+ // One bad model sample must not kill the run, and an empty tool name must never read as+ // completion (a refusal or truncated reply would otherwise be recorded as success). Retry the+ // inference once with the failure fed back; only then fail safe.+ var retryNote: String?+ for attempt in 0..<2 {+ let decision: Decision+ do {+ decision = try await decide(task: task, retryNote: retryNote)+ } catch {+ guard attempt == 0 else { break }+ retryNote = "Your previous reply could not be used (\(String(describing: error).prefix(200))). "+ + "Reply with exactly one JSON object naming one tool from AVAILABLE TOOLS."+ continue+ }+ lastNarration = decision.reason.flatMap { $0.isEmpty ? nil : $0 } ?? lastNarration+ guard let toolName = decision.tool.flatMap({ $0.isEmpty ? nil : $0 }) else {+ guard attempt == 0 else {+ return HarnessToolCall(name: "run.failSafe", input: ["reason": "plannerReturnedNoTool"])+ }+ retryNote = "Your previous reply named no tool. Pick exactly one tool from AVAILABLE TOOLS; "+ + "choose run.complete only when the goal is already confirmed by observed evidence."+ continue+ }+ if !readOnlyToolNames.contains(toolName), firstActionUptimeMS == nil {+ firstActionUptimeMS = uptimeMS()+ }+ return HarnessToolCall(name: toolName, input: decision.input ?? [:])}- return HarnessToolCall(name: toolName, input: decision.input ?? [:])+ return HarnessToolCall(name: "run.failSafe", input: ["reason": "harnessPlanFailed"])}// MARK: - Model call@@ -149,8 +164,8 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {/// caller fails safe instead of stalling the whole run on a hung provider.private static let stepTimeoutSeconds: TimeInterval = 45- private func decide(task: HarnessTaskState) async throws -> Decision {- let request = responseRequest(task: task)+ private func decide(task: HarnessTaskState, retryNote: String?) async throws -> Decision {+ let request = responseRequest(task: task, retryNote: retryNote)let backend = self.backendlet response = try await AIDeadline.enforce(seconds: Self.stepTimeoutSeconds) {try await backend.createResponse(request)@@ -164,7 +179,7 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {return Decision(tool: wire.tool, input: wire.input, reason: wire.reason)}- private func responseRequest(task: HarnessTaskState) -> RemoteInferenceResponseCreateRequest {+ private func responseRequest(task: HarnessTaskState, retryNote: String?) -> RemoteInferenceResponseCreateRequest {let toolNames = descriptors.map(\.name)return RemoteInferenceResponseCreateRequest(input: .array([@@ -179,7 +194,8 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {appName: appName,appGuidance: appGuidance,understanding: understanding,- environmentSummary: environmentSummary+ environmentSummary: environmentSummary,+ retryNote: retryNote))])])diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swiftindex a98af3e5..024e1333 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift@@ -86,10 +86,122 @@ struct HostedHarnessStepPlannerTests {#expect(!body.contains("WHAT THE USER WANTS"))}+ @Test+ func retriesOnceOnMalformedReplyThenUsesTheSecondDecision() async {+ let httpClient = SequencedHTTPClient(responses: [+ (Data(#"{"output_text":"not json at all"}"#.utf8), 200),+ (cannedDecision(tool: "ax.observe"), 200)+ ])+ let planner = makePlanner(httpClient: httpClient, understanding: nil)++ let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))++ #expect(call?.name == "ax.observe")+ #expect(httpClient.requests.count == 2)+ // The retry prompt names the failure so the model can correct itself.+ let retryBody = requestBodyString(httpClient, index: 1)+ #expect(retryBody.contains("could not be used"))+ }++ @Test+ func failsSafeAfterTwoFailedInferences() async {+ let httpClient = SequencedHTTPClient(responses: [+ (Data(), 500),+ (Data(), 500)+ ])+ let planner = makePlanner(httpClient: httpClient, understanding: nil)++ let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))++ #expect(call?.name == "run.failSafe")+ #expect(httpClient.requests.count == 2)+ }++ @Test+ func emptyToolNameNeverReadsAsCompletion() async {+ // A refusal or truncated reply decodes with no tool. That must re-ask once and then fail+ // safe — never run.complete, which would record an unverified claim as success.+ let httpClient = SequencedHTTPClient(responses: [+ (Data(#"{"output_text":"{\"tool\":\"\",\"reason\":\"cannot help\"}"}"#.utf8), 200),+ (Data(#"{"output_text":"{\"tool\":\"\",\"reason\":\"cannot help\"}"}"#.utf8), 200)+ ])+ let planner = makePlanner(httpClient: httpClient, understanding: nil)++ let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))++ #expect(call?.name == "run.failSafe")+ #expect(call?.input["reason"] == "plannerReturnedNoTool")+ }++ @Test+ func emptyToolNameRecoversWhenTheRetryNamesATool() async {+ let httpClient = SequencedHTTPClient(responses: [+ (Data(#"{"output_text":"{\"tool\":\"\",\"reason\":\"unsure\"}"}"#.utf8), 200),+ (cannedDecision(tool: "ax.observe"), 200)+ ])+ let planner = makePlanner(httpClient: httpClient, understanding: nil)++ let call = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))++ #expect(call?.name == "ax.observe")+ let retryBody = requestBodyString(httpClient, index: 1)+ #expect(retryBody.contains("named no tool"))+ }++ @Test+ func promptRendersElementGeometryValueAndEligibility() async {+ let httpClient = FixtureHTTPClient(data: cannedDecision(tool: "ax.observe"), statusCode: 200)+ let planner = makePlanner(httpClient: httpClient, understanding: nil)+ var state = task(goal: "open settings", toolHistory: [])+ state.worldModel.elements = [+ HarnessWorldElement(+ id: "btn1",+ label: "Send",+ role: "button",+ isActionEligible: true,+ metadata: [+ "ax.frame.x": "100", "ax.frame.y": "200",+ "ax.frame.width": "80", "ax.frame.height": "30",+ "ax.value": "ready"+ ]+ ),+ HarnessWorldElement(id: "lbl1", label: "Banner", role: "staticText", isActionEligible: false)+ ]++ _ = await planner.planNextStep(for: state)++ let body = requestBodyString(httpClient, index: 0)+ #expect(body.contains("@(100,200 80x30)"))+ #expect(body.contains(#"value=\"ready\""#))+ #expect(body.contains("(not clickable)"))+ }++ @Test+ func promptCondensesEvictedHistoryInsteadOfDroppingIt() async {+ let httpClient = FixtureHTTPClient(data: cannedDecision(tool: "ax.observe"), statusCode: 200)+ let planner = makePlanner(httpClient: httpClient, understanding: nil)+ let history = (1...15).map { index in+ HarnessToolCallRecord(+ call: HarnessToolCall(name: "step\(index)", input: [:]),+ resultStatus: index == 2 ? .failed : .succeeded,+ summary: "Summary of step \(index)."+ )+ }++ _ = await planner.planNextStep(for: task(goal: "open settings", toolHistory: history))++ let body = requestBodyString(httpClient, index: 0)+ // The first three steps fall outside the detailed window but stay visible condensed.+ #expect(body.contains("Earlier steps 1-3 (condensed)"))+ #expect(body.contains("step2 → failed"))+ #expect(!body.contains("Summary of step 1."))+ #expect(body.contains("Summary of step 15."))+ }+// MARK: - Helpersprivate func makePlanner(- httpClient: FixtureHTTPClient,+ httpClient: any AIHTTPClient,understanding: HarnessRequestUnderstanding?) -> HostedHarnessStepPlanner {HostedHarnessStepPlanner(@@ -129,8 +241,17 @@ struct HostedHarnessStepPlannerTests {Data(#"{"output_text":"{\"tool\":\"\#(tool)\",\"reason\":\"step\"}"}"#.utf8)}- private func requestBodyString(_ httpClient: FixtureHTTPClient) -> String {- guard let body = httpClient.requests.first?.httpBody,+ private func requestBodyString(_ httpClient: FixtureHTTPClient, index: Int = 0) -> String {+ requestBodyString(requests: httpClient.requests, index: index)+ }++ private func requestBodyString(_ httpClient: SequencedHTTPClient, index: Int = 0) -> String {+ requestBodyString(requests: httpClient.requests, index: index)+ }++ private func requestBodyString(requests: [URLRequest], index: Int) -> String {+ guard requests.indices.contains(index),+ let body = requests[index].httpBody,let string = String(data: body, encoding: .utf8) else {return ""}@@ -156,3 +277,22 @@ private final class FixtureHTTPClient: AIHTTPClient, @unchecked Sendable {)}}++/// Returns each canned response once, in order, repeating the last one if called again.+private final class SequencedHTTPClient: AIHTTPClient, @unchecked Sendable {+ var responses: [(data: Data, statusCode: Int)]+ var requests: [URLRequest] = []++ init(responses: [(data: Data, statusCode: Int)]) {+ self.responses = responses+ }++ func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {+ requests.append(request)+ let response = responses[min(requests.count - 1, responses.count - 1)]+ return (+ response.data,+ HTTPURLResponse(url: request.url!, statusCode: response.statusCode, httpVersion: nil, headerFields: [:])!+ )+ }+}