Open source CapCut alternative.
TypeScript
refactor(app): remove legacy intent-parsing adapter
David Ledbd1f126af3c
diff --git a/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift b/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swiftdeleted file mode 100644index 522fd3a6..00000000--- a/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift+++ /dev/null@@ -1,534 +0,0 @@-import DonkeyContracts-import DonkeyRuntime-import Foundation--public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {- public static let schemaID = "generic_harness_planning"-- public var router: AIModelRouter- public var configuration: DonkeyBackendInferenceConfiguration?- public var httpClient: any AIHTTPClient- public var environment: [String: String]-- public init(- router: AIModelRouter = AIModelRouter(registry: .defaultHybridPlanner),- configuration: DonkeyBackendInferenceConfiguration? = nil,- httpClient: any AIHTTPClient = URLSessionAIHTTPClient(),- environment: [String: String] = ProcessInfo.processInfo.environment- ) {- self.router = router- self.configuration = configuration- self.httpClient = httpClient- self.environment = environment- }-- public func parseTaskIntent(- _ request: TaskIntentAdapterRequest- ) async -> TaskIntentAdapterResult {- let entry: AIModelRegistryEntry- do {- entry = try router.route(request.routeRequest.limitingProviders([.donkeyBackend]))- } catch {- return result(- entry: nil,- request: request,- status: .invalidOutput,- validationStatus: "routingFailed",- latencyMS: nil,- metadata: ["error": String(describing: error)]- )- }-- let backend: DonkeyBackendInferenceClient- do {- backend = DonkeyBackendInferenceClient(- configuration: try configuration ?? DonkeyBackendInferenceConfiguration.fromEnvironment(environment),- httpClient: httpClient- )- } catch {- return result(- entry: entry,- request: request,- status: .missingCredentials,- validationStatus: "notValidated",- latencyMS: nil,- metadata: [- "credential": DonkeyBackendInferenceConfiguration.baseURLConfigurationDescription,- "error": String(describing: error)- ]- )- }-- let startedAt = ProcessInfo.processInfo.systemUptime- do {- let response = try await backend.createResponse(- responseRequest(entry: entry, adapterRequest: request)- )- let latencyMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000- guard let outputText = Self.outputText(from: response) else {- return result(- entry: entry,- request: request,- status: .invalidOutput,- validationStatus: "invalid",- latencyMS: latencyMS,- metadata: ["modelOutput.empty": "true"]- )- }-- var decodeFailureMetadata: [String: String] = [:]- do {- if let intent = try TaskIntentWireCodec.decodeHostedPlanningIntent(- outputText,- definitions: request.taskDefinitions,- originalCommand: request.command,- appFinderCatalog: request.appFinderCatalog,- sourceModelCallID: "model-call-\(request.sourceTraceID)",- parserName: "hosted-responses-v1",- parserSource: .onlineModel- ) {- return TaskIntentAdapterResult(- intent: intent,- trace: trace(- entry: entry,- request: request,- status: .completed,- validationStatus: "schemaDecoded",- latencyMS: latencyMS,- metadata: Self.outputDiagnostics(for: outputText).merging([- "provider": "donkeyBackend",- "privacy.store": "false"- ]) { current, _ in current }- )- )- }- } catch {- decodeFailureMetadata = Self.planningDecodeFailureMetadata(error)- }-- let baseMetadata = Self.outputDiagnostics(for: outputText)- .merging([- "provider": "donkeyBackend",- "privacy.store": "false"- ]) { current, _ in current }- .merging(decodeFailureMetadata) { current, _ in current }- if let noTaskMetadata = try? TaskIntentWireCodec.hostedPlanningNoTaskMetadata(- outputText,- parserName: "hosted-responses-v1"- ) {- return result(- entry: entry,- request: request,- status: .completed,- validationStatus: "noTaskIntent",- latencyMS: latencyMS,- metadata: baseMetadata.merging(noTaskMetadata) { _, new in new }- )- }-- if let repairSeed = try? TaskIntentWireCodec.hostedPlanningInvalidLocalTaskMetadata(- outputText,- parserName: "hosted-responses-v1"- ) {- return await repairHostedPlanningIntent(- entry: entry,- backend: backend,- request: request,- previousOutputText: outputText,- previousMetadata: baseMetadata.merging(repairSeed) { current, _ in current },- previousFailure: "The previous localAppTask JSON decoded but failed runtime validation, so it cannot be executed.",- startedAt: startedAt- )- }-- if !outputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {- return await repairHostedPlanningIntent(- entry: entry,- backend: backend,- request: request,- previousOutputText: outputText,- previousMetadata: baseMetadata.merging([- "reason": "hostedPlanningSchemaDecodeFailed",- "validation.failure": "hostedPlanningSchemaDecodeFailed",- "planner.repairable": "true"- ]) { current, _ in current },- previousFailure: "The previous planner output did not decode as the required generic_harness_planning schema, so it cannot be executed.",- startedAt: startedAt- )- }-- return result(- entry: entry,- request: request,- status: .invalidOutput,- validationStatus: "invalid",- latencyMS: latencyMS,- metadata: baseMetadata- )- } catch is CancellationError {- return result(entry: entry, request: request, status: .cancelled, validationStatus: "notValidated", latencyMS: nil)- } catch {- let latencyMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000- let status = Self.status(for: error)- return result(- entry: entry,- request: request,- status: status,- validationStatus: "notValidated",- latencyMS: latencyMS,- metadata: Self.errorMetadata(error)- )- }- }-- private static func planningDecodeFailureMetadata(_ error: Error) -> [String: String] {- [- "reason": "hostedPlanningSchemaDecodeFailed",- "detail": String(describing: error)- ]- }-- private func responseRequest(- entry: AIModelRegistryEntry,- adapterRequest: TaskIntentAdapterRequest,- repairContext: HostedPlanningRepairContext? = nil- ) -> RemoteInferenceResponseCreateRequest {- RemoteInferenceResponseCreateRequest(- input: .array([- .object([- "role": .string("user"),- "content": .array([- .object([- "type": .string("input_text"),- "text": .string(promptText(for: adapterRequest, repairContext: repairContext))- ])- ])- ])- ]),- store: false,- text: [- "format": .object([- "type": .string("json_schema"),- "name": .string(Self.schemaID),- "strict": .bool(true),- "schema": Self.jsonValue(TaskIntentWireCodec.genericHarnessPlanningJsonSchema(- taskDefinitions: adapterRequest.taskDefinitions,- availableToolNames: adapterRequest.availableToolNames- ))- ])- ],- metadata: [- "source_trace_id": adapterRequest.sourceTraceID,- "prompt_version": entry.promptVersion,- "repair_attempt": repairContext == nil ? "false" : "true"- ],- parameters: [- "instructions": .string(Self.instructions),- "temperature": .number(0)- ]- )- }-- private func promptText(- for request: TaskIntentAdapterRequest,- repairContext: HostedPlanningRepairContext? = nil- ) -> String {- let definitions = (try? JSONEncoder().encode(request.taskDefinitions))- .flatMap { String(data: $0, encoding: .utf8) } ?? "[]"- let appFinderCatalog = taskIntentAppFinderCatalogJSON(request.appFinderCatalog)- let skillGuidance = request.skillSnippets- .filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }- .prefix(8)- .joined(separator: "\n\n")- var sections = [- "Command: \(request.command)",- "Relevant local cache:",- request.contextSnippets.joined(separator: "\n"),- "Available harness tools:",- request.availableToolNames.joined(separator: "\n"),- "App skill guidance:",- skillGuidance,- "App finder catalog JSON:",- appFinderCatalog,- "Supported task definitions JSON:",- definitions- ]- if let repairContext {- sections.append(contentsOf: [- "Runtime validation feedback:",- repairContext.feedback,- "Previous invalid planner JSON:",- repairContext.previousOutputText- ])- }- return sections.joined(separator: "\n")- }-- private func repairHostedPlanningIntent(- entry: AIModelRegistryEntry,- backend: DonkeyBackendInferenceClient,- request: TaskIntentAdapterRequest,- previousOutputText: String,- previousMetadata: [String: String],- previousFailure: String,- startedAt: TimeInterval- ) async -> TaskIntentAdapterResult {- do {- let response = try await backend.createResponse(- responseRequest(- entry: entry,- adapterRequest: request,- repairContext: HostedPlanningRepairContext(- previousOutputText: previousOutputText,- previousFailure: previousFailure- )- )- )- let latencyMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000- guard let repairOutputText = Self.outputText(from: response) else {- return result(- entry: entry,- request: request,- status: .invalidOutput,- validationStatus: "invalid",- latencyMS: latencyMS,- metadata: Self.repairMetadata(- previousMetadata: previousMetadata,- repairOutputText: nil,- status: "empty"- )- )- }-- return decodeOutputText(- repairOutputText,- entry: entry,- request: request,- latencyMS: latencyMS,- modelCallIDSuffix: "-repair",- metadataBuilder: { status in- Self.repairMetadata(- previousMetadata: previousMetadata,- repairOutputText: repairOutputText,- status: status- )- }- )- } catch is CancellationError {- return result(entry: entry, request: request, status: .cancelled, validationStatus: "notValidated", latencyMS: nil)- } catch {- let latencyMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000- return result(- entry: entry,- request: request,- status: Self.status(for: error),- validationStatus: "notValidated",- latencyMS: latencyMS,- metadata: Self.repairMetadata(- previousMetadata: previousMetadata,- repairOutputText: nil,- status: "requestFailed"- ).merging(Self.errorMetadata(error)) { current, _ in current }- )- }- }-- private func decodeOutputText(- _ outputText: String,- entry: AIModelRegistryEntry,- request: TaskIntentAdapterRequest,- latencyMS: Double,- modelCallIDSuffix: String = "",- metadataBuilder: (String) -> [String: String]- ) -> TaskIntentAdapterResult {- var decodeFailureMetadata: [String: String] = [:]- do {- if let intent = try TaskIntentWireCodec.decodeHostedPlanningIntent(- outputText,- definitions: request.taskDefinitions,- originalCommand: request.command,- appFinderCatalog: request.appFinderCatalog,- sourceModelCallID: "model-call-\(request.sourceTraceID)\(modelCallIDSuffix)",- parserName: "hosted-responses-v1",- parserSource: .onlineModel- ) {- return TaskIntentAdapterResult(- intent: intent,- trace: trace(- entry: entry,- request: request,- status: .completed,- validationStatus: "schemaDecoded",- latencyMS: latencyMS,- metadata: metadataBuilder("schemaDecoded")- )- )- }- } catch {- decodeFailureMetadata = Self.planningDecodeFailureMetadata(error)- }-- if let noTaskMetadata = try? TaskIntentWireCodec.hostedPlanningNoTaskMetadata(- outputText,- parserName: "hosted-responses-v1"- ) {- return result(- entry: entry,- request: request,- status: .completed,- validationStatus: "noTaskIntent",- latencyMS: latencyMS,- metadata: metadataBuilder("noTaskIntent").merging(noTaskMetadata) { _, new in new }- )- }-- return result(- entry: entry,- request: request,- status: .invalidOutput,- validationStatus: "invalid",- latencyMS: latencyMS,- metadata: metadataBuilder("invalid").merging(decodeFailureMetadata) { current, _ in current }- )- }-- private static let instructions = [- "You are the first model boundary for Donkey's generic agent harness: decide how the harness should handle the user turn before any tool-specific executor is selected. Fill every field per the schema and its field descriptions.",- "Donkey is a capable Mac agent that can operate any application and item on the Mac. Default to acting: be broad in what you accept and specific in what you do, and prefer acting via a tool path over clarification whenever the action is safe and reversible. For an under-specified but low-risk, reversible request, resolve the vagueness yourself with concrete, reasonable specifics and proceed — use loaded app skill guidance to choose (for example a representative song for \"play some coldplay\") — rather than asking for details you can sensibly decide.",- "Apply App skill guidance for app-specific workflows, control strategies, required metadata, and output shapes. Do not invent task types, entities, tools, app scripts, or app-specific behavior absent from task definitions, catalog data, memory, or loaded skill guidance. If no supported capability fits, use route conversation with a helpful assistantResponse rather than a generic local-action failure.",- "Build planSteps as the generic harness plan: each executable step names one available toolName with toolInputs filled from structured entities and the tool schema; non-executable reasoning steps use an empty toolName. Only localAppTask carries executable steps.",- "For local_app_interaction, prefer a loaded app skill's validated script (skill.load then skill.script.execute with structured toolInputs) over repeated screenshot-driven keyboard fallback.",- "When automation.applescript.generate is available and a supported app action is better handled through AppleScript than UI input, use it only for a small doable target-app operation, not a full pipeline. Plan separate steps — automation.applescript.generate, automation.applescript.validate, automation.applescript.execute, then app.observe and an app.verifyCommand or app.verifyVisibleText step — reusing one stable toolInputs.scriptArtifactID across generate/validate/execute. The generate step includes targetApp, bundleIdentifier when known, goal, entities as JSON text, allowedActions, and verification. Never put script source in planner output. If AppleScript is not clearly doable, use observation, Accessibility, screenshot, or UI tools instead.",- "Use ui.clickTarget (semantic or observed visual target id in controlID) to click or submit a visible control instead of pressing Return. When ui.setText is present, entities.query and normalizedEntities.query must be non-empty and inputEntity is usually query. Use agent.path.visualize only with grounded app/window/control/action evidence for every waypoint; it is visual-only (describe the AI path with stepsJSON) and never replaces real AX, AppleScript, keyboard, or guarded coordinate actions.",- "Verification may be several verifier steps: app.verifyCommand for guarded command evidence, app.verifyVisibleText for observed result text; include both when both kinds of evidence are needed."- ].joined(separator: " ")-- private static func repairMetadata(- previousMetadata: [String: String],- repairOutputText: String?,- status: String- ) -> [String: String] {- var metadata = previousMetadata.merging([- "provider": "donkeyBackend",- "privacy.store": "false",- "planner.repairAttempted": "true",- "planner.repairStatus": status- ]) { _, new in new }- if let repairOutputText {- let repairDiagnostics = Dictionary(- uniqueKeysWithValues: Self.outputDiagnostics(for: repairOutputText).map {- ("repair.\($0.key)", $0.value)- }- )- metadata = metadata.merging(repairDiagnostics) { _, new in new }- } else {- metadata["repair.modelOutput.empty"] = "true"- }- return metadata- }-- private static func outputDiagnostics(for outputText: String) -> [String: String] {- let trimmed = outputText.trimmingCharacters(in: .whitespacesAndNewlines)- guard !trimmed.isEmpty else {- return ["modelOutput.empty": "true"]- }- return [- "modelOutput.empty": "false",- "modelOutput.preview": preview(trimmed, maxCharacters: 240)- ]- }-- private static func outputText(from value: RemoteInferenceJSONValue) -> String? {- RemoteInferenceResponseHelpers.outputText(from: value)- }-- private static func status(for error: Error) -> AIModelCallStatus {- if case DonkeyBackendInferenceClientError.httpStatus(let status, _) = error {- if status == 429 { return .rateLimited }- if status >= 500 { return .providerOutage }- return .invalidOutput- }- return (error as NSError).code == NSURLErrorTimedOut ? .timeout : .providerOutage- }-- private static func errorMetadata(_ error: Error) -> [String: String] {- if case DonkeyBackendInferenceClientError.httpStatus(let status, let message) = error {- return [- "http.status": String(status),- "http.bodyPreview": preview(message, maxCharacters: 240)- ]- }- return ["error": String(describing: error)]- }-- private static func preview(_ value: String, maxCharacters: Int) -> String {- let singleLine = value- .replacingOccurrences(of: "\n", with: "\\n")- .replacingOccurrences(of: "\r", with: "\\r")- guard singleLine.count > maxCharacters else { return singleLine }- return String(singleLine.prefix(maxCharacters))- }-- private static func jsonValue(_ value: Any) -> RemoteInferenceJSONValue {- RemoteInferenceResponseHelpers.jsonValue(value)- }-- private func result(- entry: AIModelRegistryEntry?,- request: TaskIntentAdapterRequest,- status: AIModelCallStatus,- validationStatus: String,- latencyMS: Double?,- metadata: [String: String] = [:]- ) -> TaskIntentAdapterResult {- TaskIntentAdapterResult(- intent: nil,- trace: trace(- entry: entry,- request: request,- status: status,- validationStatus: validationStatus,- latencyMS: latencyMS,- metadata: metadata- )- )- }-- private func trace(- entry: AIModelRegistryEntry?,- request: TaskIntentAdapterRequest,- status: AIModelCallStatus,- validationStatus: String,- latencyMS: Double?,- metadata: [String: String] = [:]- ) -> AIModelCallTrace {- AIModelCallTrace(- id: "model-call-\(request.sourceTraceID)",- role: entry?.role ?? .taskIntent,- provider: entry?.provider ?? .donkeyBackend,- modelID: entry?.modelID ?? "unrouted",- promptVersion: entry?.promptVersion ?? "unrouted",- schemaID: Self.schemaID,- latencyMS: latencyMS,- timeoutMS: entry?.timeoutMS ?? 0,- status: status,- validationStatus: validationStatus,- sourceTraceID: request.sourceTraceID,- metadata: metadata- )- }-}--private struct HostedPlanningRepairContext {- var previousOutputText: String- var previousFailure: String-- var feedback: String {- [- previousFailure,- "Return one corrected strict JSON object using the same schema.",- "If no supported executable action is possible, return a conversation or clarification route.",- "Use the relevant app skill and catalog metadata to repair app-specific workflow fields instead of inventing unsupported behavior."- ].joined(separator: " ")- }-}diff --git a/apps/Donkey/Sources/DonkeyAI/LocalModelPriorityWorker.swift b/apps/Donkey/Sources/DonkeyAI/LocalModelPriorityWorker.swiftindex 8f9b1348..fc704bba 100644--- a/apps/Donkey/Sources/DonkeyAI/LocalModelPriorityWorker.swift+++ b/apps/Donkey/Sources/DonkeyAI/LocalModelPriorityWorker.swift@@ -193,32 +193,3 @@ public actor LocalModelPriorityWorker {public enum LocalModelWorkScheduling {public static let shared = LocalModelPriorityWorker()}--public struct PriorityQueuedTaskIntentParsingAdapter: TaskIntentParsingAdapter {- public var base: any TaskIntentParsingAdapter- public var worker: LocalModelPriorityWorker-- public init(- base: any TaskIntentParsingAdapter,- worker: LocalModelPriorityWorker = LocalModelWorkScheduling.shared- ) {- self.base = base- self.worker = worker- }-- public func parseTaskIntent(_ request: TaskIntentAdapterRequest) async -> TaskIntentAdapterResult {- let priority: LocalModelWorkPriority = request.routeRequest.latencyTolerance == .interactive- ? .userInteractive- : .plannerHint- return await worker.submit(- kind: .taskIntent,- priority: priority,- metadata: [- "sourceTraceID": request.sourceTraceID,- "latencyTolerance": request.routeRequest.latencyTolerance.rawValue- ]- ) {- await base.parseTaskIntent(request)- }- }-}diff --git a/apps/Donkey/Sources/DonkeyAI/TaskIntentParsingAdapter.swift b/apps/Donkey/Sources/DonkeyAI/TaskIntentParsingAdapter.swiftdeleted file mode 100644index 5d8f8657..00000000--- a/apps/Donkey/Sources/DonkeyAI/TaskIntentParsingAdapter.swift+++ /dev/null@@ -1,119 +0,0 @@-import DonkeyContracts-import DonkeyRuntime-import Foundation--public struct TaskIntentAdapterRequest: Equatable, Sendable {- public var command: String- public var taskDefinitions: [LocalAppTaskDefinition]- public var contextSnippets: [String]- public var skillSnippets: [String]- public var appFinderCatalog: [LocalAppFinderCatalogEntry]- public var availableToolNames: [String]- public var sourceTraceID: String- public var routeRequest: AIModelRouteRequest-- public init(- command: String,- taskDefinitions: [LocalAppTaskDefinition],- contextSnippets: [String] = [],- skillSnippets: [String]? = nil,- appFinderCatalog: [LocalAppFinderCatalogEntry] = [],- availableToolNames: [String] = [],- sourceTraceID: String,- routeRequest: AIModelRouteRequest = AIModelRouteRequest(- jobType: .taskIntent,- privacyMode: .privacySensitive,- latencyTolerance: .interactive- )- ) {- self.command = command- self.taskDefinitions = taskDefinitions- self.contextSnippets = TaskIntentModelContextCompactor.compact(contextSnippets)- self.appFinderCatalog = appFinderCatalog- self.availableToolNames = availableToolNames- // Budget allows a compact discovery catalog plus ONE full skill body (the top match), so the- // chosen skill's concrete execution steps are not truncated. See LocalAppTaskSkillContext.- self.skillSnippets = TaskIntentModelContextCompactor(- maxSnippets: 8,- maxSnippetCharacters: 4_200,- maxTotalCharacters: 9_000- ).compact(- skillSnippets ?? LocalAppTaskSkillContext.defaultContext(- command: command,- taskDefinitions: taskDefinitions,- appFinderCatalog: appFinderCatalog- ).snippets- )- self.sourceTraceID = sourceTraceID- self.routeRequest = routeRequest- }-}--public struct TaskIntentModelContextCompactor: Equatable, Sendable {- public var maxSnippets: Int- public var maxSnippetCharacters: Int- public var maxTotalCharacters: Int-- public init(- maxSnippets: Int = 8,- maxSnippetCharacters: Int = 1_200,- maxTotalCharacters: Int = 4_800- ) {- self.maxSnippets = max(0, maxSnippets)- self.maxSnippetCharacters = max(80, maxSnippetCharacters)- self.maxTotalCharacters = max(80, maxTotalCharacters)- }-- public func compact(_ snippets: [String]) -> [String] {- var usedCharacters = 0- var compacted: [String] = []-- for snippet in snippets.prefix(maxSnippets) {- let trimmed = snippet.trimmingCharacters(in: .whitespacesAndNewlines)- guard !trimmed.isEmpty else { continue }-- let boundedSnippet = bounded(trimmed, maxCharacters: maxSnippetCharacters)- let remainingCharacters = maxTotalCharacters - usedCharacters- guard remainingCharacters > 0 else { break }-- let totalBoundedSnippet = bounded(boundedSnippet, maxCharacters: remainingCharacters)- usedCharacters += totalBoundedSnippet.count- compacted.append(totalBoundedSnippet)- }-- return compacted- }-- public static func compact(_ snippets: [String]) -> [String] {- TaskIntentModelContextCompactor().compact(snippets)- }-- private func bounded(_ value: String, maxCharacters: Int) -> String {- guard value.count > maxCharacters else { return value }- let marker = "\n...[compacted]...\n"- guard maxCharacters > marker.count + 2 else {- return String(value.suffix(maxCharacters))- }-- let contentCharacters = maxCharacters - marker.count- let prefixCharacters = contentCharacters / 2- let suffixCharacters = contentCharacters - prefixCharacters- let prefixEnd = value.index(value.startIndex, offsetBy: prefixCharacters)- let suffixStart = value.index(value.endIndex, offsetBy: -suffixCharacters)- return String(value[..<prefixEnd]) + marker + String(value[suffixStart...])- }-}--public struct TaskIntentAdapterResult: Equatable, Sendable {- public var intent: TaskIntent?- public var trace: AIModelCallTrace-- public init(intent: TaskIntent?, trace: AIModelCallTrace) {- self.intent = intent- self.trace = trace- }-}--public protocol TaskIntentParsingAdapter: Sendable {- func parseTaskIntent(_ request: TaskIntentAdapterRequest) async -> TaskIntentAdapterResult-}diff --git a/apps/Donkey/Sources/DonkeyAI/TaskIntentWireCodec.swift b/apps/Donkey/Sources/DonkeyAI/TaskIntentWireCodec.swiftdeleted file mode 100644index fdb60902..00000000--- a/apps/Donkey/Sources/DonkeyAI/TaskIntentWireCodec.swift+++ /dev/null@@ -1,1161 +0,0 @@-import DonkeyContracts-import DonkeyRuntime-import Foundation--func taskIntentAppFinderCatalogJSON(_ entries: [LocalAppFinderCatalogEntry]) -> String {- let compactEntries = entries.map { entry -> [String: Any] in- var value: [String: Any] = [- "appID": entry.appID,- "appName": entry.appName,- "description": entry.description,- "supportStatus": entry.supportStatus.rawValue- ]- if let bundleIdentifier = entry.bundleIdentifier, !bundleIdentifier.isEmpty {- value["bundleIdentifier"] = bundleIdentifier- }- if entry.capabilities.isEmpty == false {- value["capabilities"] = entry.capabilities.map { capability -> [String: Any] in- [- "id": capability.id,- "summary": capability.summary,- "controlProfiles": capability.controlProfiles,- "requiredEntities": capability.requiredEntities- ]- }- }- if let denyReason = entry.denyReason, !denyReason.isEmpty {- value["denyReason"] = denyReason- }- return value- }- guard compactEntries.isEmpty == false,- let data = try? JSONSerialization.data(withJSONObject: compactEntries),- let text = String(data: data, encoding: .utf8)- else {- return "[]"- }- return text-}--enum TaskIntentWireCodec {- static let defaultConversationAssistantResponse = "I'm here. What would you like to work on?"-- static func jsonSchema(taskDefinitions: [LocalAppTaskDefinition]) -> [String: Any] {- let allowsDynamicTargets = taskDefinitions.contains { definition in- definition.metadata["dynamicTarget"] == "true"- }- let targetAppNameSchema: [String: Any] = allowsDynamicTargets- ? ["type": "string"]- : ["type": "string", "enum": (Array(Set(taskDefinitions.map(\.targetApp.appName))) + ["none"]).sorted()]- let actionPlanSchema: [String: Any] = [- "type": "object",- "additionalProperties": false,- "required": [- "tools",- "inputEntity",- "controlID",- "focusKey",- "verificationTools"- ],- "properties": [- "tools": [- "type": "array",- "maxItems": 8,- "items": [- "type": "string",- "enum": LocalAppActionPlanTool.allCases.map(\.rawValue)- ]- ],- "inputEntity": ["type": "string"],- "controlID": ["type": "string"],- "focusKey": ["type": "string"],- "verificationTools": [- "type": "array",- "maxItems": 4,- "items": [- "type": "string",- "enum": [- LocalAppActionPlanTool.verifyCommand.rawValue,- LocalAppActionPlanTool.verifyVisibleText.rawValue- ]- ]- ]- ]- ]-- return [- "type": "object",- "additionalProperties": false,- "required": [- "taskType",- "targetAppName",- "entities",- "normalizedEntities",- "confidence",- "needsConfirmation",- "actionPlan",- "metadata"- ],- "properties": [- "taskType": ["type": "string", "enum": (Array(Set(taskDefinitions.map(\.taskType))) + ["none"]).sorted()],- "targetAppName": targetAppNameSchema,- "entities": [- "type": "object",- "additionalProperties": ["type": "string"]- ],- "normalizedEntities": [- "type": "object",- "additionalProperties": ["type": "string"]- ],- "confidence": ["type": "number", "minimum": 0, "maximum": 1],- "needsConfirmation": [- "type": "boolean",- "description": "Set true ONLY when the action is destructive, irreversible, costly, or sent/shared externally AND its intent is ambiguous. Set false for safe, reversible actions — including broad or casual requests you resolved by choosing concrete specifics yourself (e.g. playing a representative song). Do not set true just because a request was casual or under-specified."- ],- "actionPlan": actionPlanSchema,- "metadata": [- "type": "object",- "additionalProperties": ["type": "string"]- ]- ]- ]- }-- static func genericHarnessPlanningJsonSchema(- taskDefinitions: [LocalAppTaskDefinition],- availableToolNames: [String] = []- ) -> [String: Any] {- let allowsDynamicTargets = taskDefinitions.contains { definition in- definition.metadata["dynamicTarget"] == "true"- }- let taskTypes = (Array(Set(taskDefinitions.map(\.taskType))) + ["none"]).sorted()- let appNames = (Array(Set(taskDefinitions.map(\.targetApp.appName))) + ["none"]).sorted()- let targetAppNameSchema: [String: Any] = allowsDynamicTargets- ? ["type": "string"]- : ["type": "string", "enum": appNames]- let availableToolNameSet = Set(- availableToolNames- .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }- .filter { !$0.isEmpty }- )- let toolNames = [""] + Array(- availableToolNameSet.isEmpty- ? Set(LocalAppActionPlanTool.allCases.map(\.rawValue))- : availableToolNameSet- ).sorted()- let planStepSchema: [String: Any] = [- "type": "object",- "additionalProperties": false,- "required": [- "id",- "summary",- "toolName",- "inputEntity",- "controlID",- "focusKey",- "toolInputs",- "expectedObservation"- ],- "properties": [- "id": ["type": "string"],- "summary": ["type": "string"],- "toolName": [- "type": "string",- "enum": toolNames,- "description": "One available tool name for an executable step; empty string for a non-executable reasoning step."- ],- "inputEntity": [- "type": "string",- "description": "Entity key feeding this step (usually query when text is entered); empty when unused."- ],- "controlID": [- "type": "string",- "description": "Semantic or observed visual target id for click/submit tools; empty when unused."- ],- "focusKey": ["type": "string"],- "toolInputs": [- "type": "object",- "additionalProperties": ["type": "string"],- "description": "Inputs for the tool, filled from structured entities and the tool's schema."- ],- "expectedObservation": [- "type": "string",- "description": "What the harness should observe after this step."- ]- ]- ]-- return [- "type": "object",- "additionalProperties": false,- "required": [- "structuredIntent",- "ambiguityRisk",- "contextNeeds",- "planSteps",- "verificationCriteria",- "fallbacks",- "clarificationPolicy",- "metadata"- ],- "properties": [- "structuredIntent": [- "type": "object",- "additionalProperties": false,- "required": [- "route",- "taskType",- "needsConfirmation"- ],- "properties": [- "route": [- "type": "string",- "enum": ["localAppTask", "conversation", "clarification", "guidance"],- "description": "How the harness should handle the turn. localAppTask: operate a local app or item — the default for any safe, identifiable action, including broad or casual ones you resolve by choosing concrete specifics. conversation: greetings, questions, explanations, status, malformed input, or any turn needing no external action. guidance: SHOW where something is or how to do it without changing any state. clarification: only when acting would be destructive, irreversible, costly, or sent/shared externally AND intent is genuinely ambiguous, or a required target is unknown and cannot be inferred."- ],- "goal": [- "type": "string",- "description": "Concise restatement of what the user wants."- ],- "taskType": [- "type": "string",- "enum": taskTypes,- "description": "Provided task type to execute, or \"none\" for conversation, guidance, or clarification. Use local_app_interaction for an executable local-app request that needs a model-planned workflow and has no more specific provided task type."- ],- "targetAppName": targetAppNameSchema,- "entities": [- "type": "object",- "additionalProperties": ["type": "string"],- "description": "Concrete values required by the task's entity rules. For local_app_interaction set appName (human app name) and goal, plus query when text must be entered."- ],- "normalizedEntities": [- "type": "object",- "additionalProperties": ["type": "string"],- "description": "Normalized form of entities; mirror query here when text input is needed."- ],- "confidence": ["type": "number", "minimum": 0, "maximum": 1],- "needsConfirmation": [- "type": "boolean",- "description": "Set true ONLY when the action is destructive, irreversible, costly, or sent/shared externally AND its intent is ambiguous. Set false for safe, reversible actions — including broad or casual requests you resolved by choosing concrete specifics yourself (e.g. playing a representative song). Do not set true just because a request was casual or under-specified."- ]- ]- ],- "ambiguityRisk": [- "type": "object",- "additionalProperties": false,- "required": [- "ambiguityClass",- "riskLevel",- "missingInformation",- "shouldAskBeforeActing"- ],- "properties": [- "ambiguityClass": [- "type": "string",- "enum": ["safe", "recoverable", "dangerous"]- ],- "riskLevel": [- "type": "string",- "enum": ["low", "medium", "high"]- ],- "missingInformation": [- "type": "array",- "maxItems": 8,- "items": ["type": "string"]- ],- "shouldAskBeforeActing": [- "type": "boolean",- "description": "True only for dangerous, destructive, irreversible, costly, or externally-sent actions whose intent is ambiguous; false for safe, reversible actions, including broad or casual ones."- ]- ]- ],- "contextNeeds": [- "type": "array",- "maxItems": 8,- "items": ["type": "string"],- "description": "Lookups needed before or during execution: app lookup, memory lookup, screen observation, element discovery, or skill lookup."- ],- "planSteps": [- "type": "array",- "maxItems": 12,- "items": planStepSchema,- "description": "Generic harness plan. Empty for conversation, guidance, and clarification — those routes carry no executable steps."- ],- "verificationCriteria": [- "type": "array",- "maxItems": 8,- "items": ["type": "string"],- "description": "What proves the task succeeded."- ],- "fallbacks": [- "type": "array",- "maxItems": 8,- "items": ["type": "string"],- "description": "Safe recovery choices if the primary plan fails."- ],- "clarificationPolicy": [- "type": "object",- "additionalProperties": false,- "required": [- "shouldAsk",- "questions",- "policy"- ],- "properties": [- "shouldAsk": [- "type": "boolean",- "description": "True only when route is clarification."- ],- "questions": [- "type": "array",- "maxItems": 4,- "items": ["type": "string"],- "description": "When asking, exactly one specific question naming what you need; otherwise empty."- ],- "policy": ["type": "string"]- ]- ],- "metadata": [- "type": "object",- "additionalProperties": ["type": "string"],- "description": "Free-form string map. conversation: set responseMode=\"conversation\" and assistantResponse=<brief natural-language reply>. guidance: set assistantResponse=<brief spoken narration> and guidanceTargets=<JSON array of {\"label\":\"...\",\"query\":\"...\"} controls to point at, in order; label is shown to the user, query is the control's on-screen text>. local_app_interaction with a non-empty app finder catalog: set appFinder.selectedAppID, appFinder.selectedCapabilityID, and appFinder.controlProfile from a catalog entry whose supportStatus is supported (never candidate, unsupported, or denied)."- ]- ]- ]- }-- static func decodeIntent(- _ outputText: String,- definitions: [LocalAppTaskDefinition],- originalCommand: String,- appFinderCatalog: [LocalAppFinderCatalogEntry] = [],- sourceModelCallID: String,- parserName: String,- parserSource: TaskIntentParserSource = .localModel- ) throws -> TaskIntent? {- let wire = try decodeWire(from: outputText)- return try decodeIntent(- from: wire,- definitions: definitions,- originalCommand: originalCommand,- appFinderCatalog: appFinderCatalog,- sourceModelCallID: sourceModelCallID,- parserName: parserName,- parserSource: parserSource- )- }-- static func decodeHostedPlanningIntent(- _ outputText: String,- definitions: [LocalAppTaskDefinition],- originalCommand: String,- appFinderCatalog: [LocalAppFinderCatalogEntry] = [],- sourceModelCallID: String,- parserName: String,- parserSource: TaskIntentParserSource- ) throws -> TaskIntent? {- let planningWire = try decodeHostedPlanningWire(from: outputText)- guard planningWire.structuredIntent.route == "localAppTask",- planningWire.structuredIntent.taskType != "none"- else {- return nil- }-- let wire = TaskIntentWire(- taskType: planningWire.structuredIntent.taskType,- targetAppName: planningWire.structuredIntent.targetAppName,- entities: planningWire.structuredIntent.entities,- normalizedEntities: planningWire.structuredIntent.normalizedEntities,- confidence: planningWire.structuredIntent.confidence,- needsConfirmation: planningWire.structuredIntent.needsConfirmation- || planningWire.ambiguityRisk.shouldAskBeforeActing- || planningWire.clarificationPolicy.shouldAsk,- actionPlan: actionPlan(from: planningWire),- metadata: hostedPlanningMetadata(from: planningWire)- )- return try decodeIntent(- from: wire,- definitions: definitions,- originalCommand: originalCommand,- appFinderCatalog: appFinderCatalog,- sourceModelCallID: sourceModelCallID,- parserName: parserName,- parserSource: parserSource- )- }-- private static func decodeIntent(- from wire: TaskIntentWire,- definitions: [LocalAppTaskDefinition],- originalCommand: String,- appFinderCatalog: [LocalAppFinderCatalogEntry],- sourceModelCallID: String,- parserName: String,- parserSource: TaskIntentParserSource- ) throws -> TaskIntent? {- if wire.taskType == "none" {- return nil- }- let exactDefinition = definitions.first(where: {- $0.taskType == wire.taskType && $0.targetApp.appName == wire.targetAppName- })- let dynamicDefinition = definitions.first(where: {- $0.taskType == wire.taskType && $0.metadata["dynamicTarget"] == "true"- })- guard let definition = exactDefinition ?? dynamicDefinition else {- return nil- }- guard definition.metadata["modelPlanned"] == "true" || wire.actionPlan.tools.isEmpty else {- return nil- }-- var entities = wire.entities- var normalizedEntities = normalizedEntities(from: wire, definition: definition)- if definition.metadata["dynamicTarget"] == "true",- normalizedEntities["appName"] == nil,- let appName = dynamicAppName(from: wire, definition: definition) {- entities["appName"] = appName- normalizedEntities["appName"] = appName- }- var metadata = wire.metadata.merging(definition.metadata) { current, _ in current }- metadata["parser"] = parserName-- let appFinderSelection = validatedAppFinderSelection(- wire: wire,- definition: definition,- appFinderCatalog: appFinderCatalog- )- if definition.metadata["modelPlanned"] == "true",- appFinderCatalog.isEmpty == false,- appFinderSelection == nil {- return nil- }- if let appFinderSelection {- entities["appName"] = appFinderSelection.entry.appName- normalizedEntities["appName"] = appFinderSelection.entry.appName- metadata["appFinder.selectedAppID"] = appFinderSelection.entry.appID- metadata["appFinder.selectedCapabilityID"] = appFinderSelection.capability.id- metadata["appFinder.controlProfile"] = appFinderSelection.controlProfile- metadata["appFinder.supportStatus"] = appFinderSelection.entry.supportStatus.rawValue- metadata["appFinder.validated"] = "true"- }-- let missingRequiredEntity = definition.entityRules.first { rule in- rule.required && normalizedEntities[rule.name] == nil- }- if definition.metadata["dynamicTarget"] == "true" {- metadata["requestedItemName"] = normalizedEntities["appName"] ?? entities["appName"] ?? ""- }- if let missingRequiredEntity {- metadata["missingEntity"] = missingRequiredEntity.name- }-- let confidence = wire.confidence- let needsConfirmation = wire.needsConfirmation || missingRequiredEntity != nil- let hasGenericExecutablePlan = metadata["genericHarness.planStepsJSON"]- .map(Self.hasGenericExecutableTool) ?? false- let actionPlan = wire.actionPlan.tools.isEmpty && !hasGenericExecutablePlan- ? nil- : wire.actionPlan- let primaryEntity = definition.verificationEntityName- .flatMap { normalizedEntities[$0] }- ?? normalizedEntities.values.sorted().first- ?? definition.taskType-- return TaskIntent(- intentID: needsConfirmation- ? "\(definition.taskType)-needs-\(missingRequiredEntity?.name ?? "confirmation")"- : "\(definition.taskType)-\(slug(primaryEntity))",- taskType: definition.taskType,- targetApp: targetApp(from: wire, definition: definition, appFinderEntry: appFinderSelection?.entry),- entities: entities,- normalizedEntities: normalizedEntities,- confidence: confidence,- parserSource: parserSource,- needsConfirmation: needsConfirmation,- sourceModelCallID: sourceModelCallID,- actionPlan: actionPlan,- metadata: metadata- )- }-- static func hostedPlanningNoTaskMetadata(- _ outputText: String,- parserName: String- ) throws -> [String: String]? {- let wire = try decodeHostedPlanningWire(from: outputText)- guard wire.structuredIntent.route != "localAppTask"- || wire.structuredIntent.taskType == "none"- else {- return nil- }-- var metadata = hostedPlanningMetadata(from: wire)- metadata["parser"] = parserName- let route = wire.structuredIntent.route- if route == "clarification" || wire.clarificationPolicy.shouldAsk {- metadata["reason"] = nonEmpty(metadata["reason"]) ?? "clarificationRequired"- metadata["responseMode"] = "clarification"- metadata["assistantResponse"] = nonEmpty(metadata["assistantResponse"])- ?? wire.clarificationPolicy.questions.first(where: { nonEmpty($0) != nil })- ?? defaultConversationAssistantResponse- } else {- metadata["reason"] = nonEmpty(metadata["reason"]) ?? "noSupportedTaskIntent"- metadata["responseMode"] = "conversation"- metadata["assistantResponse"] = nonEmpty(metadata["assistantResponse"])- ?? defaultConversationAssistantResponse- }- metadata["taskType"] = "none"- metadata["targetApp"] = wire.structuredIntent.targetAppName- return metadata- }-- static func hostedPlanningInvalidLocalTaskMetadata(- _ outputText: String,- parserName: String- ) throws -> [String: String]? {- let wire = try decodeHostedPlanningWire(from: outputText)- guard wire.structuredIntent.route == "localAppTask",- wire.structuredIntent.taskType != "none"- else {- return nil- }-- var metadata = hostedPlanningMetadata(from: wire)- metadata["parser"] = parserName- metadata["reason"] = nonEmpty(metadata["reason"]) ?? "localAppTaskValidationFailed"- metadata["validation.failure"] = "localAppTaskValidationFailed"- metadata["taskType"] = wire.structuredIntent.taskType- metadata["targetApp"] = wire.structuredIntent.targetAppName- metadata["planner.repairable"] = "true"- return metadata- }-- static func noTaskMetadata(- _ outputText: String,- parserName: String- ) throws -> [String: String]? {- let wire = try decodeWire(from: outputText)- guard wire.taskType == "none" else { return nil }-- var metadata = wire.metadata- metadata["parser"] = parserName- metadata["reason"] = nonEmpty(metadata["reason"]) ?? "noSupportedTaskIntent"- metadata["responseMode"] = "conversation"- metadata["assistantResponse"] = nonEmpty(metadata["assistantResponse"])- ?? defaultConversationAssistantResponse- metadata["taskType"] = "none"- metadata["targetApp"] = wire.targetAppName- return metadata- }-- private static func decodeWire(from outputText: String) throws -> TaskIntentWire {- var lastError: Error?- for candidate in jsonObjectCandidates(in: outputText) {- do {- return try JSONDecoder().decode(TaskIntentWire.self, from: Data(candidate.utf8))- } catch {- lastError = error- }- }-- if let lastError {- throw lastError- }- throw DecodingError.dataCorrupted(- DecodingError.Context(- codingPath: [],- debugDescription: "No JSON object found in task intent model output"- )- )- }-- private static func decodeHostedPlanningWire(from outputText: String) throws -> GenericHarnessPlanningWire {- var lastError: Error?- for candidate in jsonObjectCandidates(in: outputText) {- do {- return try JSONDecoder().decode(GenericHarnessPlanningWire.self, from: Data(candidate.utf8))- } catch {- lastError = error- }- }-- if let lastError {- throw lastError- }- throw DecodingError.dataCorrupted(- DecodingError.Context(- codingPath: [],- debugDescription: "No JSON object found in generic harness planning model output"- )- )- }-- private static func jsonObjectCandidates(in outputText: String) -> [String] {- let trimmed = outputText.trimmingCharacters(in: .whitespacesAndNewlines)- var candidates: [String] = trimmed.isEmpty ? [] : [trimmed]- var objectStart: String.Index?- var depth = 0- var isInsideString = false- var isEscaped = false- var index = outputText.startIndex-- while index < outputText.endIndex {- let character = outputText[index]- if isInsideString {- if isEscaped {- isEscaped = false- } else if character == "\\" {- isEscaped = true- } else if character == "\"" {- isInsideString = false- }- } else if character == "\"" {- isInsideString = true- } else if character == "{" {- if depth == 0 {- objectStart = index- }- depth += 1- } else if character == "}", depth > 0 {- depth -= 1- if depth == 0, let start = objectStart {- let objectEnd = outputText.index(after: index)- candidates.append(String(outputText[start..<objectEnd]))- objectStart = nil- }- }-- index = outputText.index(after: index)- }-- var seen = Set<String>()- return candidates.filter { seen.insert($0).inserted }- }-- private static func actionPlan(from wire: GenericHarnessPlanningWire) -> LocalAppActionPlan {- let planSteps = wire.planSteps- let tools = planSteps.compactMap { step -> LocalAppActionPlanTool? in- let toolName = step.toolName.trimmingCharacters(in: .whitespacesAndNewlines)- guard !toolName.isEmpty else { return nil }- return LocalAppActionPlanTool(rawValue: toolName)- }- // Planners often carry the text to enter in a step's toolInputs (e.g. toolInputs.query)- // and leave the per-step inputEntity blank. Fall back to the conventional "query" entity so- // text-input plans still resolve their value from entities instead of looking up a blank key.- let inputEntity = firstNonEmpty(planSteps.map(\.inputEntity)) ?? "query"- let controlID = firstNonEmpty(planSteps.map(\.controlID)) ?? ""- let focusKey = firstNonEmpty(planSteps.map(\.focusKey)) ?? ""- var verificationTools = tools.filter(LocalAppActionPlan.isVerificationTool)- if verificationTools.isEmpty {- verificationTools = wire.verificationCriteria.contains { criterion in- criterion.localizedCaseInsensitiveContains("visible")- } ? [.verifyVisibleText] : [.verifyCommand]- }-- return LocalAppActionPlan(- tools: tools,- inputEntity: inputEntity,- controlID: controlID,- focusKey: focusKey,- verificationTools: verificationTools- )- }-- private static func hostedPlanningMetadata(from wire: GenericHarnessPlanningWire) -> [String: String] {- var metadata = wire.metadata- metadata["genericHarness.schemaVersion"] = wire.schemaVersion- metadata["genericHarness.intent.route"] = wire.structuredIntent.route- metadata["genericHarness.intent.goal"] = wire.structuredIntent.goal- metadata["genericHarness.intent.targetApp"] = wire.structuredIntent.targetAppName- metadata["genericHarness.ambiguity.class"] = wire.ambiguityRisk.ambiguityClass- metadata["genericHarness.risk.level"] = wire.ambiguityRisk.riskLevel- metadata["genericHarness.shouldAskBeforeActing"] = String(wire.ambiguityRisk.shouldAskBeforeActing)- metadata["genericHarness.missingInformationJSON"] = jsonString(wire.ambiguityRisk.missingInformation)- metadata["genericHarness.contextNeedsJSON"] = jsonString(wire.contextNeeds)- metadata["genericHarness.planStepsJSON"] = jsonString(- wire.planSteps.map { step in- [- "id": step.id,- "summary": step.summary,- "toolName": step.toolName,- "inputEntity": step.inputEntity,- "controlID": step.controlID,- "focusKey": step.focusKey,- "toolInputs": step.toolInputs,- "expectedObservation": step.expectedObservation- ]- }- )- metadata["genericHarness.verificationCriteriaJSON"] = jsonString(wire.verificationCriteria)- metadata["genericHarness.fallbacksJSON"] = jsonString(wire.fallbacks)- metadata["genericHarness.clarification.shouldAsk"] = String(wire.clarificationPolicy.shouldAsk)- metadata["genericHarness.clarification.questionsJSON"] = jsonString(wire.clarificationPolicy.questions)- metadata["genericHarness.clarification.policy"] = wire.clarificationPolicy.policy- return metadata- }-- private static func jsonString(_ value: Any) -> String {- guard JSONSerialization.isValidJSONObject(value),- let data = try? JSONSerialization.data(- withJSONObject: value,- options: [.sortedKeys]- ),- let text = String(data: data, encoding: .utf8)- else {- return "[]"- }- return text- }-- private static func hasGenericExecutableTool(_ planStepsJSON: String) -> Bool {- guard let data = planStepsJSON.data(using: .utf8),- let steps = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]]- else {- return false- }- return steps.contains { step in- guard let toolName = step["toolName"] as? String else { return false }- return toolName == "skill.script.execute"- || toolName == "automation.applescript.execute"- }- }-- private static func firstNonEmpty(_ values: [String]) -> String? {- values.first { value in- !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty- }- }-- private static func nonEmpty(_ value: String?) -> String? {- let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""- return trimmed.isEmpty ? nil : trimmed- }-- private static func normalizedEntities(- from wire: TaskIntentWire,- definition: LocalAppTaskDefinition- ) -> [String: String] {- var normalized = wire.normalizedEntities- for rule in definition.entityRules {- guard let rawValue = wire.entities[rule.name] ?? normalized[rule.name] else { continue }- if let alias = rule.aliases[rawValue] ?? rule.aliases[LocalAppTextNormalizer.normalizedPhrase(rawValue)] {- normalized[rule.name] = alias- }- }- return normalized- }-- private static func dynamicAppName(- from wire: TaskIntentWire,- definition: LocalAppTaskDefinition- ) -> String? {- let entityAppName = wire.normalizedEntities["appName"] ?? wire.entities["appName"]- if let entityAppName,- !entityAppName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {- return entityAppName- }-- guard wire.targetAppName != definition.targetApp.appName else { return nil }- return wire.targetAppName- }-- private static func targetApp(- from wire: TaskIntentWire,- definition: LocalAppTaskDefinition,- appFinderEntry: LocalAppFinderCatalogEntry? = nil- ) -> LocalAppTarget {- if let appFinderEntry {- return LocalAppTarget(- appName: appFinderEntry.appName,- bundleIdentifier: appFinderEntry.bundleIdentifier,- titleContains: appFinderEntry.appName,- metadata: definition.targetApp.metadata- )- }- guard definition.metadata["dynamicTarget"] == "true",- wire.targetAppName != definition.targetApp.appName else {- return definition.targetApp- }-- return LocalAppTarget(- appName: wire.targetAppName,- bundleIdentifier: nil,- titleContains: wire.targetAppName,- metadata: definition.targetApp.metadata- )- }-- private struct AppFinderSelection {- var entry: LocalAppFinderCatalogEntry- var capability: LocalAppFinderCapability- var controlProfile: String- }-- private static func validatedAppFinderSelection(- wire: TaskIntentWire,- definition: LocalAppTaskDefinition,- appFinderCatalog: [LocalAppFinderCatalogEntry]- ) -> AppFinderSelection? {- guard definition.metadata["modelPlanned"] == "true",- appFinderCatalog.isEmpty == false- else {- return nil- }-- guard let entry = appFinderEntry(from: wire, in: appFinderCatalog),- entry.supportStatus == .supported,- entry.capabilities.isEmpty == false- else {- return nil- }-- let requestedCapabilityID = appFinderMetadataValue(- "appFinder.selectedCapabilityID",- fallback: "selectedCapabilityID",- in: wire- )- let capability = requestedCapabilityID.flatMap { capabilityID in- entry.capabilities.first { $0.id == capabilityID }- } ?? (entry.capabilities.count == 1 ? entry.capabilities[0] : nil)- guard let capability else {- return nil- }- let requestedControlProfile = appFinderMetadataValue(- "appFinder.controlProfile",- fallback: "controlProfile",- in: wire- )- let controlProfile = requestedControlProfile.flatMap { profile in- capability.controlProfiles.contains(profile) ? profile : nil- } ?? capability.controlProfiles.first- guard let controlProfile else {- return nil- }-- return AppFinderSelection(- entry: entry,- capability: capability,- controlProfile: controlProfile- )- }-- private static func appFinderEntry(- from wire: TaskIntentWire,- in appFinderCatalog: [LocalAppFinderCatalogEntry]- ) -> LocalAppFinderCatalogEntry? {- let selectedAppID = appFinderMetadataValue(- "appFinder.selectedAppID",- fallback: "selectedAppID",- in: wire- )- let appNameCandidates = [- wire.targetAppName,- wire.normalizedEntities["appName"],- wire.entities["appName"]- ]- .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }- .filter { !$0.isEmpty }-- if let selectedAppID,- let entry = appFinderCatalog.first(where: {- $0.appID == selectedAppID || $0.bundleIdentifier == selectedAppID- }) {- return entry- }-- return appFinderCatalog.first { entry in- appNameCandidates.contains { candidate in- LocalAppTextNormalizer.normalizedPhrase(candidate)- == LocalAppTextNormalizer.normalizedPhrase(entry.appName)- || candidate == entry.appID- || candidate == entry.bundleIdentifier- }- }- }-- private static func appFinderMetadataValue(- _ key: String,- fallback: String,- in wire: TaskIntentWire- ) -> String? {- let value = wire.metadata[key] ?? wire.metadata[fallback]- let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""- return trimmed.isEmpty ? nil : trimmed- }-- private static func slug(_ value: String) -> String {- LocalAppTextNormalizer.normalizedPhrase(value)- .split(separator: " ")- .joined(separator: "-")- }-}--private struct GenericHarnessPlanningWire: Decodable {- var schemaVersion: String- var structuredIntent: GenericHarnessStructuredIntentWire- var ambiguityRisk: GenericHarnessAmbiguityRiskWire- var contextNeeds: [String]- var planSteps: [GenericHarnessPlanStepWire]- var verificationCriteria: [String]- var fallbacks: [String]- var clarificationPolicy: GenericHarnessClarificationPolicyWire- var metadata: [String: String]-- private enum CodingKeys: String, CodingKey {- case structuredIntent- case ambiguityRisk- case contextNeeds- case planSteps- case verificationCriteria- case fallbacks- case clarificationPolicy- case metadata- }-- init(from decoder: Decoder) throws {- let container = try decoder.container(keyedBy: CodingKeys.self)- self.schemaVersion = "generic_harness_planning"- self.structuredIntent = try container.decode(GenericHarnessStructuredIntentWire.self, forKey: .structuredIntent)- self.ambiguityRisk = try container.decodeIfPresent(GenericHarnessAmbiguityRiskWire.self, forKey: .ambiguityRisk)- ?? GenericHarnessAmbiguityRiskWire(- ambiguityClass: "safe",- riskLevel: "low",- missingInformation: [],- shouldAskBeforeActing: false- )- self.contextNeeds = try container.decodeIfPresent(GenericHarnessStringListWire.self, forKey: .contextNeeds)?.values ?? []- self.planSteps = try container.decodeIfPresent([GenericHarnessPlanStepWire].self, forKey: .planSteps) ?? []- self.verificationCriteria = try container.decodeIfPresent(GenericHarnessStringListWire.self, forKey: .verificationCriteria)?.values ?? []- self.fallbacks = try container.decodeIfPresent(GenericHarnessStringListWire.self, forKey: .fallbacks)?.values ?? []- self.clarificationPolicy = try container.decodeIfPresent(GenericHarnessClarificationPolicyWire.self, forKey: .clarificationPolicy)- ?? GenericHarnessClarificationPolicyWire(shouldAsk: false, questions: [], policy: "")- self.metadata = try container.decodeIfPresent(GenericHarnessStringMapWire.self, forKey: .metadata)?.values ?? [:]- }-}--private struct GenericHarnessStructuredIntentWire: Decodable {- var route: String- var goal: String- var taskType: String- var targetAppName: String- var entities: [String: String]- var normalizedEntities: [String: String]- var confidence: Double- var needsConfirmation: Bool-- private enum CodingKeys: String, CodingKey {- case route- case goal- case taskType- case targetAppName- case entities- case normalizedEntities- case confidence- case needsConfirmation- }-- init(from decoder: Decoder) throws {- let container = try decoder.container(keyedBy: CodingKeys.self)- self.route = try container.decode(String.self, forKey: .route)- self.taskType = try container.decode(String.self, forKey: .taskType)- self.entities = try container.decodeIfPresent(GenericHarnessStringMapWire.self, forKey: .entities)?.values ?? [:]- self.normalizedEntities = try container.decodeIfPresent(GenericHarnessStringMapWire.self, forKey: .normalizedEntities)?.values ?? entities- self.goal = try container.decodeIfPresent(String.self, forKey: .goal)- ?? normalizedEntities["goal"]- ?? entities["goal"]- ?? ""- self.targetAppName = try container.decodeIfPresent(String.self, forKey: .targetAppName)- ?? normalizedEntities["appName"]- ?? entities["appName"]- ?? "none"- self.confidence = try container.decodeIfPresent(Double.self, forKey: .confidence) ?? 0.7- self.needsConfirmation = try container.decodeIfPresent(Bool.self, forKey: .needsConfirmation) ?? false- }-}--private struct GenericHarnessAmbiguityRiskWire: Decodable {- var ambiguityClass: String- var riskLevel: String- var missingInformation: [String]- var shouldAskBeforeActing: Bool-- init(- ambiguityClass: String,- riskLevel: String,- missingInformation: [String],- shouldAskBeforeActing: Bool- ) {- self.ambiguityClass = ambiguityClass- self.riskLevel = riskLevel- self.missingInformation = missingInformation- self.shouldAskBeforeActing = shouldAskBeforeActing- }-- private enum CodingKeys: String, CodingKey {- case ambiguityClass- case riskLevel- case missingInformation- case shouldAskBeforeActing- }-- init(from decoder: Decoder) throws {- let container = try decoder.container(keyedBy: CodingKeys.self)- self.ambiguityClass = try container.decodeIfPresent(String.self, forKey: .ambiguityClass) ?? "safe"- self.riskLevel = try container.decodeIfPresent(String.self, forKey: .riskLevel) ?? "low"- self.missingInformation = try container.decodeIfPresent(GenericHarnessStringListWire.self, forKey: .missingInformation)?.values ?? []- self.shouldAskBeforeActing = try container.decodeIfPresent(Bool.self, forKey: .shouldAskBeforeActing) ?? false- }-}--private struct GenericHarnessPlanStepWire: Decodable {- var id: String- var summary: String- var toolName: String- var inputEntity: String- var controlID: String- var focusKey: String- var toolInputs: [String: String]- var expectedObservation: String-- private enum CodingKeys: String, CodingKey {- case id- case summary- case toolName- case inputEntity- case controlID- case focusKey- case toolInputs- case expectedObservation- }-- init(from decoder: Decoder) throws {- let container = try decoder.container(keyedBy: CodingKeys.self)- self.toolName = try container.decode(String.self, forKey: .toolName)- self.id = try container.decodeIfPresent(String.self, forKey: .id) ?? toolName- self.summary = try container.decodeIfPresent(String.self, forKey: .summary) ?? ""- self.inputEntity = try container.decodeIfPresent(String.self, forKey: .inputEntity) ?? ""- self.controlID = try container.decodeIfPresent(String.self, forKey: .controlID) ?? ""- self.focusKey = try container.decodeIfPresent(String.self, forKey: .focusKey) ?? ""- self.toolInputs = try container.decodeIfPresent(GenericHarnessStringMapWire.self, forKey: .toolInputs)?.values ?? [:]- self.expectedObservation = try container.decodeIfPresent(String.self, forKey: .expectedObservation) ?? ""- }-}--private struct GenericHarnessClarificationPolicyWire: Decodable {- var shouldAsk: Bool- var questions: [String]- var policy: String-- init(shouldAsk: Bool, questions: [String], policy: String) {- self.shouldAsk = shouldAsk- self.questions = questions- self.policy = policy- }-- private enum CodingKeys: String, CodingKey {- case shouldAsk- case questions- case policy- }-- init(from decoder: Decoder) throws {- let container = try decoder.container(keyedBy: CodingKeys.self)- self.shouldAsk = try container.decodeIfPresent(Bool.self, forKey: .shouldAsk) ?? false- self.questions = try container.decodeIfPresent(GenericHarnessStringListWire.self, forKey: .questions)?.values ?? []- self.policy = try container.decodeIfPresent(String.self, forKey: .policy) ?? ""- }-}--private struct GenericHarnessStringListWire: Decodable {- var values: [String]-- init(from decoder: Decoder) throws {- let container = try decoder.singleValueContainer()- if let strings = try? container.decode([String].self) {- self.values = strings- return- }- if let string = try? container.decode(String.self) {- self.values = string.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? [] : [string]- return- }- if let object = try? container.decode(GenericHarnessStringMapWire.self) {- self.values = object.values- .map { key, value in value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? key : value }- .filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }- .sorted()- return- }- self.values = []- }-}--private struct GenericHarnessStringMapWire: Decodable {- var values: [String: String]-- init(from decoder: Decoder) throws {- let container = try decoder.container(keyedBy: GenericHarnessDynamicCodingKey.self)- var values: [String: String] = [:]- for key in container.allKeys {- guard let value = try? container.decode(GenericHarnessStringValueWire.self, forKey: key),- !value.value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty- else {- continue- }- values[key.stringValue] = value.value- }- self.values = values- }-}--private struct GenericHarnessStringValueWire: Decodable {- var value: String-- init(from decoder: Decoder) throws {- let container = try decoder.singleValueContainer()- if let string = try? container.decode(String.self) {- self.value = string- } else if let bool = try? container.decode(Bool.self) {- self.value = String(bool)- } else if let int = try? container.decode(Int.self) {- self.value = String(int)- } else if let double = try? container.decode(Double.self) {- self.value = String(double)- } else if let strings = try? container.decode([String].self) {- self.value = strings.joined(separator: ", ")- } else if let object = try? container.decode([String: String].self) {- self.value = object- .map { "\($0.key): \($0.value)" }- .sorted()- .joined(separator: ", ")- } else {- self.value = ""- }- }-}--private struct GenericHarnessDynamicCodingKey: CodingKey {- var stringValue: String- var intValue: Int?-- init?(stringValue: String) {- self.stringValue = stringValue- }-- init?(intValue: Int) {- self.stringValue = String(intValue)- self.intValue = intValue- }-}--private struct TaskIntentWire: Decodable {- var taskType: String- var targetAppName: String- var entities: [String: String]- var normalizedEntities: [String: String]- var confidence: Double- var needsConfirmation: Bool- var actionPlan: LocalAppActionPlan- var metadata: [String: String]-}diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swiftindex 8b8a64dd..60d22d97 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swift@@ -118,113 +118,3 @@ public enum BuiltInLocalAppSkillPacks {return String(value.prefix(maxCharacters)).trimmingCharacters(in: .whitespacesAndNewlines)}}--public struct LocalAppTaskSkillContext: Equatable, Sendable {- public var snippets: [String]-- public init(snippets: [String]) {- self.snippets = snippets- }-- /// Builds skill guidance that scales to many skills via progressive disclosure (no embeddings):- /// 1. A compact discovery catalog — one line per skill (id + summary + tags) for the top-K- /// lexically-relevant skills — so the planner can SEE what is available and pick one.- /// 2. The FULL instruction body of the single best-matched skill, so its concrete execution- /// steps (e.g. skill.load → skill.script.execute) are never truncated.- /// Context stays bounded regardless of the total number of skills: K one-liners + 1 full body.- /// The planner can `skill.load` any other catalog entry to get that skill's full body on demand.- public static func defaultContext(- command: String = "",- taskDefinitions: [LocalAppTaskDefinition],- appFinderCatalog: [LocalAppFinderCatalogEntry],- maxSkills: Int = 24,- detailCharacters: Int = 4_000- ) -> LocalAppTaskSkillContext {- let ranked = rankedBuiltInSkillDescriptors(- command: command,- taskDefinitions: taskDefinitions,- appFinderCatalog: appFinderCatalog- )- guard !ranked.isEmpty else {- return LocalAppTaskSkillContext(snippets: [])- }-- let catalogEntries = ranked.prefix(max(1, maxSkills)).map(\.descriptor)- let catalog = (["Available skills (pick the most relevant for the request; load it with skill.load to get its full steps):"]- + catalogEntries.map(discoveryLine(for:)))- .joined(separator: "\n")-- var snippets = [catalog]- if let top = ranked.first, top.score > 0 {- snippets.append(BuiltInLocalAppSkillPacks.instructionSnippet(for: top.descriptor, maxCharacters: detailCharacters))- }- return LocalAppTaskSkillContext(snippets: snippets)- }-- /// One compact catalog line for discovery: `- <id>: <summary> (tags: a, b)`.- private static func discoveryLine(for descriptor: HarnessSkillDescriptor) -> String {- let tags = descriptor.tags.isEmpty ? "" : " (tags: \(descriptor.tags.joined(separator: ", ")))"- return "- \(descriptor.id): \(descriptor.summary)\(tags)"- }-- private static func rankedBuiltInSkillDescriptors(- command: String,- taskDefinitions: [LocalAppTaskDefinition],- appFinderCatalog: [LocalAppFinderCatalogEntry]- ) -> [(descriptor: HarnessSkillDescriptor, score: Int)] {- // App-specific operating skills (those declaring `apps:`) are vision-driving playbooks- // consumed via `appOperatingGuidance(forApp:)` by the vision action path — they are not- // intent-planning skills, so keep them out of the planner's skill catalog/ranking.- let descriptors = BuiltInLocalAppSkillPacks.descriptors()- .filter { ($0.metadata["apps"] ?? "").trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }- guard !descriptors.isEmpty else { return [] }-- var taskValues: [String] = []- for definition in taskDefinitions {- taskValues.append(definition.taskType)- taskValues.append(definition.targetApp.appName)- taskValues.append(definition.metadata["displayTitle"] ?? "")- taskValues.append(definition.metadata["domain"] ?? "")- taskValues.append(definition.metadata["catalogEntry"] ?? "")- }- let taskTokens = tokens(in: taskValues.joined(separator: " "))-- var catalogValues: [String] = []- for entry in appFinderCatalog {- catalogValues.append(entry.appName)- catalogValues.append(entry.description)- for capability in entry.capabilities {- catalogValues.append(capability.id)- catalogValues.append(capability.summary)- catalogValues.append(capability.controlProfiles.joined(separator: " "))- }- }- let catalogTokens = tokens(in: catalogValues.joined(separator: " "))- // The user's actual request is the strongest signal for which skills the task needs, so- // weight command matches heavily. Without this, selection only reflects installed apps and- // static task definitions, which can miss (or arbitrarily pick) the skill the task requires.- let commandTokens = tokens(in: command)- let availableTokens = taskTokens.union(catalogTokens).union(commandTokens)- return descriptors.map { descriptor in- // Score over id, name, summary, tags, and the file-based `keywords:` trigger words.- let descriptorTokens = tokens(- in: ([descriptor.id, descriptor.name, descriptor.summary, descriptor.metadata["keywords"] ?? ""]- + descriptor.tags)- .joined(separator: " ")- )- let score = descriptorTokens.intersection(availableTokens).count- + 3 * descriptorTokens.intersection(commandTokens).count- return (descriptor: descriptor, score: score)- }- .sorted {- if $0.score == $1.score {- return $0.descriptor.name < $1.descriptor.name- }- return $0.score > $1.score- }- }-- private static func tokens(in value: String) -> Set<String> {- ControlTextRelevance.tokens(in: value)- }-}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swiftindex 2c649fb8..1e921ad8 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift@@ -332,316 +332,6 @@ struct AIHarnessAdapterTests {#expect(failed.metadata["sidecar.reason"] == "nonZeroExit")}- @Test- func hostedTaskIntentAdapterUsesBackendResponsesProxy() async throws {- let httpClient = FakeAIHTTPClient(- data: responseData(- outputText: hostedPlanningOutput(- goal: "open cnn.com in Safari",- taskType: "local_app_interaction",- targetAppName: "Safari",- entitiesJSON: #"{"appName":"Safari","goal":"open requested website","query":"https://cnn.com"}"#,- normalizedEntitiesJSON: #"{"appName":"Safari","goal":"open requested website","query":"https://cnn.com"}"#,- confidence: 0.91,- planStepsJSON: #"[{"id":"launch","summary":"Open Safari.","toolName":"app.openOrFocus","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Safari is focused."},{"id":"focus-address","summary":"Focus address bar.","toolName":"ui.focusAddressBar","inputEntity":"","controlID":"addressBar","focusKey":"Command+L","expectedObservation":"Address bar is focused."},{"id":"set-url","summary":"Enter URL.","toolName":"ui.setText","inputEntity":"query","controlID":"addressBar","focusKey":"","expectedObservation":"URL is entered."},{"id":"submit","summary":"Submit navigation.","toolName":"ui.pressReturn","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Navigation is submitted."},{"id":"verify","summary":"Verify command.","toolName":"app.verifyCommand","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Navigation command is attempted."}]"#,- verificationCriteriaJSON: #"["Navigation command is attempted."]"#,- fallbacksJSON: #"["Ask if the website is ambiguous."]"#,- metadataJSON: #"{"source":"test"}"#- )- ),- statusCode: 200- )- let adapter = HostedTaskIntentParsingAdapter(- configuration: DonkeyBackendInferenceConfiguration(- baseURL: URL(string: "https://donkey.example")!,- clientID: "client-1"- ),- httpClient: httpClient- )-- let result = await adapter.parseTaskIntent(- TaskIntentAdapterRequest(- command: "open cnn.com",- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,- sourceTraceID: "trace-hosted-intent"- )- )-- #expect(result.intent?.taskType == "local_app_interaction")- #expect(result.intent?.parserSource == .onlineModel)- #expect(result.trace.provider == .donkeyBackend)- #expect(result.trace.modelID == AIModelRegistryEntry.backendSelectedModelID)- #expect(result.trace.metadata["privacy.store"] == "false")-- let request = try #require(httpClient.requests.first)- #expect(request.url?.path == "/api/inference/responses/")- let body = try #require(request.httpBodyJSONObject)- #expect(body["model"] == nil)- #expect(body["store"] as? Bool == false)- #expect(body["donkeyProvider"] == nil)- let parameters = try #require(body["parameters"] as? [String: Any])- let instructions = try #require(parameters["instructions"] as? String)- let text = try #require(body["text"] as? [String: Any])- let format = try #require(text["format"] as? [String: Any])- #expect(format["name"] as? String == "generic_harness_planning")- let schema = try #require(format["schema"] as? [String: Any])- let required = try #require(schema["required"] as? [String])- #expect(required.contains("schemaVersion") == false)- let properties = try #require(schema["properties"] as? [String: Any])- #expect(properties["schemaVersion"] == nil)- #expect(properties["structuredIntent"] != nil)- let structuredIntent = try #require(properties["structuredIntent"] as? [String: Any])- let structuredRequired = try #require(structuredIntent["required"] as? [String])- #expect(structuredRequired.contains("goal") == false)- #expect(structuredRequired.contains("targetAppName") == false)- #expect(structuredRequired.contains("confidence") == false)- #expect(properties["ambiguityRisk"] != nil)- #expect(properties["contextNeeds"] != nil)- #expect(properties["planSteps"] != nil)- #expect(properties["verificationCriteria"] != nil)- #expect(properties["fallbacks"] != nil)- #expect(properties["clarificationPolicy"] != nil)- #expect(result.intent?.metadata["genericHarness.schemaVersion"] == "generic_harness_planning")- #expect(result.intent?.metadata["genericHarness.intent.goal"] == "open cnn.com in Safari")- #expect(instructions.contains("local_app_interaction"))- #expect(instructions.contains("App skill guidance"))- #expect(instructions.contains("metadata.assistantResponse"))- let input = try #require(body["input"] as? [[String: Any]])- let firstInput = try #require(input.first)- let content = try #require(firstInput["content"] as? [[String: Any]])- let prompt = try #require(content.first?["text"] as? String)- #expect(prompt.contains("Skill ID: browser-navigation"))- }-- @Test- func hostedTaskIntentAdapterPreservesSkillToolPlanInputs() async throws {- let httpClient = FakeAIHTTPClient(- data: responseData(- outputText: hostedPlanningOutput(- goal: "play a selected song in Music",- taskType: "local_app_interaction",- targetAppName: "Music",- entitiesJSON: #"{"appName":"Music","goal":"play media","query":"Yellow Coldplay"}"#,- normalizedEntitiesJSON: #"{"appName":"Music","goal":"play media","query":"Yellow Coldplay"}"#,- confidence: 0.91,- planStepsJSON: #"[{"id":"load-music-skill","summary":"Load the media skill.","toolName":"skill.load","inputEntity":"","controlID":"","focusKey":"","toolInputs":{"skillID":"music-media"},"expectedObservation":"Music skill is loaded."},{"id":"play-media","summary":"Run the validated media script.","toolName":"skill.script.execute","inputEntity":"query","controlID":"","focusKey":"","toolInputs":{"skillID":"music-media","scriptID":"scripts-play-media-by-search"},"expectedObservation":"status=played"},{"id":"verify-played","summary":"Verify script evidence.","toolName":"state.verify","inputEntity":"","controlID":"","focusKey":"","toolInputs":{"criteria":"status=played"},"expectedObservation":"Script reported playback."}]"#,- verificationCriteriaJSON: #"["status=played"]"#,- fallbacksJSON: #"["Ask if the script reports clarification.required=true."]"#,- metadataJSON: #"{"appFinder.selectedAppID":"com.apple.Music","appFinder.selectedCapabilityID":"play_media","appFinder.controlProfile":"search_then_enter"}"#- )- ),- statusCode: 200- )- let adapter = HostedTaskIntentParsingAdapter(- configuration: DonkeyBackendInferenceConfiguration(- baseURL: URL(string: "https://donkey.example")!,- clientID: "client-1"- ),- httpClient: httpClient- )-- let result = await adapter.parseTaskIntent(- TaskIntentAdapterRequest(- command: "play some coldplay",- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,- availableToolNames: [- "skill.load",- "skill.script.execute",- "state.verify"- ],- sourceTraceID: "trace-skill-intent"- )- )-- #expect(result.intent?.taskType == "local_app_interaction")- #expect(result.intent?.actionPlan != nil)- #expect(result.intent?.metadata["genericHarness.planStepsJSON"]?.contains("\"toolName\":\"skill.script.execute\"") == true)- #expect(result.intent?.metadata["genericHarness.planStepsJSON"]?.contains("\"scriptID\":\"scripts-play-media-by-search\"") == true)-- let request = try #require(httpClient.requests.first)- let body = try #require(request.httpBodyJSONObject)- let text = try #require(body["text"] as? [String: Any])- let format = try #require(text["format"] as? [String: Any])- let schema = try #require(format["schema"] as? [String: Any])- let properties = try #require(schema["properties"] as? [String: Any])- let planSteps = try #require(properties["planSteps"] as? [String: Any])- let items = try #require(planSteps["items"] as? [String: Any])- let stepProperties = try #require(items["properties"] as? [String: Any])- #expect(stepProperties["toolInputs"] != nil)- let toolName = try #require(stepProperties["toolName"] as? [String: Any])- let toolEnums = try #require(toolName["enum"] as? [String])- #expect(toolEnums.contains("skill.script.execute"))- }-- @Test- func hostedTaskIntentAdapterDefaultsMissingPlanningSchemaVersion() async {- let output = hostedPlanningOutput(- goal: "play a selected song in Music",- taskType: "local_app_interaction",- targetAppName: "Music",- entitiesJSON: #"{"appName":"Music","goal":"play media","query":"Yellow Coldplay"}"#,- normalizedEntitiesJSON: #"{"appName":"Music","goal":"play media","query":"Yellow Coldplay"}"#,- confidence: 0.91,- planStepsJSON: #"[{"id":"launch","summary":"Open Music.","toolName":"app.openOrFocus","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Music is focused."},{"id":"focus-search","summary":"Focus search.","toolName":"ui.focusSearch","inputEntity":"","controlID":"search","focusKey":"Command+F","expectedObservation":"Search is focused."},{"id":"set-text","summary":"Enter query.","toolName":"ui.setText","inputEntity":"query","controlID":"search","focusKey":"","expectedObservation":"Query is entered."},{"id":"submit","summary":"Submit search.","toolName":"ui.pressReturn","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Search is submitted."}]"#,- verificationCriteriaJSON: #"{"success":"Playback command is attempted."}"#,- fallbacksJSON: #"["Ask if the song is ambiguous."]"#- )- .replacingOccurrences(- of: #""goal":"play a selected song in Music","#,- with: ""- )- let httpClient = FakeAIHTTPClient(data: responseData(outputText: output), statusCode: 200)- let adapter = HostedTaskIntentParsingAdapter(- configuration: DonkeyBackendInferenceConfiguration(- baseURL: URL(string: "https://donkey.example")!,- clientID: "client-1"- ),- httpClient: httpClient- )-- let result = await adapter.parseTaskIntent(- TaskIntentAdapterRequest(- command: "play some coldplay",- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,- sourceTraceID: "trace-repair-intent"- )- )-- #expect(result.intent?.taskType == "local_app_interaction")- #expect(result.trace.status == .completed)- #expect(result.trace.validationStatus == "schemaDecoded")- #expect(result.intent?.metadata["genericHarness.schemaVersion"] == "generic_harness_planning")- #expect(result.intent?.metadata["genericHarness.intent.goal"] == "play media")- #expect(result.intent?.metadata["genericHarness.verificationCriteriaJSON"] == #"["Playback command is attempted."]"#)- #expect(result.trace.metadata["reason"] == nil)- #expect(result.trace.metadata["planner.repairAttempted"] == nil)- #expect(httpClient.requests.count == 1)- }-- @Test- func hostedTaskIntentAdapterTreatsIrreparablePlanningEnvelopeAsInvalidOutput() async {- let httpClient = SequencedFakeAIHTTPClient(responses: [- HTTPStub(data: responseData(outputText: "{}"), statusCode: 200),- HTTPStub(data: responseData(outputText: "{}"), statusCode: 200)- ])- let adapter = HostedTaskIntentParsingAdapter(- configuration: DonkeyBackendInferenceConfiguration(- baseURL: URL(string: "https://donkey.example")!,- clientID: "client-1"- ),- httpClient: httpClient- )-- let result = await adapter.parseTaskIntent(- TaskIntentAdapterRequest(- command: "play some coldplay",- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,- sourceTraceID: "trace-invalid-intent"- )- )-- #expect(result.intent == nil)- #expect(result.trace.status == .invalidOutput)- #expect(result.trace.validationStatus == "invalid")- #expect(result.trace.metadata["reason"] == "hostedPlanningSchemaDecodeFailed")- #expect(result.trace.metadata["planner.repairAttempted"] == "true")- #expect(result.trace.metadata["planner.repairStatus"] == "invalid")- #expect(httpClient.requests.count == 2)- }-- @Test- func hostedTaskIntentAdapterPreservesNoTaskConversationResponse() async throws {- let httpClient = FakeAIHTTPClient(- data: responseData(- outputText: hostedPlanningOutput(- route: "conversation",- goal: "respond to greeting",- taskType: "none",- targetAppName: "none",- confidence: 0,- metadataJSON: #"{"responseMode":"conversation","assistantResponse":"Hi there! What would you like to work on?"}"#- )- ),- statusCode: 200- )- let adapter = HostedTaskIntentParsingAdapter(- configuration: DonkeyBackendInferenceConfiguration(- baseURL: URL(string: "https://donkey.example")!,- clientID: "client-1"- ),- httpClient: httpClient- )-- let result = await adapter.parseTaskIntent(- TaskIntentAdapterRequest(- command: "hi there",- taskDefinitions: BuiltInLocalAppTaskDefinitions.testFixtures,- sourceTraceID: "trace-hosted-greeting"- )- )-- #expect(result.intent == nil)- #expect(result.trace.status == .completed)- #expect(result.trace.validationStatus == "noTaskIntent")- #expect(result.trace.metadata["responseMode"] == "conversation")- #expect(result.trace.metadata["assistantResponse"] == "Hi there! What would you like to work on?")- #expect(result.trace.metadata["provider"] == "donkeyBackend")- }-- @Test- func hostedTaskIntentAdapterMapsGenericPlanStepsToBridgeActionPlan() async throws {- let httpClient = FakeAIHTTPClient(- data: responseData(- outputText: hostedPlanningOutput(- goal: "open cnn.com in Safari",- taskType: "local_app_interaction",- targetAppName: "Safari",- entitiesJSON: #"{"appName":"Safari","goal":"open requested website","query":"https://cnn.com"}"#,- normalizedEntitiesJSON: #"{"appName":"Safari","goal":"open requested website","query":"https://cnn.com"}"#,- confidence: 0.94,- contextNeedsJSON: #"["app lookup","screen observation"]"#,- planStepsJSON: """- [{"id":"launch","summary":"Open or focus Safari.","toolName":"app.openOrFocus","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Safari is focused."},{"id":"focus-address","summary":"Focus the address bar.","toolName":"ui.focusAddressBar","inputEntity":"","controlID":"addressBar","focusKey":"Command+L","expectedObservation":"Address bar is ready."},{"id":"enter-url","summary":"Enter the requested URL.","toolName":"ui.setText","inputEntity":"query","controlID":"addressBar","focusKey":"","expectedObservation":"URL is entered."},{"id":"submit","summary":"Navigate to the URL.","toolName":"ui.pressReturn","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Navigation is attempted."},{"id":"verify","summary":"Verify the navigation command.","toolName":"app.verifyCommand","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Command attempt is recorded."}]- """,- verificationCriteriaJSON: #"["Navigation to the requested URL is attempted."]"#,- fallbacksJSON: #"["Ask if the URL is missing or ambiguous."]"#,- metadataJSON: #"{"source":"test"}"#- )- ),- statusCode: 200- )- let adapter = HostedTaskIntentParsingAdapter(- configuration: DonkeyBackendInferenceConfiguration(- baseURL: URL(string: "https://donkey.example")!,- clientID: "client-1"- ),- httpClient: httpClient- )-- let result = await adapter.parseTaskIntent(- TaskIntentAdapterRequest(- command: "open cnn.com",- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,- sourceTraceID: "trace-hosted-plan-steps"- )- )-- #expect(result.intent?.taskType == "local_app_interaction")- #expect(result.intent?.targetApp.appName == "Safari")- #expect(result.intent?.actionPlan?.tools == [- .openOrFocusApp,- .focusAddressBar,- .setText,- .pressReturn,- .verifyCommand- ])- #expect(result.intent?.actionPlan?.inputEntity == "query")- #expect(result.intent?.actionPlan?.controlID == "addressBar")- #expect(result.intent?.actionPlan?.focusKey == "Command+L")- #expect(result.intent?.metadata["genericHarness.contextNeedsJSON"] == #"["app lookup","screen observation"]"#)- #expect(result.intent?.metadata["genericHarness.fallbacksJSON"] == #"["Ask if the URL is missing or ambiguous."]"#)- }-@Testfunc hostedFollowUpResolverLetsBackendSelectResponsesModel() async throws {let httpClient = FakeAIHTTPClient(@@ -691,45 +381,6 @@ struct AIHarnessAdapterTests {-- @Test- func taskIntentRequestsCompactContextSnippetsBeforeModelCalls() {- let snippets = (0..<12).map { index in- "snippet-\(index) " + String(repeating: "\(index)", count: 2_000)- }-- let request = TaskIntentAdapterRequest(- command: "continue",- taskDefinitions: [],- contextSnippets: snippets,- sourceTraceID: "trace-compact-intent"- )-- #expect(request.contextSnippets.count == 4)- #expect(request.contextSnippets.allSatisfy { $0.count <= 1_200 })- #expect(request.contextSnippets.joined().count <= 4_800)- #expect(request.contextSnippets.first?.contains("snippet-0") == true)- #expect(request.contextSnippets.first?.contains("[compacted]") == true)- }-------------------@Testfunc hostedPlannerAdapterBuildsResponsesRequestWithStoreFalseAndDecodesStructuredHint() async throws {let httpClient = FakeAIHTTPClient(diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swiftindex 2ce82cee..9eb486e3 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift@@ -324,14 +324,6 @@ struct GenericHarnessTests {let skills = BuiltInLocalAppSkillPacks.descriptors()#expect(skills.contains { $0.id == "music-media" })#expect(skills.contains { $0.id == "browser-navigation" })-- let context = LocalAppTaskSkillContext.defaultContext(- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,- appFinderCatalog: []- )-- #expect(context.snippets.contains { $0.contains("Skill ID: music-media") })- #expect(context.snippets.joined(separator: "\n").contains("metadata.mediaSelection.kind"))}@Test