Open source CapCut alternative.
TypeScript
feat(app): understand the request once before the harness loop
David Lea4964fbdae6b
diff --git a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swiftindex 271ac6a7..812b8978 100644--- a/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift@@ -244,20 +244,38 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {preparedTurnMetadata: preparedTurnMetadata)}- let appName = target.appName ?? "the frontmost app"- let bundleIdentifier = target.bundleIdentifier+ let frontmostAppName = target.appName ?? "the frontmost app"+ let frontmostBundleIdentifier = target.bundleIdentifierguard let configuration = try? DonkeyBackendInferenceConfiguration.fromEnvironment() else {return await failHarnessRun(response: "The vision backend isn't configured (set DONKEY_WEB_BASE_URL), so I couldn't navigate by vision.",reason: "visionBackendUnavailable",- appName: appName,+ appName: frontmostAppName,traceID: traceID,taskID: taskID,preparedTurnMetadata: preparedTurnMetadata)}let backend = DonkeyBackendInferenceClient(configuration: configuration)++ // Understand the request ONCE before the loop: restate the goal, identify the target app,+ // extract parameters, and decide whether to clarify. Degrades to driving the raw command when+ // it returns nil, so a backend hiccup never dead-ends the run.+ let understanding = await HostedHarnessRequestUnderstanding(backend: backend)+ .understand(command: command, frontmostAppName: frontmostAppName)++ // Drive the understood target app when it names one that resolves to a running window; else the+ // frontmost app. resolveTarget never falls back to an unrelated window, so a miss keeps us on+ // the frontmost app and the planner can app.openOrFocus the target itself.+ let driveTarget = Self.resolveDriveTarget(+ understanding: understanding,+ frontmostAppName: frontmostAppName,+ frontmostBundleIdentifier: frontmostBundleIdentifier+ )+ let appName = driveTarget.appName+ let bundleIdentifier = driveTarget.bundleIdentifier+let appGuidance = BuiltInLocalAppSkillPacks.appOperatingGuidance(forApp: appName,bundleIdentifier: bundleIdentifier@@ -310,7 +328,8 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {backend: backend,descriptors: plannerDescriptors,appName: appName,- appGuidance: appGuidance+ appGuidance: appGuidance,+ understanding: understanding)_ = await genericHarnessLifecycle.coordinator.startRunning(taskID: taskID,@@ -324,7 +343,7 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {// Suspend the warm-cache monitor for the whole drive so it never races us writing the same// app's parse. The run between these calls has no early exit, so resume always pairs with it.VisionWarmCacheActivity.shared.suspend()- let runSteps = await runtime.run(taskID: taskID, planner: planner, maxSteps: 8)+ let runSteps = await runtime.run(taskID: taskID, planner: planner, maxSteps: 24)VisionWarmCacheActivity.shared.resume()let finalTask = await genericHarnessLifecycle.coordinator.task(id: taskID)@@ -528,6 +547,26 @@ struct LocalAppUserQueryCommandHandler: UserQueryCommandHandling {]}+ /// Picks the app the harness drive operates: the understood target app when it names one that+ /// resolves to a running window, otherwise the frontmost app. `AccessibilityObserver.resolveTarget`+ /// only ever returns the named app's window (never an unrelated frontmost one), so a non-running or+ /// misnamed target safely falls back to the frontmost app.+ @MainActor+ private static func resolveDriveTarget(+ understanding: HarnessRequestUnderstanding?,+ frontmostAppName: String,+ frontmostBundleIdentifier: String?+ ) -> (appName: String, bundleIdentifier: String?) {+ guard let requested = understanding?.targetAppName,+ !requested.isEmpty,+ requested.caseInsensitiveCompare(frontmostAppName) != .orderedSame,+ let resolved = AccessibilityObserver.resolveTarget(appName: requested, bundleIdentifier: nil)+ else {+ return (frontmostAppName, frontmostBundleIdentifier)+ }+ return (resolved.appName ?? requested, resolved.bundleIdentifier)+ }+static func genericHarnessToolNames() -> [String] {let allowedSensitiveTools: Set<String> = ["automation.applescript.generate"diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swiftnew file mode 100644index 00000000..9ead6582--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift@@ -0,0 +1,205 @@+import DonkeyContracts+import Foundation++/// A focused, one-shot "understand the request" boundary that runs ONCE before the harness loop.+///+/// It does not plan or pick tools. It turns the raw user command into a small typed understanding the+/// loop can act on: a restated goal, the app to operate, the key parameters, observable success+/// criteria, and a clarify gate. The per-step `HostedHarnessStepPlanner` still chooses every tool —+/// this only sharpens what "the goal" means and which app to drive, so the planner stops re-deriving+/// intent from a raw string on every step.+public 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.+ public var targetAppName: String?+ /// Structured parameters extracted from the request (e.g. title, recipient, query).+ public var parameters: [String: String]+ /// What, observable on screen, would mean the goal is done.+ public var successCriteria: String?+ /// True only when the request is genuinely ambiguous or missing critical detail and cannot be+ /// safely resolved with reasonable defaults.+ public var needsClarification: Bool+ /// The question to ask when `needsClarification` is true.+ public var clarifyingQuestion: String?++ public init(+ restatedGoal: String,+ targetAppName: String? = nil,+ parameters: [String: String] = [:],+ successCriteria: String? = nil,+ needsClarification: Bool = false,+ clarifyingQuestion: String? = nil+ ) {+ self.restatedGoal = restatedGoal+ self.targetAppName = targetAppName+ self.parameters = parameters+ self.successCriteria = successCriteria+ self.needsClarification = needsClarification+ self.clarifyingQuestion = clarifyingQuestion+ }+}++/// Makes the single hosted call that produces a `HarnessRequestUnderstanding`. Mirrors the request /+/// decode shape of `HostedHarnessStepPlanner` (one `createResponse`, a JSON-schema response, scalar+/// coercion on decode) so both boundaries stay consistent.+@MainActor+public final class HostedHarnessRequestUnderstanding {+ private let backend: DonkeyBackendInferenceClient++ public init(backend: DonkeyBackendInferenceClient) {+ self.backend = backend+ }++ /// Returns the parsed understanding, or `nil` on any provider/decode failure so the caller can+ /// degrade to driving the raw command directly rather than dead-ending.+ public func understand(command: String, frontmostAppName: String) async -> HarnessRequestUnderstanding? {+ do {+ let response = try await backend.createResponse(responseRequest(command: command, frontmostAppName: frontmostAppName))+ guard let text = RemoteInferenceResponseHelpers.outputText(from: response), !text.isEmpty else {+ return nil+ }+ let json = DebugUIInspectionResponseDecoder.jsonObjectSubstring(text)+ let wire = try JSONDecoder().decode(UnderstandingWire.self, from: Data(json.utf8))+ let restated = wire.restatedGoal?.trimmingCharacters(in: .whitespacesAndNewlines)+ guard let restated, !restated.isEmpty else { return nil }+ return HarnessRequestUnderstanding(+ restatedGoal: restated,+ targetAppName: wire.targetAppName.flatMap { $0.isEmpty ? nil : $0 },+ parameters: wire.parameters ?? [:],+ successCriteria: wire.successCriteria.flatMap { $0.isEmpty ? nil : $0 },+ needsClarification: wire.needsClarification ?? false,+ clarifyingQuestion: wire.clarifyingQuestion.flatMap { $0.isEmpty ? nil : $0 }+ )+ } catch {+ return nil+ }+ }++ // MARK: - Wire++ private struct UnderstandingWire: Decodable {+ var restatedGoal: String?+ var targetAppName: String?+ var parameters: [String: String]?+ var successCriteria: String?+ var needsClarification: Bool?+ var clarifyingQuestion: String?++ private enum CodingKeys: String, CodingKey {+ case restatedGoal, targetAppName, parameters, successCriteria, needsClarification, clarifyingQuestion+ }++ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ restatedGoal = try container.decodeIfPresent(String.self, forKey: .restatedGoal)+ targetAppName = try container.decodeIfPresent(String.self, forKey: .targetAppName)+ successCriteria = try container.decodeIfPresent(String.self, forKey: .successCriteria)+ clarifyingQuestion = try container.decodeIfPresent(String.self, forKey: .clarifyingQuestion)+ needsClarification = try container.decodeIfPresent(Bool.self, forKey: .needsClarification)+ // The schema is non-strict, so a parameter value may arrive as a number or boolean. Coerce+ // scalars to strings instead of failing the whole decode.+ parameters = try container.decodeIfPresent([String: ScalarString].self, forKey: .parameters)?+ .mapValues(\.value)+ }+ }++ /// A JSON scalar (string, number, boolean, or null) decoded into its string form.+ private struct ScalarString: Decodable {+ let value: String++ init(from decoder: Decoder) throws {+ let container = try decoder.singleValueContainer()+ if let string = try? container.decode(String.self) {+ value = string+ } else if let bool = try? container.decode(Bool.self) {+ value = String(bool)+ } else if let int = try? container.decode(Int.self) {+ value = String(int)+ } else if let double = try? container.decode(Double.self) {+ value = String(double)+ } else if container.decodeNil() {+ value = ""+ } else {+ throw DecodingError.dataCorruptedError(+ in: container,+ debugDescription: "Parameter value is not a JSON scalar"+ )+ }+ }+ }++ private func responseRequest(command: String, frontmostAppName: String) -> RemoteInferenceResponseCreateRequest {+ RemoteInferenceResponseCreateRequest(+ input: .array([+ .object([+ "role": .string("user"),+ "content": .array([+ .object([+ "type": .string("input_text"),+ "text": .string(prompt(command: command, frontmostAppName: frontmostAppName))+ ])+ ])+ ])+ ]),+ store: false,+ text: [+ "format": .object([+ "type": .string("json_schema"),+ "name": .string("harness_request_understanding_v1"),+ "strict": .bool(false),+ "schema": .object([+ "type": .string("object"),+ "additionalProperties": .bool(false),+ "required": .array([.string("restatedGoal"), .string("needsClarification")]),+ "properties": .object([+ "restatedGoal": .object(["type": .string("string")]),+ "targetAppName": .object(["type": .string("string")]),+ "parameters": .object([+ "type": .string("object"),+ "additionalProperties": .object(["type": .string("string")])+ ]),+ "successCriteria": .object(["type": .string("string")]),+ "needsClarification": .object(["type": .string("boolean")]),+ "clarifyingQuestion": .object(["type": .string("string")])+ ])+ ])+ ])+ ],+ metadata: ["source": "hosted-harness-request-understanding", "prompt_version": "harness-request-understanding-v1"],+ parameters: [+ "temperature": .number(0),+ "max_output_tokens": .number(800),+ "thinking_budget": .number(0)+ ]+ )+ }++ private func prompt(command: String, frontmostAppName: String) -> String {+ """+ You are the first step of a macOS agent. Read the user's request and return a precise, structured+ understanding of EXACTLY what they want. You do not act or choose tools here — a separate planner+ does that. Be broad in what you accept and specific in what you capture.++ The app currently in front of the user is "\(frontmostAppName)".++ USER REQUEST: \(command)++ 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.+ - parameters: the concrete details needed to do it (e.g. title, recipient, query, value), as+ string key/values. Omit what is not specified.+ - successCriteria: what would be visible on screen once the goal is done.+ - 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.+ - clarifyingQuestion: the single question to ask when needsClarification is true; otherwise empty.++ Return JSON only.+ """+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swiftindex 813164eb..4dc0e75e 100644--- a/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift+++ b/apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift@@ -17,6 +17,10 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {private let descriptors: [HarnessToolDescriptor]private let appName: Stringprivate let appGuidance: String?+ /// One-shot understanding parsed before the loop: the restated goal, target app, parameters, and a+ /// 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?private let uptimeMS: @Sendable () -> Double/// Uptime (ms) at which the planner first chose an *action* tool (something that changes app@@ -38,17 +42,30 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {descriptors: [HarnessToolDescriptor],appName: String,appGuidance: String?,+ understanding: HarnessRequestUnderstanding? = nil,uptimeMS: @escaping @Sendable () -> Double = { ProcessInfo.processInfo.systemUptime * 1_000 }) {self.backend = backendself.descriptors = descriptorsself.appName = appNameself.appGuidance = appGuidance+ self.understanding = understandingself.uptimeMS = uptimeMSself.readOnlyToolNames = Set(descriptors.filter { $0.safetyClass == .readOnly }.map(\.name))}public func planNextStep(for task: HarnessTaskState) async -> HarnessToolCall? {+ // When the upfront understanding flagged the request as ambiguous, ask before doing anything.+ // Gated on a typed field (not raw text) and only on the first step, so a user answer resumes+ // into the normal planning loop. Reuses the harness's existing user.clarify waiting gate.+ if task.toolHistory.isEmpty,+ let understanding,+ understanding.needsClarification,+ let question = understanding.clarifyingQuestion,+ !question.isEmpty,+ descriptors.contains(where: { $0.name == "user.clarify" }) {+ return HarnessToolCall(name: "user.clarify", input: ["question": question])+ }let decision: Decisiondo {decision = try await decide(task: task)@@ -183,6 +200,28 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {)}+ /// 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.+ private func understandingBlock() -> String {+ guard let understanding else { return "" }+ var lines: [String] = []+ if let app = understanding.targetAppName, !app.isEmpty {+ lines.append(" Target app: \(app)")+ }+ if !understanding.parameters.isEmpty {+ let params = understanding.parameters.sorted { $0.key < $1.key }+ .map { "\($0.key)=\($0.value)" }+ .joined(separator: ", ")+ lines.append(" Parameters: \(params)")+ }+ if let criteria = understanding.successCriteria, !criteria.isEmpty {+ lines.append(" Success when: \(criteria)")+ }+ guard !lines.isEmpty else { return "" }+ return "WHAT THE USER WANTS:\n" + lines.joined(separator: "\n") + "\n"+ }+private func prompt(task: HarnessTaskState) -> String {let elements = task.worldModel.elementslet elementsBlock: String@@ -224,11 +263,18 @@ public final class HostedHarnessStepPlanner: HarnessNextStepPlanning {guidanceBlock = ""}+ // Prefer the restated goal parsed once up front; fall back to the raw task goal when no+ // understanding was produced.+ let restatedGoal = understanding?.restatedGoal+ let goalText = (restatedGoal?.isEmpty == false ? restatedGoal : nil) ?? task.goal+ 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.- GOAL: \(task.goal)-+ 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.+ GOAL: \(goalText)+ \(understandingBlock)\(historyBlock)\(factsBlock)\(guidanceBlock)\(elementsBlock)diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swiftnew file mode 100644index 00000000..a98af3e5--- /dev/null+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/HostedHarnessStepPlannerTests.swift@@ -0,0 +1,158 @@+import DonkeyAI+import DonkeyContracts+import DonkeyHarness+import Foundation+import Testing++@Suite+@MainActor+struct HostedHarnessStepPlannerTests {+ @Test+ func clarifyGateFiresOnFirstStepWhenUnderstandingNeedsClarification() async {+ // The HTTP client returns 500 so any model round-trip would fail the decode and yield+ // run.failSafe — proving the clarify result came from the deterministic gate, not the model.+ let planner = makePlanner(+ httpClient: FixtureHTTPClient(data: Data(), statusCode: 500),+ understanding: HarnessRequestUnderstanding(+ restatedGoal: "Delete the selected file",+ needsClarification: true,+ clarifyingQuestion: "Which file should I delete?"+ )+ )++ let call = await planner.planNextStep(for: task(goal: "delete it", toolHistory: []))++ #expect(call?.name == "user.clarify")+ #expect(call?.input["question"] == "Which file should I delete?")+ }++ @Test+ func clarifyGateDoesNotFireAfterTheFirstStep() async {+ // With history present the gate must not short-circuit; the model picks the next tool instead.+ let planner = makePlanner(+ httpClient: FixtureHTTPClient(data: cannedDecision(tool: "ax.observe"), statusCode: 200),+ understanding: HarnessRequestUnderstanding(+ restatedGoal: "Delete the selected file",+ needsClarification: true,+ clarifyingQuestion: "Which file should I delete?"+ )+ )++ let priorStep = HarnessToolCallRecord(+ call: HarnessToolCall(name: "ax.observe", input: [:]),+ resultStatus: .succeeded,+ summary: "Observed the window."+ )+ let call = await planner.planNextStep(for: task(goal: "delete it", toolHistory: [priorStep]))++ #expect(call?.name == "ax.observe")+ }++ @Test+ func promptUsesRestatedGoalAndRendersUnderstandingBlock() async {+ let httpClient = FixtureHTTPClient(data: cannedDecision(tool: "ax.observe"), statusCode: 200)+ let planner = makePlanner(+ httpClient: httpClient,+ understanding: HarnessRequestUnderstanding(+ restatedGoal: "Create a note titled Groceries",+ targetAppName: "Notes",+ parameters: ["title": "Groceries"],+ successCriteria: "a note titled Groceries exists"+ )+ )++ let call = await planner.planNextStep(for: task(goal: "raw untouched command", toolHistory: []))+ #expect(call?.name == "ax.observe")++ let body = requestBodyString(httpClient)+ #expect(body.contains("Create a note titled Groceries"))+ #expect(body.contains("WHAT THE USER WANTS"))+ #expect(body.contains("Target app: Notes"))+ #expect(body.contains("title=Groceries"))+ #expect(body.contains("a note titled Groceries exists"))+ // The restated goal replaces the raw command as the GOAL line.+ #expect(!body.contains("raw untouched command"))+ }++ @Test+ func promptFallsBackToRawGoalWhenNoUnderstanding() async {+ let httpClient = FixtureHTTPClient(data: cannedDecision(tool: "ax.observe"), statusCode: 200)+ let planner = makePlanner(httpClient: httpClient, understanding: nil)++ _ = await planner.planNextStep(for: task(goal: "open settings", toolHistory: []))++ let body = requestBodyString(httpClient)+ #expect(body.contains("open settings"))+ #expect(!body.contains("WHAT THE USER WANTS"))+ }++ // MARK: - Helpers++ private func makePlanner(+ httpClient: FixtureHTTPClient,+ understanding: HarnessRequestUnderstanding?+ ) -> HostedHarnessStepPlanner {+ HostedHarnessStepPlanner(+ backend: DonkeyBackendInferenceClient(+ configuration: DonkeyBackendInferenceConfiguration(+ baseURL: URL(string: "https://donkey.example")!,+ clientID: "client-1"+ ),+ httpClient: httpClient+ ),+ descriptors: [+ HarnessToolDescriptor(+ name: "user.clarify",+ pluginID: "core",+ summary: "Ask the user a question.",+ inputSchema: ["question": "The question to ask."],+ safetyClass: .readOnly+ ),+ HarnessToolDescriptor(+ name: "ax.observe",+ pluginID: "core",+ summary: "Read the accessibility tree.",+ safetyClass: .readOnly+ )+ ],+ appName: "Notes",+ appGuidance: nil,+ understanding: understanding+ )+ }++ private func task(goal: String, toolHistory: [HarnessToolCallRecord]) -> HarnessTaskState {+ HarnessTaskState(threadID: "thread-1", goal: goal, toolHistory: toolHistory)+ }++ private func cannedDecision(tool: String) -> Data {+ Data(#"{"output_text":"{\"tool\":\"\#(tool)\",\"reason\":\"step\"}"}"#.utf8)+ }++ private func requestBodyString(_ httpClient: FixtureHTTPClient) -> String {+ guard let body = httpClient.requests.first?.httpBody,+ let string = String(data: body, encoding: .utf8) else {+ return ""+ }+ return string+ }+}++private final class FixtureHTTPClient: AIHTTPClient, @unchecked Sendable {+ var data: Data+ var statusCode: Int+ var requests: [URLRequest] = []++ init(data: Data, statusCode: Int) {+ self.data = data+ self.statusCode = statusCode+ }++ func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {+ requests.append(request)+ return (+ data,+ HTTPURLResponse(url: request.url!, statusCode: statusCode, httpVersion: nil, headerFields: [:])!+ )+ }+}diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex 5644f2a9..4d91113a 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -78,6 +78,14 @@ LLM or another typed model/runtime boundary first. After that, deterministiccode may match typed fields such as tool names, app ids, schema values,permissions, filesystem paths, and Accessibility roles/actions.+A desktop turn is understood once before the per-step loop begins: a typed+understanding boundary restates the goal, names the target app, extracts the+request's parameters and success criteria, and decides whether to clarify. That+understanding selects which app the loop drives and is carried into every step so+the planner grounds against a stable goal instead of re-reading raw text each+step. Deterministic matching (e.g. clarify when the understanding flags it) keys+off those typed fields, never the raw command.+The app catalog is part of the model boundary. If a requested app or capabilityis not supported or is still refreshing, surface conversation, clarification,waiting, or failed-safe state rather than silently executing an unsupported