Open source CapCut alternative.
TypeScript
Remove local-generate task intent adapter
David Le41c98b46a952
diff --git a/apps/Donkey/Package.swift b/apps/Donkey/Package.swiftindex 17b8444e..2e0c3a98 100644--- a/apps/Donkey/Package.swift+++ b/apps/Donkey/Package.swift@@ -43,7 +43,8 @@ let package = Package("DonkeyHarness"],resources: [- .process("Resources")+ .process("Resources/local-app-finder-profiles.json"),+ .copy("Resources/BuiltInSkills")],linkerSettings: [.linkedLibrary("sqlite3")diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swiftindex 1691d3ac..4b69325a 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift@@ -610,7 +610,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {)?? Self.metadataValue(in: trace.metadata,- keys: ["reason", "fallback.reason", "modelFallback.reason"]+ keys: ["reason", "fallback.reason"])?? ""let modelDetail = Self.metadataValue(diff --git a/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift b/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swiftnew file mode 100644index 00000000..ed374bf7--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift@@ -0,0 +1,374 @@+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"]+ )+ }++ guard 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+ ) else {+ let baseMetadata = Self.outputDiagnostics(for: outputText)+ .merging([+ "provider": "donkeyBackend",+ "privacy.store": "false"+ ]) { current, _ in current }+ guard let noTaskMetadata = try? TaskIntentWireCodec.hostedPlanningNoTaskMetadata(+ outputText,+ parserName: "hosted-responses-v1"+ ) else {+ return result(+ entry: entry,+ request: request,+ status: .invalidOutput,+ validationStatus: "invalid",+ latencyMS: latencyMS,+ metadata: baseMetadata+ )+ }+ return result(+ entry: entry,+ request: request,+ status: .completed,+ validationStatus: "noTaskIntent",+ latencyMS: latencyMS,+ metadata: baseMetadata.merging(noTaskMetadata) { _, new in new }+ )+ }++ 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 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 func responseRequest(+ entry: AIModelRegistryEntry,+ adapterRequest: TaskIntentAdapterRequest+ ) -> RemoteInferenceResponseCreateRequest {+ RemoteInferenceResponseCreateRequest(+ input: .array([+ .object([+ "role": .string("user"),+ "content": .array([+ .object([+ "type": .string("input_text"),+ "text": .string(promptText(for: adapterRequest))+ ])+ ])+ ])+ ]),+ store: false,+ text: [+ "format": .object([+ "type": .string("json_schema"),+ "name": .string(Self.schemaID),+ "strict": .bool(true),+ "schema": Self.jsonValue(TaskIntentWireCodec.genericHarnessPlanningJsonSchema(taskDefinitions: adapterRequest.taskDefinitions))+ ])+ ],+ metadata: [+ "source_trace_id": adapterRequest.sourceTraceID,+ "prompt_version": entry.promptVersion+ ],+ parameters: [+ "instructions": .string(Self.instructions),+ "temperature": .number(0)+ ]+ )+ }++ private func promptText(for request: TaskIntentAdapterRequest) -> 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")+ return [+ "Command: \(request.command)",+ "Relevant local cache:",+ request.contextSnippets.joined(separator: "\n"),+ "App skill guidance:",+ skillGuidance,+ "App finder catalog JSON:",+ appFinderCatalog,+ "Supported task definitions JSON:",+ definitions+ ].joined(separator: "\n")+ }++ private static let instructions = [+ "Decide whether the user is asking Donkey to run one of the provided local app task definitions.",+ "Return strict JSON only using the generic harness planning schema.",+ "First decide whether Command is an executable local-app task or a conversation turn.",+ "Executable local-app task means all three are clear: action, destination or target app/item, and enough payload to execute safely.",+ "Always fill structuredIntent, ambiguityRisk, contextNeeds, planSteps, verificationCriteria, fallbacks, clarificationPolicy, and metadata.",+ "If Command is a greeting, conversation, question, malformed request, or lacks a real executable payload, set structuredIntent.route conversation, taskType \"none\", targetAppName \"none\", empty entities and normalizedEntities, confidence 0, needsConfirmation false, no planSteps with toolName values, and metadata.responseMode \"conversation\" with metadata.assistantResponse containing a brief natural-language reply.",+ "For supported actions, set structuredIntent.route localAppTask, choose only a provided taskType and target app, and fill entities and normalizedEntities with the concrete values needed by required entity rules.",+ "Use the generic local_app_interaction task type for executable local app requests that need a model-planned app workflow and do not have a more specific provided task type.",+ "Use ambiguityRisk for safe, recoverable, or dangerous ambiguity. Dangerous ambiguity and missing required details must set structuredIntent.needsConfirmation true, ambiguityRisk.shouldAskBeforeActing true, and clarificationPolicy.shouldAsk true with a specific question.",+ "Use contextNeeds for app lookup, memory lookup, screen observation, element discovery, or skill lookup needed before or during execution.",+ "Use planSteps for the generic harness plan. Each executable step must name one allowed toolName, with inputEntity/controlID/focusKey filled when that tool needs them. Non-executable reasoning steps should use an empty toolName.",+ "Use verificationCriteria for what proves success, fallbacks for safe recovery choices, and clarificationPolicy for when Donkey should stop and ask.",+ "Apply App skill guidance for app-specific workflows, control strategies, required metadata, and output shapes. Do not invent app-specific behavior that is absent from task definitions, catalog data, memory, or loaded skill guidance.",+ "When App finder catalog JSON is non-empty and you use local_app_interaction, choose the target app only from a catalog entry with supportStatus supported and a matching capability. Set metadata.appFinder.selectedAppID to the exact appID, metadata.appFinder.selectedCapabilityID to the capability id, and metadata.appFinder.controlProfile to one declared control profile. Never select candidate, unsupported, or denied entries for execution.",+ "For local_app_interaction, select the most likely local app, set targetAppName and entities.appName to the human app name, set entities.goal, and when text must be entered set entities.query plus normalizedEntities.query.",+ "For local_app_interaction, fill planSteps with allowed toolName values only: app.openOrFocus, app.observe, ui.newDocument, ui.focusSearch, ui.focusAddressBar, ui.focusTextEntry, ui.setText, ui.pressReturn, app.verifyCommand, app.verifyVisibleText.",+ "When ui.setText is present, entities.query and normalizedEntities.query must be non-empty, the step inputEntity should usually be query, and controlID/focusKey should describe the guarded UI strategy.",+ "For every other task type, planSteps should not contain executable toolName values.",+ "If no supported capability fits, set structuredIntent.route conversation and taskType \"none\" with a helpful conversational assistantResponse rather than a generic local-action failure.",+ "Do not invent task types, unsupported entities, unsupported tools, app scripts, or direct input outside the schema."+ ].joined(separator: " ")++ 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? {+ if let outputText = value.objectValue?["output_text"]?.stringValue,+ !outputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ return outputText+ }++ guard let output = value.objectValue?["output"]?.arrayValue else {+ return nil+ }+ for item in output {+ guard let content = item.objectValue?["content"]?.arrayValue else { continue }+ for contentItem in content {+ guard contentItem.objectValue?["type"]?.stringValue == "output_text",+ let text = contentItem.objectValue?["text"]?.stringValue,+ !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ else {+ continue+ }+ return text+ }+ }+ return nil+ }++ 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 {+ switch value {+ case let string as String:+ return .string(string)+ case let bool as Bool:+ return .bool(bool)+ case let int as Int:+ return .number(Double(int))+ case let double as Double:+ return .number(double)+ case let array as [Any]:+ return .array(array.map(jsonValue))+ case let object as [String: Any]:+ return .object(object.mapValues(jsonValue))+ default:+ return .null+ }+ }++ 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 extension RemoteInferenceJSONValue {+ var objectValue: [String: RemoteInferenceJSONValue]? {+ if case .object(let value) = self {+ return value+ }+ return nil+ }++ var arrayValue: [RemoteInferenceJSONValue]? {+ if case .array(let value) = self {+ return value+ }+ return nil+ }++ var stringValue: String? {+ if case .string(let value) = self {+ return value+ }+ return nil+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift b/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swiftdeleted file mode 100644index d7f13f51..00000000--- a/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift+++ /dev/null@@ -1,2424 +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 appFinderCatalog: [LocalAppFinderCatalogEntry]- public var sourceTraceID: String- public var routeRequest: AIModelRouteRequest-- public init(- command: String,- taskDefinitions: [LocalAppTaskDefinition],- contextSnippets: [String] = [],- appFinderCatalog: [LocalAppFinderCatalogEntry] = [],- 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.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-}--public struct ProcessBackedLocalLLMTaskIntentAdapter: TaskIntentParsingAdapter {- public static let schemaID = "task_intent_v1"-- public var router: AIModelRouter- public var sidecarRunner: any LocalJSONSidecarRunning- public var encoder: JSONEncoder- public var decoder: JSONDecoder-- public init(- router: AIModelRouter = AIModelRouter(registry: .defaultHybridPlanner),- sidecarRunner: any LocalJSONSidecarRunning = ProcessBackedLocalJSONSidecarRunner(),- encoder: JSONEncoder = JSONEncoder(),- decoder: JSONDecoder = JSONDecoder()- ) {- self.router = router- self.sidecarRunner = sidecarRunner- self.encoder = encoder- self.decoder = decoder- }-- public func parseTaskIntent(- _ request: TaskIntentAdapterRequest- ) async -> TaskIntentAdapterResult {- let entry: AIModelRegistryEntry- do {- entry = try router.route(request.routeRequest.limitingProviders([.localRuntime]))- } catch {- return result(- entry: nil,- request: request,- status: .invalidOutput,- validationStatus: "routingFailed",- latencyMS: nil,- metadata: ["error": String(describing: error)]- )- }-- let input = LocalLLMTaskIntentSidecarRequest(- command: request.command,- taskDefinitions: request.taskDefinitions,- contextSnippets: request.contextSnippets,- appFinderCatalog: request.appFinderCatalog,- sourceTraceID: request.sourceTraceID,- modelID: entry.modelID,- cacheDirectory: LocalModelRuntimeExecutableResolver().modelCacheDirectoryPath(- environmentVariableName: "DONKEY_LOCAL_LLM_RUNNER"- ),- metadata: [- "schemaID": Self.schemaID,- "promptVersion": entry.promptVersion- ]- )- let result = await sidecarRunner.run(- LocalJSONSidecarRequest(- environmentVariableName: "DONKEY_LOCAL_LLM_RUNNER",- inputData: (try? encoder.encode(input)) ?? Data(),- timeoutMS: entry.timeoutMS,- metadata: [- "sidecar.role": "taskIntent",- "modelID": entry.modelID- ]- )- )-- guard result.status == .completed else {- return self.result(- entry: entry,- request: request,- status: result.status == .timedOut ? .timeout : .providerOutage,- validationStatus: "notValidated",- latencyMS: result.latencyMS,- metadata: result.metadata.merging([- "sidecar.stderr": result.stderrText- ]) { current, _ in current }- )- }-- do {- let response = try decoder.decode(LocalLLMTaskIntentSidecarResponse.self, from: result.outputData)- let responseMetadata = result.metadata- .merging(response.metadata) { current, _ in current }- .merging(Self.outputDiagnostics(for: response.outputText)) { current, _ in current }- if response.outputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,- response.metadata["reason"] != nil {- return self.result(- entry: entry,- request: request,- status: .providerOutage,- validationStatus: "notValidated",- latencyMS: result.latencyMS,- metadata: responseMetadata- )- }-- guard let intent = try TaskIntentWireCodec.decodeIntent(- response.outputText,- definitions: request.taskDefinitions,- originalCommand: request.command,- appFinderCatalog: request.appFinderCatalog,- sourceModelCallID: "model-call-\(request.sourceTraceID)",- parserName: "local-llm-sidecar-v1"- ) else {- if let noTaskMetadata = try? TaskIntentWireCodec.noTaskMetadata(- response.outputText,- parserName: "local-llm-sidecar-v1"- ) {- return self.result(- entry: entry,- request: request,- status: .completed,- validationStatus: "noTaskIntent",- latencyMS: result.latencyMS,- metadata: responseMetadata.merging(noTaskMetadata) { _, new in new }- )- }- return self.result(- entry: entry,- request: request,- status: .invalidOutput,- validationStatus: "invalid",- latencyMS: result.latencyMS,- metadata: responseMetadata- )- }-- return TaskIntentAdapterResult(- intent: intent,- trace: trace(- entry: entry,- request: request,- status: .completed,- validationStatus: "schemaDecoded",- latencyMS: result.latencyMS,- metadata: responseMetadata- )- )- } catch {- if let sidecarError = decodeSidecarError(- result.outputData,- entry: entry,- request: request,- sidecarResult: result,- decodeError: error- ) {- return sidecarError- }-- return self.result(- entry: entry,- request: request,- status: .invalidOutput,- validationStatus: "invalid",- latencyMS: result.latencyMS,- metadata: result.metadata.merging([- "error": String(describing: error),- "sidecar.outputPreview": Self.preview(result.outputData, maxCharacters: 240)- ]) { current, _ in current }- )- }- }-- private func decodeSidecarError(- _ data: Data,- entry: AIModelRegistryEntry,- request: TaskIntentAdapterRequest,- sidecarResult: LocalJSONSidecarResult,- decodeError: Error- ) -> TaskIntentAdapterResult? {- guard let errorResponse = try? decoder.decode(LocalLLMTaskIntentSidecarErrorResponse.self, from: data),- errorResponse.status == "error" || errorResponse.metadata["reason"] != nil- else {- return nil- }-- return result(- entry: entry,- request: request,- status: .providerOutage,- validationStatus: "notValidated",- latencyMS: sidecarResult.latencyMS,- metadata: sidecarResult.metadata.merging(- errorResponse.metadata.merging([- "sidecar.status": errorResponse.status,- "decode.error": String(describing: decodeError)- ]) { current, _ in current }- ) { current, _ in current }- )- }-- 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 preview(_ data: Data, maxCharacters: Int) -> String {- preview(String(decoding: data, as: UTF8.self), maxCharacters: maxCharacters)- }-- 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 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 ?? .localRuntime,- 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 LocalLLMTaskIntentSidecarRequest: Codable, Equatable, Sendable {- var command: String- var taskDefinitions: [LocalAppTaskDefinition]- var contextSnippets: [String]- var appFinderCatalog: [LocalAppFinderCatalogEntry]- var sourceTraceID: String- var modelID: String- var cacheDirectory: String?- var metadata: [String: String]-}--private struct LocalLLMTaskIntentSidecarResponse: Codable, Equatable, Sendable {- var outputText: String- var metadata: [String: String]-}--private struct LocalLLMTaskIntentSidecarErrorResponse: Codable, Equatable, Sendable {- var status: String- var metadata: [String: String]-}--public struct LocalGenerateTaskIntentAdapter: TaskIntentParsingAdapter {- public static let schemaID = "task_intent_v1"-- public var router: AIModelRouter- public var httpClient: any AIHTTPClient-- public init(- router: AIModelRouter = AIModelRouter(registry: .defaultHybridPlanner),- httpClient: any AIHTTPClient = URLSessionAIHTTPClient()- ) {- self.router = router- self.httpClient = httpClient- }-- public func parseTaskIntent(- _ request: TaskIntentAdapterRequest- ) async -> TaskIntentAdapterResult {- let entry: AIModelRegistryEntry- do {- entry = try router.route(request.routeRequest.limitingProviders([.ollama]))- } catch {- return result(- entry: nil,- request: request,- status: .invalidOutput,- validationStatus: "routingFailed",- latencyMS: nil,- metadata: ["error": String(describing: error)]- )- }-- let startedAt = ProcessInfo.processInfo.systemUptime- return await parseTaskIntent(- request,- entry: entry,- startedAt: startedAt,- fallbackFromModelID: nil- )- }-- private func parseTaskIntent(- _ request: TaskIntentAdapterRequest,- entry: AIModelRegistryEntry,- startedAt: Double,- fallbackFromModelID: String?- ) async -> TaskIntentAdapterResult {- do {- let urlRequest = try makeURLRequest(entry: entry, adapterRequest: request)- let (data, response) = try await httpClient.send(urlRequest)- let latencyMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000-- if response.statusCode == 404,- fallbackFromModelID == nil,- let fallbackModelID = try? await fallbackLocalGenerateModelID(- for: entry,- excluding: [entry.modelID]- ),- fallbackModelID != entry.modelID {- var fallbackEntry = entry- fallbackEntry.modelID = fallbackModelID- fallbackEntry.metadata["modelFallback.originalModelID"] = entry.modelID- fallbackEntry.metadata["modelFallback.reason"] = "requestedModelUnavailable"- let fallbackResult = await parseTaskIntent(- request,- entry: fallbackEntry,- startedAt: startedAt,- fallbackFromModelID: entry.modelID- )- var trace = fallbackResult.trace- trace.metadata["modelFallback.originalModelID"] = entry.modelID- trace.metadata["modelFallback.selectedModelID"] = fallbackModelID- trace.metadata["modelFallback.reason"] = "requestedModelUnavailable"- return TaskIntentAdapterResult(intent: fallbackResult.intent, trace: trace)- }-- if response.statusCode == 429 {- return result(- entry: entry,- request: request,- status: .rateLimited,- validationStatus: "notValidated",- latencyMS: latencyMS,- metadata: httpMetadata(response: response, data: data, fallbackFromModelID: fallbackFromModelID)- )- }-- if response.statusCode >= 500 {- return result(- entry: entry,- request: request,- status: .providerOutage,- validationStatus: "notValidated",- latencyMS: latencyMS,- metadata: httpMetadata(response: response, data: data, fallbackFromModelID: fallbackFromModelID)- )- }-- guard (200..<300).contains(response.statusCode),- let outputText = try Self.outputText(from: data)- else {- return result(- entry: entry,- request: request,- status: (200..<300).contains(response.statusCode) ? .invalidOutput : .providerOutage,- validationStatus: (200..<300).contains(response.statusCode) ? "invalid" : "notValidated",- latencyMS: latencyMS,- metadata: httpMetadata(response: response, data: data, fallbackFromModelID: fallbackFromModelID)- )- }-- let baseMetadata = httpMetadata(- response: response,- data: data,- fallbackFromModelID: fallbackFromModelID- )- guard let intent = try TaskIntentWireCodec.decodeIntent(- outputText,- definitions: request.taskDefinitions,- originalCommand: request.command,- appFinderCatalog: request.appFinderCatalog,- sourceModelCallID: "model-call-\(request.sourceTraceID)",- parserName: "local-generate-task-intent-v1"- ) else {- if let noTaskMetadata = try? TaskIntentWireCodec.noTaskMetadata(- outputText,- parserName: "local-generate-task-intent-v1"- ) {- return result(- entry: entry,- request: request,- status: .completed,- validationStatus: "noTaskIntent",- latencyMS: latencyMS,- metadata: baseMetadata- .merging(noTaskMetadata) { _, new in new }- .merging(["local.provider": "ollama"]) { current, _ in current }- )- }- return result(- entry: entry,- request: request,- status: .invalidOutput,- validationStatus: "invalid",- latencyMS: latencyMS,- metadata: baseMetadata- )- }-- return TaskIntentAdapterResult(- intent: intent,- trace: trace(- entry: entry,- request: request,- status: .completed,- validationStatus: "schemaDecoded",- latencyMS: latencyMS,- metadata: httpMetadata(- response: response,- data: data,- fallbackFromModelID: fallbackFromModelID- ).merging([- "local.provider": "ollama"- ]) { current, _ in current }- )- )- } 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: AIModelCallStatus = (error as NSError).code == NSURLErrorTimedOut ? .timeout : .providerOutage- return result(- entry: entry,- request: request,- status: status,- validationStatus: "notValidated",- latencyMS: latencyMS,- metadata: ["error": String(describing: error)]- )- }- }-- private func fallbackLocalGenerateModelID(- for entry: AIModelRegistryEntry,- excluding excludedModelIDs: Set<String>- ) async throws -> String? {- var request = URLRequest(url: Self.localGenerateAPIURL(for: entry.endpoint, path: "tags"))- request.httpMethod = "GET"- request.timeoutInterval = min(Double(entry.timeoutMS) / 1_000, 2)- let (data, response) = try await httpClient.send(request)- guard (200..<300).contains(response.statusCode) else {- return nil- }-- let tags = try JSONDecoder().decode(LocalGenerateTagsResponse.self, from: data)- return Self.preferredInstalledModelID(- from: tags.models,- excluding: excludedModelIDs- )- }-- private static func localGenerateAPIURL(for endpoint: URL, path: String) -> URL {- var components = URLComponents(url: endpoint, resolvingAgainstBaseURL: false)- components?.path = "/api/\(path)"- components?.query = nil- return components?.url ?? endpoint- }-- private static func preferredInstalledModelID(- from models: [LocalGenerateModelTag],- excluding excludedModelIDs: Set<String>- ) -> String? {- let candidates = models- .filter { model in- !model.name.isEmpty- && !excludedModelIDs.contains(model.name)- && !model.name.contains(":cloud")- && (model.size ?? 1) > 0- }- .map(\.name)-- for prefix in fallbackModelPrefixes {- if let match = candidates.first(where: { $0 == prefix || $0.hasPrefix("\(prefix):") }) {- return match- }- }-- return candidates.first- }-- private static let fallbackModelPrefixes = [- "qwen3",- "qwen2.5",- "llama3.1",- "llama3",- "mistral",- "gemma3",- "gemma2"- ]-- private func httpMetadata(- response: HTTPURLResponse,- data: Data,- fallbackFromModelID: String?- ) -> [String: String] {- var metadata = [- "http.status": String(response.statusCode),- "http.bodyPreview": Self.preview(data, maxCharacters: 240)- ]- if let fallbackFromModelID {- metadata["modelFallback.originalModelID"] = fallbackFromModelID- }- return metadata- }-- private static func preview(_ data: Data, maxCharacters: Int) -> String {- let singleLine = String(decoding: data, as: UTF8.self)- .replacingOccurrences(of: "\n", with: "\\n")- .replacingOccurrences(of: "\r", with: "\\r")- guard singleLine.count > maxCharacters else { return singleLine }- return String(singleLine.prefix(maxCharacters))- }-- private func makeURLRequest(- entry: AIModelRegistryEntry,- adapterRequest: TaskIntentAdapterRequest- ) throws -> URLRequest {- var request = URLRequest(url: entry.endpoint)- request.httpMethod = "POST"- request.timeoutInterval = Double(entry.timeoutMS) / 1_000- request.setValue("application/json", forHTTPHeaderField: "Content-Type")- request.httpBody = try JSONSerialization.data(withJSONObject: requestBody(entry: entry, adapterRequest: adapterRequest))- return request- }-- private func requestBody(- entry: AIModelRegistryEntry,- adapterRequest: TaskIntentAdapterRequest- ) -> [String: Any] {- return [- "model": entry.modelID,- "prompt": promptText(for: adapterRequest),- "stream": false,- "format": TaskIntentWireCodec.jsonSchema(- taskDefinitions: adapterRequest.taskDefinitions- ),- "options": [- "num_ctx": 2048,- "num_predict": Self.maxGeneratedTokens,- "temperature": 0,- "top_p": 0.8- ],- "keep_alive": "10m"- ]- }-- private func promptText(for request: TaskIntentAdapterRequest) -> String {- let tasks = request.taskDefinitions.map { definition in- let entities = definition.entityRules.map { rule in- "\(rule.name) required=\(rule.required)"- }- .joined(separator: "; ")- let workflow = definition.workflowSteps- .filter { $0.role != .parseIntent }- .map(\.summary)- .joined(separator: " -> ")- let automation = [- definition.metadata["automationBackend"].map { "automation_backend=\($0)" },- definition.metadata["appleScript.action"].map { "apple_script_action=\($0)" },- definition.metadata["appleScript.entityName"].map { "apple_script_entity=\($0)" }- ]- .compactMap(\.self)- .joined(separator: " | ")- let modelPlan = definition.metadata["modelPlanned"] == "true"- ? [- "model_plan=true",- "allowed_tools=\(definition.metadata["plan.allowedTools"] ?? "")",- "set_text_input_contract=\(definition.metadata["plan.setTextInputContract"] ?? "")",- "action_plan_required=true"- ].joined(separator: " | ")- : ""-- return [- "task_type=\(definition.taskType)",- "app=\(definition.targetApp.appName)",- "bundle=\(definition.targetApp.bundleIdentifier ?? "unknown")",- "capability=\(workflow)",- "entities=\(entities)",- automation,- modelPlan- ]- .filter { !$0.isEmpty }- .joined(separator: " | ")- }- .joined(separator: "\n")- let context = request.contextSnippets- .filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }- .prefix(8)- .joined(separator: "\n")- let appFinderCatalog = taskIntentAppFinderCatalogJSON(request.appFinderCatalog)-- return [- "You are Donkey's local task-intent boundary. Return strict JSON only; do not include reasoning.",- "First decide whether Command is an executable local-app task or a conversation turn.",- "Executable local-app task means all three are clear: action, destination or target app/item, and enough payload to execute safely.",- "If Command is a question, greeting, conversation, malformed request, or lacks a real executable payload, do not invent one. Return taskType \"none\", targetAppName \"none\", empty entities and normalizedEntities, confidence 0, needsConfirmation=false, actionPlan.tools=[], and metadata.responseMode=conversation with metadata.assistantResponse containing a brief natural-language reply.",- "If Command is an executable local task with one ordinary missing detail, set needsConfirmation=true and include missingEntity in metadata.",- "If Command is executable, choose by capability and target app, not exact wording. Use only the provided task definitions; do not invent task types, unsupported entities, or actions.",- "For play/listen media requests, treat the turn as executable when a supported play_media capability or media_playback task is available; choose Music or another supported media app, set query to the requested artist/song/album, and do not downgrade it to conversation.",- "For every media playback request, include metadata.mediaSelection.kind. For explicit playable requests use explicit_song, explicit_album, or explicit_playlist. For vague artist-level media requests such as 'play some <artist>', do media-selection planning before returning JSON: pick one concrete playable song or album by that artist using model knowledge, set query to '<selected title> <artist>', and include metadata.mediaSelection.kind=representative_song or representative_album, metadata.mediaSelection.seed=<artist>, metadata.mediaSelection.selectedTitle=<title>, and metadata.mediaSelection.reason. Do not use an artist-only query unless the user explicitly asks to open the artist page, play an artist radio/station, or browse the artist.",- "If visible search results are provided in context for a media request, choose the highest-confidence playable Song row whose artist matches the requested seed; skip Artist, Playlist, category, and different-artist rows.",- "If no capability fits, choose conversation with taskType \"none\" and a helpful metadata.assistantResponse rather than a failed local-action message.",- "For dynamic local-item capabilities, app/file/folder names may come from the request, relevant local cache, or default-app inference; the catalog will verify availability before execution.",- "For write/create document requests: if the requested content is malformed or not meaningful enough to type, choose conversation; do not fabricate a document payload just to make the task executable.",- "For local_app_interaction, select the most likely local app for the user's goal, set entities.goal, and when text must be entered set entities.query plus normalizedEntities.query.",- "For local_app_interaction, fill actionPlan.tools with allowed tools only: app.openOrFocus, app.observe, ui.newDocument, ui.focusSearch, ui.focusAddressBar, ui.focusTextEntry, ui.setText, ui.pressReturn, app.verifyCommand, app.verifyVisibleText.",- "For website navigation, choose Safari or the user's browser, set query to the URL, use ui.focusAddressBar with controlID=addressBar and focusKey=Command+L, then ui.setText and ui.pressReturn.",- "For writing in Notes, choose Notes, create the requested prose in query, and use ui.newDocument followed by ui.setText.",- "For generative writing requests, query must be the complete final text to type, not a single category label, restatement of the request, or placeholder copied from these instructions.",- "If the writing type is clear but topic/details are sparse, compose a short generic piece that satisfies the requested writing type and put that complete text in query.",- "For spreadsheet or table creation, choose Numbers, put compact tab-separated table content in query, and use ui.newDocument followed by ui.setText. If exact live data is unavailable, make a table-shaped brief with a data-needed note; do not output a single sentence.",- "When ui.setText is present, entities.query and normalizedEntities.query must be non-empty.",- "If you cannot produce non-empty text for ui.setText, choose conversation; never return ui.setText with an empty query.",- "For sparse writing requests such as 'write a [form] in Notes', infer the requested form and write a short finished piece. If the requested object is malformed or nonsensical, choose conversation.",- "Example malformed writing boundary: 'write a people in Notes' is not a meaningful writing form or payload, so choose conversation rather than writing a definition.",- "entities.appName must be the human app name, such as Safari, Notes, Numbers, or Music; do not put a bundle identifier in appName.",- "For local_app_interaction, set actionPlan.inputEntity to query when ui.setText should type the query, and set actionPlan.controlID/focusKey for the UI control strategy.",- "actionPlan must be one nested object containing tools, inputEntity, controlID, focusKey, and verification. Do not put inputEntity, controlID, focusKey, or verification at the top level.",- "The examples below show output structure only. Replace every example entity value with values inferred from Command and local cache; do not copy example query text unless the user asked for that exact text.",- "Media playback output shape when media_playback is provided: taskType=media_playback, targetAppName=Music, entities.query=<concrete playable title plus artist>, normalizedEntities.query=<concrete playable title plus artist>, metadata.mediaSelection.* when the user gave only an artist/genre/seed.",- "Media playback output shape for generic local_app_interaction: targetAppName=Music, entities.appName=Music, entities.goal=play media, entities.query=<concrete playable title plus artist>, actionPlan.tools=[app.openOrFocus, app.observe, ui.focusSearch, ui.setText, ui.pressReturn, app.verifyCommand], inputEntity=query, controlID=search, focusKey=Command+F, metadata.appFinder.selectedCapabilityID=play_media when selected from the app finder catalog, metadata.mediaSelection.* when the user gave only an artist/genre/seed.",- "Example vague artist request output shape: {\"taskType\":\"local_app_interaction\",\"targetAppName\":\"Music\",\"entities\":{\"appName\":\"Music\",\"goal\":\"play media\",\"query\":\"Viva La Vida Coldplay\"},\"normalizedEntities\":{\"appName\":\"Music\",\"goal\":\"play media\",\"query\":\"Viva La Vida Coldplay\"},\"confidence\":0.9,\"needsConfirmation\":false,\"actionPlan\":{\"tools\":[\"app.openOrFocus\",\"app.observe\",\"ui.focusSearch\",\"ui.setText\",\"ui.pressReturn\",\"app.verifyCommand\"],\"inputEntity\":\"query\",\"controlID\":\"search\",\"focusKey\":\"Command+F\",\"verification\":\"commandAttempted\"},\"metadata\":{\"appFinder.selectedCapabilityID\":\"play_media\",\"mediaSelection.kind\":\"representative_song\",\"mediaSelection.seed\":\"Coldplay\",\"mediaSelection.selectedTitle\":\"Viva La Vida\",\"mediaSelection.reason\":\"User asked for some Coldplay, so choose a concrete well-known song instead of an artist-only search.\"}}",- "Example website output shape: {\"taskType\":\"local_app_interaction\",\"targetAppName\":\"Safari\",\"entities\":{\"appName\":\"Safari\",\"goal\":\"open requested website\",\"query\":\"https://example.org\"},\"normalizedEntities\":{\"appName\":\"Safari\",\"goal\":\"open requested website\",\"query\":\"https://example.org\"},\"confidence\":0.9,\"needsConfirmation\":false,\"actionPlan\":{\"tools\":[\"app.openOrFocus\",\"app.observe\",\"ui.focusAddressBar\",\"ui.setText\",\"ui.pressReturn\",\"app.verifyCommand\"],\"inputEntity\":\"query\",\"controlID\":\"addressBar\",\"focusKey\":\"Command+L\",\"verification\":\"commandAttempted\"},\"metadata\":{}}",- "Writing output shape: targetAppName=Notes, entities.appName=Notes, entities.goal=write requested text, entities.query=<the actual final text to type>, actionPlan.tools=[app.openOrFocus, app.observe, ui.newDocument, ui.setText, app.verifyCommand], inputEntity=query, controlID=editor.",- "Table output shape: targetAppName=Numbers, entities.appName=Numbers, entities.goal=create requested table, entities.query=<tab-separated rows for the requested table>, actionPlan.tools=[app.openOrFocus, app.observe, ui.newDocument, ui.setText, app.verifyCommand], inputEntity=query, controlID=editor.",- "Conversation output shape: {\"taskType\":\"none\",\"targetAppName\":\"none\",\"entities\":{},\"normalizedEntities\":{},\"confidence\":0,\"needsConfirmation\":false,\"actionPlan\":{\"tools\":[],\"inputEntity\":\"\",\"controlID\":\"\",\"focusKey\":\"\",\"verification\":\"commandAttempted\"},\"metadata\":{\"responseMode\":\"conversation\",\"assistantResponse\":\"Hi! What would you like to work on?\"}}",- "Example malformed request output shape: {\"taskType\":\"none\",\"targetAppName\":\"none\",\"entities\":{},\"normalizedEntities\":{},\"confidence\":0,\"needsConfirmation\":false,\"actionPlan\":{\"tools\":[],\"inputEntity\":\"\",\"controlID\":\"\",\"focusKey\":\"\",\"verification\":\"commandAttempted\"},\"metadata\":{\"responseMode\":\"conversation\",\"assistantResponse\":\"I can help, but I need a clearer thing to write before opening an app.\"}}",- "For every other task type, actionPlan.tools must be empty.",- "For AppleScript-backed capabilities, include compact appleScript.source or appleScript.template metadata only when the provided action is insufficient; prefer task metadata and normalized entities for speed.",- "App finder catalog entries are installed local apps with descriptions, support status, capabilities, and control profiles.",- "When App finder catalog JSON is non-empty and you use local_app_interaction, choose the target app only from a catalog entry with supportStatus=supported and a matching capability.",- "For local_app_interaction with an app finder choice, set targetAppName and entities.appName to the catalog appName, set metadata.appFinder.selectedAppID to the exact catalog appID, metadata.appFinder.selectedCapabilityID to the chosen capability id, and metadata.appFinder.controlProfile to one control profile from that capability.",- "Never select catalog entries with supportStatus=candidate, unsupported, or denied for execution; if no supported app capability fits, choose conversation.",- "Command: \(request.command)",- "Relevant local cache:",- context,- "App finder catalog JSON:",- appFinderCatalog,- "Supported task capabilities:",- tasks- ]- .joined(separator: "\n")- }-- private static let maxGeneratedTokens = 512-- 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 ?? .ollama,- 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- )- }-}--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"]- )- }-- guard 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- ) else {- let baseMetadata = Self.outputDiagnostics(for: outputText)- .merging([- "provider": "donkeyBackend",- "privacy.store": "false"- ]) { current, _ in current }- guard let noTaskMetadata = try? TaskIntentWireCodec.hostedPlanningNoTaskMetadata(- outputText,- parserName: "hosted-responses-v1"- ) else {- return result(- entry: entry,- request: request,- status: .invalidOutput,- validationStatus: "invalid",- latencyMS: latencyMS,- metadata: baseMetadata- )- }- return result(- entry: entry,- request: request,- status: .completed,- validationStatus: "noTaskIntent",- latencyMS: latencyMS,- metadata: baseMetadata.merging(noTaskMetadata) { _, new in new }- )- }-- 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 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 func responseRequest(- entry: AIModelRegistryEntry,- adapterRequest: TaskIntentAdapterRequest- ) -> RemoteInferenceResponseCreateRequest {- RemoteInferenceResponseCreateRequest(- input: .array([- .object([- "role": .string("user"),- "content": .array([- .object([- "type": .string("input_text"),- "text": .string(promptText(for: adapterRequest))- ])- ])- ])- ]),- store: false,- text: [- "format": .object([- "type": .string("json_schema"),- "name": .string(Self.schemaID),- "strict": .bool(true),- "schema": Self.jsonValue(TaskIntentWireCodec.genericHarnessPlanningJsonSchema(taskDefinitions: adapterRequest.taskDefinitions))- ])- ],- metadata: [- "source_trace_id": adapterRequest.sourceTraceID,- "prompt_version": entry.promptVersion- ],- parameters: [- "instructions": .string(Self.instructions),- "temperature": .number(0)- ]- )- }-- private func promptText(for request: TaskIntentAdapterRequest) -> String {- let definitions = (try? JSONEncoder().encode(request.taskDefinitions))- .flatMap { String(data: $0, encoding: .utf8) } ?? "[]"- let appFinderCatalog = taskIntentAppFinderCatalogJSON(request.appFinderCatalog)- return [- "Command: \(request.command)",- "Relevant local cache:",- request.contextSnippets.joined(separator: "\n"),- "App finder catalog JSON:",- appFinderCatalog,- "Supported task definitions JSON:",- definitions- ].joined(separator: "\n")- }-- private static let instructions = [- "Decide whether the user is asking Donkey to run one of the provided local app task definitions.",- "Return strict JSON only using the generic harness planning schema.",- "First decide whether Command is an executable local-app task or a conversation turn.",- "Executable local-app task means all three are clear: action, destination or target app/item, and enough payload to execute safely.",- "Always fill structuredIntent, ambiguityRisk, contextNeeds, planSteps, verificationCriteria, fallbacks, clarificationPolicy, and metadata.",- "If Command is a greeting, conversation, question, malformed request, or lacks a real executable payload, set structuredIntent.route conversation, taskType \"none\", targetAppName \"none\", empty entities and normalizedEntities, confidence 0, needsConfirmation false, no planSteps with toolName values, and metadata.responseMode \"conversation\" with metadata.assistantResponse containing a brief natural-language reply.",- "For supported actions, set structuredIntent.route localAppTask, choose only a provided taskType and target app, and fill entities and normalizedEntities with the concrete values needed by required entity rules.",- "Use the generic local_app_interaction task type for executable local app requests that need a model-planned app workflow and do not have a more specific provided task type.",- "Use ambiguityRisk for safe, recoverable, or dangerous ambiguity. Dangerous ambiguity and missing required details must set structuredIntent.needsConfirmation true, ambiguityRisk.shouldAskBeforeActing true, and clarificationPolicy.shouldAsk true with a specific question.",- "Use contextNeeds for app lookup, memory lookup, screen observation, element discovery, or skill lookup needed before or during execution.",- "Use planSteps for the generic harness plan. Each executable step must name one allowed toolName, with inputEntity/controlID/focusKey filled when that tool needs them. Non-executable reasoning steps should use an empty toolName.",- "Use verificationCriteria for what proves success, fallbacks for safe recovery choices, and clarificationPolicy for when Donkey should stop and ask.",- "For play/listen media requests, treat the turn as executable when a supported play_media capability or media_playback task is available; choose Music or another supported media app, set query to the requested artist/song/album, and do not downgrade it to conversation.",- "For every media playback request, include metadata.mediaSelection.kind. For explicit playable requests use explicit_song, explicit_album, or explicit_playlist. For vague artist-level media requests such as 'play some <artist>', do media-selection planning before returning JSON: pick one concrete playable song or album by that artist using model knowledge, set query to '<selected title> <artist>', and include metadata.mediaSelection.kind=representative_song or representative_album, metadata.mediaSelection.seed=<artist>, metadata.mediaSelection.selectedTitle=<title>, and metadata.mediaSelection.reason. Do not use an artist-only query unless the user explicitly asks to open the artist page, play an artist radio/station, or browse the artist.",- "If visible search results are provided in context for a media request, choose the highest-confidence playable Song row whose artist matches the requested seed; skip Artist, Playlist, category, and different-artist rows.",- "When App finder catalog JSON is non-empty and you use local_app_interaction, choose the target app only from a catalog entry with supportStatus supported and a matching capability. Set metadata.appFinder.selectedAppID to the exact appID, metadata.appFinder.selectedCapabilityID to the capability id, and metadata.appFinder.controlProfile to one declared control profile. Never select candidate, unsupported, or denied entries for execution.",- "For local_app_interaction, select the most likely local app, set targetAppName and entities.appName to the human app name, set entities.goal, and when text must be entered set entities.query plus normalizedEntities.query.",- "For local_app_interaction, fill planSteps with allowed toolName values only: app.openOrFocus, app.observe, ui.newDocument, ui.focusSearch, ui.focusAddressBar, ui.focusTextEntry, ui.setText, ui.pressReturn, app.verifyCommand, app.verifyVisibleText.",- "When ui.setText is present, entities.query and normalizedEntities.query must be non-empty, the step inputEntity should usually be query, and controlID/focusKey should describe the guarded UI strategy.",- "For media playback when media_playback is provided, use taskType=media_playback, targetAppName=Music, entities.query=<concrete playable title plus artist>, normalizedEntities.query=<concrete playable title plus artist>, and metadata.mediaSelection.* when the user gave only an artist/genre/seed.",- "For media playback through generic local_app_interaction, targetAppName=Music, entities.appName=Music, entities.goal=play media, entities.query=<concrete playable title plus artist>, planSteps should use app.openOrFocus, app.observe, ui.focusSearch, ui.setText, ui.pressReturn, app.verifyCommand with inputEntity=query, controlID=search, focusKey=Command+F, metadata.appFinder.selectedCapabilityID=play_media when selected from the app finder catalog, and metadata.mediaSelection.* when the user gave only an artist/genre/seed.",- "For website navigation, choose Safari or the user's browser, set query to the URL, and use planSteps for ui.focusAddressBar, ui.setText, ui.pressReturn, app.verifyCommand.",- "For writing in Notes, choose Notes, make query the complete text to type, and use planSteps for ui.newDocument, ui.setText, app.verifyCommand.",- "For spreadsheet or table creation, choose Numbers, put compact tab-separated table content in query, and use planSteps for ui.newDocument, ui.setText, app.verifyCommand.",- "For every other task type, planSteps should not contain executable toolName values.",- "If no supported capability fits, set structuredIntent.route conversation and taskType \"none\" with a helpful conversational assistantResponse rather than a generic local-action failure.",- "Do not invent task types, unsupported entities, unsupported tools, app scripts, or direct input outside the schema."- ].joined(separator: " ")-- 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? {- if let outputText = value.objectValue?["output_text"]?.stringValue,- !outputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {- return outputText- }-- guard let output = value.objectValue?["output"]?.arrayValue else {- return nil- }- for item in output {- guard let content = item.objectValue?["content"]?.arrayValue else { continue }- for contentItem in content {- guard contentItem.objectValue?["type"]?.stringValue == "output_text",- let text = contentItem.objectValue?["text"]?.stringValue,- !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty- else {- continue- }- return text- }- }- return nil- }-- 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 {- switch value {- case let string as String:- return .string(string)- case let bool as Bool:- return .bool(bool)- case let int as Int:- return .number(Double(int))- case let double as Double:- return .number(double)- case let array as [Any]:- return .array(array.map(jsonValue))- case let object as [String: Any]:- return .object(object.mapValues(jsonValue))- default:- return .null- }- }-- 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- )- }-}--public struct LocalModelTaskIntentResolver: Sendable {- public var catalog: LocalAppTaskCatalog- public var adapter: any TaskIntentParsingAdapter-- public init(- catalog: LocalAppTaskCatalog,- adapter: any TaskIntentParsingAdapter = HostedTaskIntentParsingAdapter()- ) {- self.catalog = catalog- self.adapter = adapter- }-- public func resolve(- command: String,- contextSnippets: [String] = [],- sourceTraceID: String- ) async -> (resolution: LocalAppTaskCatalogResolution, trace: AIModelCallTrace) {- let request = TaskIntentAdapterRequest(- command: command,- taskDefinitions: catalog.taskDefinitions,- contextSnippets: contextSnippets,- appFinderCatalog: catalog.appFinderCatalogEntries(),- sourceTraceID: sourceTraceID- )- let result = await adapter.parseTaskIntent(request)-- guard let intent = result.intent else {- let unavailableReason = result.trace.provider == .donkeyBackend- ? "hostedModelIntentUnavailable"- : "localModelIntentUnavailable"- var metadata = [- "reason": unavailableReason,- "modelCallStatus": result.trace.status.rawValue,- "modelValidationStatus": result.trace.validationStatus- ]- if result.trace.validationStatus == "noTaskIntent" {- metadata["reason"] = "noSupportedTaskIntent"- metadata["responseMode"] = "conversation"- metadata["assistantResponse"] = TaskIntentWireCodec.defaultConversationAssistantResponse- }- for key in ["responseMode", "assistantResponse"] {- if let value = result.trace.metadata[key], !value.isEmpty {- metadata[key] = value- }- }- for key in [- "reason",- "detail",- "error",- "backend.provider",- "http.status",- "http.bodyPreview",- "modelOutput.empty",- "modelOutput.preview",- "sidecar.outputPreview",- "fallback.status",- "fallback.validation",- "fallback.reason",- "fallback.http.status",- "fallback.http.bodyPreview",- "fallback.modelFallback.selectedModelID",- "provider",- "privacy.store"- ] {- if let value = result.trace.metadata[key], !value.isEmpty {- metadata["model.\(key)"] = value- }- }- return (- LocalAppTaskCatalogResolution(- status: .needsConfirmation,- metadata: metadata- ),- result.trace- )- }-- return (catalog.resolve(intent: intent), result.trace)- }-}--private struct LocalGenerateTaskIntentResponse: Decodable {- var response: String?-}--private struct LocalGenerateTagsResponse: Decodable {- var models: [LocalGenerateModelTag]-}--private struct LocalGenerateModelTag: Decodable {- var name: String- var size: Int64?-}--private 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-}--private 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",- "verification"- ],- "properties": [- "tools": [- "type": "array",- "maxItems": 8,- "items": [- "type": "string",- "enum": LocalAppActionPlanTool.allCases.map(\.rawValue)- ]- ],- "inputEntity": ["type": "string"],- "controlID": ["type": "string"],- "focusKey": ["type": "string"],- "verification": [- "type": "string",- "enum": LocalAppActionPlanVerification.allCases.map(\.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"],- "actionPlan": actionPlanSchema,- "metadata": [- "type": "object",- "additionalProperties": ["type": "string"]- ]- ]- ]- }-- static func genericHarnessPlanningJsonSchema(taskDefinitions: [LocalAppTaskDefinition]) -> [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 toolNames = [""] + LocalAppActionPlanTool.allCases.map(\.rawValue)- let planStepSchema: [String: Any] = [- "type": "object",- "additionalProperties": false,- "required": [- "id",- "summary",- "toolName",- "inputEntity",- "controlID",- "focusKey",- "expectedObservation"- ],- "properties": [- "id": ["type": "string"],- "summary": ["type": "string"],- "toolName": ["type": "string", "enum": toolNames],- "inputEntity": ["type": "string"],- "controlID": ["type": "string"],- "focusKey": ["type": "string"],- "expectedObservation": ["type": "string"]- ]- ]-- return [- "type": "object",- "additionalProperties": false,- "required": [- "schemaVersion",- "structuredIntent",- "ambiguityRisk",- "contextNeeds",- "planSteps",- "verificationCriteria",- "fallbacks",- "clarificationPolicy",- "metadata"- ],- "properties": [- "schemaVersion": ["type": "string", "enum": ["generic_harness_planning"]],- "structuredIntent": [- "type": "object",- "additionalProperties": false,- "required": [- "route",- "goal",- "taskType",- "targetAppName",- "entities",- "normalizedEntities",- "confidence",- "needsConfirmation"- ],- "properties": [- "route": [- "type": "string",- "enum": ["localAppTask", "conversation", "clarification"]- ],- "goal": ["type": "string"],- "taskType": ["type": "string", "enum": taskTypes],- "targetAppName": targetAppNameSchema,- "entities": [- "type": "object",- "additionalProperties": ["type": "string"]- ],- "normalizedEntities": [- "type": "object",- "additionalProperties": ["type": "string"]- ],- "confidence": ["type": "number", "minimum": 0, "maximum": 1],- "needsConfirmation": ["type": "boolean"]- ]- ],- "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"]- ]- ],- "contextNeeds": [- "type": "array",- "maxItems": 8,- "items": ["type": "string"]- ],- "planSteps": [- "type": "array",- "maxItems": 12,- "items": planStepSchema- ],- "verificationCriteria": [- "type": "array",- "maxItems": 8,- "items": ["type": "string"]- ],- "fallbacks": [- "type": "array",- "maxItems": 8,- "items": ["type": "string"]- ],- "clarificationPolicy": [- "type": "object",- "additionalProperties": false,- "required": [- "shouldAsk",- "questions",- "policy"- ],- "properties": [- "shouldAsk": ["type": "boolean"],- "questions": [- "type": "array",- "maxItems": 4,- "items": ["type": "string"]- ],- "policy": ["type": "string"]- ]- ],- "metadata": [- "type": "object",- "additionalProperties": ["type": "string"]- ]- ]- ]- }-- 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"- }-- guard mediaSelectionIsValidIfRequired(- definition: definition,- metadata: metadata,- normalizedEntities: normalizedEntities- ) else {- return nil- }-- 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- }-- var confidence = wire.confidence- var needsConfirmation = wire.needsConfirmation || missingRequiredEntity != nil- var actionPlan = wire.actionPlan.tools.isEmpty ? nil : wire.actionPlan- if definition.metadata["modelPlanned"] == "true",- let modelActionPlan = actionPlan {- let repairedPlan = repairedModelActionPlan(- modelActionPlan,- normalizedEntities: normalizedEntities- )- if repairedPlan != modelActionPlan {- metadata["modelPlan.repaired"] = "true"- actionPlan = repairedPlan- }- }- if let tableRepair = repairedSpreadsheetQueryIfNeeded(- actionPlan: actionPlan,- normalizedEntities: normalizedEntities,- wire: wire- ) {- entities[tableRepair.entityName] = tableRepair.text- normalizedEntities[tableRepair.entityName] = tableRepair.text- metadata["modelPlan.repairedTableText"] = "true"- }- if let conversationReason = textInputConversationReason(- actionPlan: actionPlan,- normalizedEntities: normalizedEntities- ) ?? documentConversationReason(- actionPlan: actionPlan,- normalizedEntities: normalizedEntities,- originalCommand: originalCommand- ) {- confidence = min(confidence, 0.2)- needsConfirmation = false- actionPlan = nil- metadata["responseMode"] = "conversation"- metadata["assistantResponse"] = "I can help, but I need a clearer thing to write before opening an app."- metadata["notActionableReason"] = conversationReason- }- 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- 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 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 tools = wire.planSteps.compactMap { step -> LocalAppActionPlanTool? in- let toolName = step.toolName.trimmingCharacters(in: .whitespacesAndNewlines)- guard !toolName.isEmpty else { return nil }- return LocalAppActionPlanTool(rawValue: toolName)- }- let inputEntity = firstNonEmpty(wire.planSteps.map(\.inputEntity)) ?? ""- let controlID = firstNonEmpty(wire.planSteps.map(\.controlID)) ?? ""- let focusKey = firstNonEmpty(wire.planSteps.map(\.focusKey)) ?? ""- let verification: LocalAppActionPlanVerification = wire.planSteps.contains { step in- step.toolName == LocalAppActionPlanTool.verifyVisibleText.rawValue- } || wire.verificationCriteria.contains { criterion in- criterion.localizedCaseInsensitiveContains("visible")- } ? .visibleText : .commandAttempted-- return LocalAppActionPlan(- tools: tools,- inputEntity: inputEntity,- controlID: controlID,- focusKey: focusKey,- verification: verification- )- }-- 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.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,- "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 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[LocalAppTaskIntentParser.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 repairedModelActionPlan(- _ actionPlan: LocalAppActionPlan,- normalizedEntities: [String: String]- ) -> LocalAppActionPlan {- var plan = actionPlan- if plan.inputEntity.isEmpty {- plan.inputEntity = "query"- }- if plan.controlID.isEmpty {- plan.controlID = defaultControlID(for: plan.tools)- }- if plan.focusKey.isEmpty {- plan.focusKey = defaultFocusKey(for: plan.tools)- }-- let inputValue = normalizedEntities[plan.inputEntity] ?? normalizedEntities["query"] ?? ""- guard !plan.isExecutable,- !inputValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty- else {- return plan- }-- if plan.tools.contains(.newDocument) || plan.tools.contains(.focusTextEntry) {- return LocalAppActionPlan(- tools: repairedTools(- from: plan.tools,- appending: [.setText, .verifyCommand]- ),- inputEntity: plan.inputEntity,- controlID: plan.controlID,- focusKey: plan.focusKey,- verification: plan.verification- )- }-- if plan.tools.contains(.focusAddressBar) {- return LocalAppActionPlan(- tools: repairedTools(- from: plan.tools,- appending: [.setText, .pressReturn, .verifyCommand]- ),- inputEntity: plan.inputEntity,- controlID: plan.controlID,- focusKey: plan.focusKey,- verification: plan.verification- )- }-- return LocalAppActionPlan(- tools: LocalAppActionPlan.defaultSearchSubmitPlan.tools,- inputEntity: plan.inputEntity,- controlID: plan.controlID,- focusKey: plan.focusKey,- verification: plan.verification- )- }-- private static func defaultControlID(for tools: [LocalAppActionPlanTool]) -> String {- if tools.contains(.focusAddressBar) {- return "addressBar"- }- if tools.contains(.focusTextEntry) || tools.contains(.newDocument) {- return "editor"- }- return "search"- }-- private static func defaultFocusKey(for tools: [LocalAppActionPlanTool]) -> String {- if tools.contains(.focusAddressBar) {- return "Command+L"- }- if tools.contains(.focusTextEntry) || tools.contains(.newDocument) {- return ""- }- return "Command+F"- }-- private static func repairedTools(- from tools: [LocalAppActionPlanTool],- appending repairTools: [LocalAppActionPlanTool]- ) -> [LocalAppActionPlanTool] {- var repaired = tools- for tool in repairTools where !repaired.contains(tool) {- repaired.append(tool)- }- return repaired- }-- private static func repairedSpreadsheetQueryIfNeeded(- actionPlan: LocalAppActionPlan?,- normalizedEntities: [String: String],- wire: TaskIntentWire- ) -> (entityName: String, text: String)? {- guard let actionPlan,- actionPlan.tools.contains(.newDocument),- actionPlan.tools.contains(.setText)- else {- return nil- }-- let appName = normalizedEntities["appName"] ?? wire.entities["appName"] ?? wire.targetAppName- guard LocalAppTaskIntentParser.normalizedPhrase(appName) == "numbers" else {- return nil- }-- let entityName = actionPlan.inputEntity.isEmpty ? "query" : actionPlan.inputEntity- let query = (normalizedEntities[entityName] ?? normalizedEntities["query"] ?? "")- .trimmingCharacters(in: .whitespacesAndNewlines)- guard !query.isEmpty,- !query.contains("\n"),- !query.contains("\t")- else {- return nil- }-- let subject = query- .replacingOccurrences(of: "\n", with: " ")- .replacingOccurrences(of: "\t", with: " ")- .trimmingCharacters(in: .whitespacesAndNewlines)- guard !subject.isEmpty else { return nil }-- let clippedSubject = String(subject.prefix(160))- return (- entityName,- "Request\tStatus\n\(clippedSubject)\tNeeds table data"- )- }-- private static func textInputConversationReason(- actionPlan: LocalAppActionPlan?,- normalizedEntities: [String: String]- ) -> String? {- guard let actionPlan,- actionPlan.requiresTextInput- else {- return nil- }-- let entityName = actionPlan.inputEntity.isEmpty ? "query" : actionPlan.inputEntity- let query = (normalizedEntities[entityName] ?? normalizedEntities["query"] ?? "")- .trimmingCharacters(in: .whitespacesAndNewlines)- if query.isEmpty {- return "missingTextPayload"- }- if isCopiedPromptPlaceholder(query) {- return "promptPlaceholderPayload"- }-- return nil- }-- private static func mediaSelectionIsValidIfRequired(- definition: LocalAppTaskDefinition,- metadata: [String: String],- normalizedEntities: [String: String]- ) -> Bool {- let capabilityID = metadata["appFinder.selectedCapabilityID"]- ?? metadata["selectedCapabilityID"]- ?? ""- let requiresMediaSelection = capabilityID == "play_media"- || definition.metadata["verificationMode"] == "playbackCommandAttempted"- guard requiresMediaSelection else { return true }-- guard let kind = nonEmpty(metadata["mediaSelection.kind"])?.lowercased() else {- return false- }- let blockedKinds: Set<String> = [- "artist",- "artist_only",- "artist_page",- "browse_artist"- ]- guard !blockedKinds.contains(kind) else { return false }-- let queryEntity = definition.verificationEntityName ?? "query"- guard let query = nonEmpty(normalizedEntities[queryEntity] ?? normalizedEntities["query"]) else {- return false- }-- if let seed = nonEmpty(metadata["mediaSelection.seed"]),- LocalAppTaskIntentParser.normalizedPhrase(query) == LocalAppTaskIntentParser.normalizedPhrase(seed) {- return false- }-- if kind.contains("representative") {- return nonEmpty(metadata["mediaSelection.selectedTitle"]) != nil- }-- return true- }-- private static func documentConversationReason(- actionPlan: LocalAppActionPlan?,- normalizedEntities: [String: String],- originalCommand: String- ) -> String? {- guard let actionPlan,- actionPlan.tools.contains(.newDocument),- actionPlan.tools.contains(.setText),- !actionPlan.tools.contains(.pressReturn)- else {- return nil- }-- let entityName = actionPlan.inputEntity.isEmpty ? "query" : actionPlan.inputEntity- let query = (normalizedEntities[entityName] ?? normalizedEntities["query"] ?? "")- .trimmingCharacters(in: .whitespacesAndNewlines)- guard !query.isEmpty,- !commandContainsQuoted(query, originalCommand: originalCommand),- !query.contains("\n"),- !query.contains("\t"),- query.rangeOfCharacter(from: CharacterSet(charactersIn: ".?!:;,")) == nil- else {- return nil- }-- let words = LocalAppTaskIntentParser.normalizedPhrase(query)- .split(separator: " ")- return words.count <= 5 ? "insufficientDocumentPayload" : nil- }-- private static func isCopiedPromptPlaceholder(_ query: String) -> Bool {- let normalizedQuery = LocalAppTaskIntentParser.normalizedPhrase(query)- guard !normalizedQuery.isEmpty else { return false }-- return copiedPromptPayloadPhrases.contains { phrase in- normalizedQuery.contains(LocalAppTaskIntentParser.normalizedPhrase(phrase))- }- }-- private static let copiedPromptPayloadPhrases = [- "complete piece of text generated for the user writing request",- "complete piece of text generated for the user's writing request",- "generated for the user writing request",- "the actual final text to type",- "tab separated rows for the requested table",- "column a column b row label value or data needed note"- ]-- private static func commandContainsQuoted(- _ query: String,- originalCommand: String- ) -> Bool {- let trimmedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)- guard !trimmedQuery.isEmpty else { return false }- let quotedPatterns = [- "\"\(trimmedQuery)\"",- "'\(trimmedQuery)'",- "`\(trimmedQuery)`"- ]- return quotedPatterns.contains { originalCommand.localizedCaseInsensitiveContains($0) }- }-- 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- LocalAppTaskIntentParser.normalizedPhrase(candidate)- == LocalAppTaskIntentParser.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 {- LocalAppTaskIntentParser.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 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 struct GenericHarnessAmbiguityRiskWire: Decodable {- var ambiguityClass: String- var riskLevel: String- var missingInformation: [String]- var shouldAskBeforeActing: Bool-}--private struct GenericHarnessPlanStepWire: Decodable {- var id: String- var summary: String- var toolName: String- var inputEntity: String- var controlID: String- var focusKey: String- var expectedObservation: String-}--private struct GenericHarnessClarificationPolicyWire: Decodable {- var shouldAsk: Bool- var questions: [String]- var policy: String-}--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]-}--private extension LocalGenerateTaskIntentAdapter {- static func outputText(from data: Data) throws -> String? {- try JSONDecoder().decode(LocalGenerateTaskIntentResponse.self, from: data).response- }-}--private extension RemoteInferenceJSONValue {- var objectValue: [String: RemoteInferenceJSONValue]? {- if case .object(let value) = self {- return value- }- return nil- }-- var arrayValue: [RemoteInferenceJSONValue]? {- if case .array(let value) = self {- return value- }- return nil- }-- var stringValue: String? {- if case .string(let value) = self {- return value- }- return nil- }-}diff --git a/apps/Donkey/Sources/DonkeyAI/LocalModelTaskIntentResolver.swift b/apps/Donkey/Sources/DonkeyAI/LocalModelTaskIntentResolver.swiftnew file mode 100644index 00000000..64f31548--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/LocalModelTaskIntentResolver.swift@@ -0,0 +1,83 @@+import DonkeyContracts+import DonkeyRuntime+import Foundation++public struct LocalModelTaskIntentResolver: Sendable {+ public var catalog: LocalAppTaskCatalog+ public var adapter: any TaskIntentParsingAdapter++ public init(+ catalog: LocalAppTaskCatalog,+ adapter: any TaskIntentParsingAdapter = HostedTaskIntentParsingAdapter()+ ) {+ self.catalog = catalog+ self.adapter = adapter+ }++ public func resolve(+ command: String,+ contextSnippets: [String] = [],+ sourceTraceID: String+ ) async -> (resolution: LocalAppTaskCatalogResolution, trace: AIModelCallTrace) {+ let request = TaskIntentAdapterRequest(+ command: command,+ taskDefinitions: catalog.taskDefinitions,+ contextSnippets: contextSnippets,+ appFinderCatalog: catalog.appFinderCatalogEntries(),+ sourceTraceID: sourceTraceID+ )+ let result = await adapter.parseTaskIntent(request)++ guard let intent = result.intent else {+ let unavailableReason = result.trace.provider == .donkeyBackend+ ? "hostedModelIntentUnavailable"+ : "localModelIntentUnavailable"+ var metadata = [+ "reason": unavailableReason,+ "modelCallStatus": result.trace.status.rawValue,+ "modelValidationStatus": result.trace.validationStatus+ ]+ if result.trace.validationStatus == "noTaskIntent" {+ metadata["reason"] = "noSupportedTaskIntent"+ metadata["responseMode"] = "conversation"+ metadata["assistantResponse"] = TaskIntentWireCodec.defaultConversationAssistantResponse+ }+ for key in ["responseMode", "assistantResponse"] {+ if let value = result.trace.metadata[key], !value.isEmpty {+ metadata[key] = value+ }+ }+ for key in [+ "reason",+ "detail",+ "error",+ "backend.provider",+ "http.status",+ "http.bodyPreview",+ "modelOutput.empty",+ "modelOutput.preview",+ "sidecar.outputPreview",+ "fallback.status",+ "fallback.validation",+ "fallback.reason",+ "fallback.http.status",+ "fallback.http.bodyPreview",+ "provider",+ "privacy.store"+ ] {+ if let value = result.trace.metadata[key], !value.isEmpty {+ metadata["model.\(key)"] = value+ }+ }+ return (+ LocalAppTaskCatalogResolution(+ status: .needsConfirmation,+ metadata: metadata+ ),+ result.trace+ )+ }++ return (catalog.resolve(intent: intent), result.trace)+ }+}diff --git a/apps/Donkey/Sources/DonkeyAI/ProcessBackedLocalLLMTaskIntentAdapter.swift b/apps/Donkey/Sources/DonkeyAI/ProcessBackedLocalLLMTaskIntentAdapter.swiftnew file mode 100644index 00000000..88c87f40--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/ProcessBackedLocalLLMTaskIntentAdapter.swift@@ -0,0 +1,285 @@+import DonkeyContracts+import DonkeyRuntime+import Foundation++public struct ProcessBackedLocalLLMTaskIntentAdapter: TaskIntentParsingAdapter {+ public static let schemaID = "task_intent_v1"++ public var router: AIModelRouter+ public var sidecarRunner: any LocalJSONSidecarRunning+ public var encoder: JSONEncoder+ public var decoder: JSONDecoder++ public init(+ router: AIModelRouter = AIModelRouter(registry: .defaultHybridPlanner),+ sidecarRunner: any LocalJSONSidecarRunning = ProcessBackedLocalJSONSidecarRunner(),+ encoder: JSONEncoder = JSONEncoder(),+ decoder: JSONDecoder = JSONDecoder()+ ) {+ self.router = router+ self.sidecarRunner = sidecarRunner+ self.encoder = encoder+ self.decoder = decoder+ }++ public func parseTaskIntent(+ _ request: TaskIntentAdapterRequest+ ) async -> TaskIntentAdapterResult {+ let entry: AIModelRegistryEntry+ do {+ entry = try router.route(request.routeRequest.limitingProviders([.localRuntime]))+ } catch {+ return result(+ entry: nil,+ request: request,+ status: .invalidOutput,+ validationStatus: "routingFailed",+ latencyMS: nil,+ metadata: ["error": String(describing: error)]+ )+ }++ let input = LocalLLMTaskIntentSidecarRequest(+ command: request.command,+ taskDefinitions: request.taskDefinitions,+ contextSnippets: request.contextSnippets,+ skillSnippets: request.skillSnippets,+ appFinderCatalog: request.appFinderCatalog,+ sourceTraceID: request.sourceTraceID,+ modelID: entry.modelID,+ cacheDirectory: LocalModelRuntimeExecutableResolver().modelCacheDirectoryPath(+ environmentVariableName: "DONKEY_LOCAL_LLM_RUNNER"+ ),+ metadata: [+ "schemaID": Self.schemaID,+ "promptVersion": entry.promptVersion+ ]+ )+ let result = await sidecarRunner.run(+ LocalJSONSidecarRequest(+ environmentVariableName: "DONKEY_LOCAL_LLM_RUNNER",+ inputData: (try? encoder.encode(input)) ?? Data(),+ timeoutMS: entry.timeoutMS,+ metadata: [+ "sidecar.role": "taskIntent",+ "modelID": entry.modelID+ ]+ )+ )++ guard result.status == .completed else {+ return self.result(+ entry: entry,+ request: request,+ status: result.status == .timedOut ? .timeout : .providerOutage,+ validationStatus: "notValidated",+ latencyMS: result.latencyMS,+ metadata: result.metadata.merging([+ "sidecar.stderr": result.stderrText+ ]) { current, _ in current }+ )+ }++ do {+ let response = try decoder.decode(LocalLLMTaskIntentSidecarResponse.self, from: result.outputData)+ let responseMetadata = result.metadata+ .merging(response.metadata) { current, _ in current }+ .merging(Self.outputDiagnostics(for: response.outputText)) { current, _ in current }+ if response.outputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,+ response.metadata["reason"] != nil {+ return self.result(+ entry: entry,+ request: request,+ status: .providerOutage,+ validationStatus: "notValidated",+ latencyMS: result.latencyMS,+ metadata: responseMetadata+ )+ }++ guard let intent = try TaskIntentWireCodec.decodeIntent(+ response.outputText,+ definitions: request.taskDefinitions,+ originalCommand: request.command,+ appFinderCatalog: request.appFinderCatalog,+ sourceModelCallID: "model-call-\(request.sourceTraceID)",+ parserName: "local-llm-sidecar-v1"+ ) else {+ if let noTaskMetadata = try? TaskIntentWireCodec.noTaskMetadata(+ response.outputText,+ parserName: "local-llm-sidecar-v1"+ ) {+ return self.result(+ entry: entry,+ request: request,+ status: .completed,+ validationStatus: "noTaskIntent",+ latencyMS: result.latencyMS,+ metadata: responseMetadata.merging(noTaskMetadata) { _, new in new }+ )+ }+ return self.result(+ entry: entry,+ request: request,+ status: .invalidOutput,+ validationStatus: "invalid",+ latencyMS: result.latencyMS,+ metadata: responseMetadata+ )+ }++ return TaskIntentAdapterResult(+ intent: intent,+ trace: trace(+ entry: entry,+ request: request,+ status: .completed,+ validationStatus: "schemaDecoded",+ latencyMS: result.latencyMS,+ metadata: responseMetadata+ )+ )+ } catch {+ if let sidecarError = decodeSidecarError(+ result.outputData,+ entry: entry,+ request: request,+ sidecarResult: result,+ decodeError: error+ ) {+ return sidecarError+ }++ return self.result(+ entry: entry,+ request: request,+ status: .invalidOutput,+ validationStatus: "invalid",+ latencyMS: result.latencyMS,+ metadata: result.metadata.merging([+ "error": String(describing: error),+ "sidecar.outputPreview": Self.preview(result.outputData, maxCharacters: 240)+ ]) { current, _ in current }+ )+ }+ }++ private func decodeSidecarError(+ _ data: Data,+ entry: AIModelRegistryEntry,+ request: TaskIntentAdapterRequest,+ sidecarResult: LocalJSONSidecarResult,+ decodeError: Error+ ) -> TaskIntentAdapterResult? {+ guard let errorResponse = try? decoder.decode(LocalLLMTaskIntentSidecarErrorResponse.self, from: data),+ errorResponse.status == "error" || errorResponse.metadata["reason"] != nil+ else {+ return nil+ }++ return result(+ entry: entry,+ request: request,+ status: .providerOutage,+ validationStatus: "notValidated",+ latencyMS: sidecarResult.latencyMS,+ metadata: sidecarResult.metadata.merging(+ errorResponse.metadata.merging([+ "sidecar.status": errorResponse.status,+ "decode.error": String(describing: decodeError)+ ]) { current, _ in current }+ ) { current, _ in current }+ )+ }++ 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 preview(_ data: Data, maxCharacters: Int) -> String {+ preview(String(decoding: data, as: UTF8.self), maxCharacters: maxCharacters)+ }++ 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 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 ?? .localRuntime,+ 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 LocalLLMTaskIntentSidecarRequest: Codable, Equatable, Sendable {+ var command: String+ var taskDefinitions: [LocalAppTaskDefinition]+ var contextSnippets: [String]+ var skillSnippets: [String]+ var appFinderCatalog: [LocalAppFinderCatalogEntry]+ var sourceTraceID: String+ var modelID: String+ var cacheDirectory: String?+ var metadata: [String: String]+}++private struct LocalLLMTaskIntentSidecarResponse: Codable, Equatable, Sendable {+ var outputText: String+ var metadata: [String: String]+}++private struct LocalLLMTaskIntentSidecarErrorResponse: Codable, Equatable, Sendable {+ var status: String+ var metadata: [String: String]+}diff --git a/apps/Donkey/Sources/DonkeyAI/TaskIntentParsingAdapter.swift b/apps/Donkey/Sources/DonkeyAI/TaskIntentParsingAdapter.swiftnew file mode 100644index 00000000..e3a13c9c--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/TaskIntentParsingAdapter.swift@@ -0,0 +1,113 @@+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 sourceTraceID: String+ public var routeRequest: AIModelRouteRequest++ public init(+ command: String,+ taskDefinitions: [LocalAppTaskDefinition],+ contextSnippets: [String] = [],+ skillSnippets: [String]? = nil,+ appFinderCatalog: [LocalAppFinderCatalogEntry] = [],+ 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.skillSnippets = TaskIntentModelContextCompactor(+ maxSnippets: 8,+ maxSnippetCharacters: 1_200,+ maxTotalCharacters: 6_400+ ).compact(+ skillSnippets ?? LocalAppTaskSkillContext.defaultContext(+ 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.swiftnew file mode 100644index 00000000..a4a5f9e6--- /dev/null+++ b/apps/Donkey/Sources/DonkeyAI/TaskIntentWireCodec.swift@@ -0,0 +1,1133 @@+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",+ "verification"+ ],+ "properties": [+ "tools": [+ "type": "array",+ "maxItems": 8,+ "items": [+ "type": "string",+ "enum": LocalAppActionPlanTool.allCases.map(\.rawValue)+ ]+ ],+ "inputEntity": ["type": "string"],+ "controlID": ["type": "string"],+ "focusKey": ["type": "string"],+ "verification": [+ "type": "string",+ "enum": LocalAppActionPlanVerification.allCases.map(\.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"],+ "actionPlan": actionPlanSchema,+ "metadata": [+ "type": "object",+ "additionalProperties": ["type": "string"]+ ]+ ]+ ]+ }++ static func genericHarnessPlanningJsonSchema(taskDefinitions: [LocalAppTaskDefinition]) -> [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 toolNames = [""] + LocalAppActionPlanTool.allCases.map(\.rawValue)+ let planStepSchema: [String: Any] = [+ "type": "object",+ "additionalProperties": false,+ "required": [+ "id",+ "summary",+ "toolName",+ "inputEntity",+ "controlID",+ "focusKey",+ "expectedObservation"+ ],+ "properties": [+ "id": ["type": "string"],+ "summary": ["type": "string"],+ "toolName": ["type": "string", "enum": toolNames],+ "inputEntity": ["type": "string"],+ "controlID": ["type": "string"],+ "focusKey": ["type": "string"],+ "expectedObservation": ["type": "string"]+ ]+ ]++ return [+ "type": "object",+ "additionalProperties": false,+ "required": [+ "schemaVersion",+ "structuredIntent",+ "ambiguityRisk",+ "contextNeeds",+ "planSteps",+ "verificationCriteria",+ "fallbacks",+ "clarificationPolicy",+ "metadata"+ ],+ "properties": [+ "schemaVersion": ["type": "string", "enum": ["generic_harness_planning"]],+ "structuredIntent": [+ "type": "object",+ "additionalProperties": false,+ "required": [+ "route",+ "goal",+ "taskType",+ "targetAppName",+ "entities",+ "normalizedEntities",+ "confidence",+ "needsConfirmation"+ ],+ "properties": [+ "route": [+ "type": "string",+ "enum": ["localAppTask", "conversation", "clarification"]+ ],+ "goal": ["type": "string"],+ "taskType": ["type": "string", "enum": taskTypes],+ "targetAppName": targetAppNameSchema,+ "entities": [+ "type": "object",+ "additionalProperties": ["type": "string"]+ ],+ "normalizedEntities": [+ "type": "object",+ "additionalProperties": ["type": "string"]+ ],+ "confidence": ["type": "number", "minimum": 0, "maximum": 1],+ "needsConfirmation": ["type": "boolean"]+ ]+ ],+ "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"]+ ]+ ],+ "contextNeeds": [+ "type": "array",+ "maxItems": 8,+ "items": ["type": "string"]+ ],+ "planSteps": [+ "type": "array",+ "maxItems": 12,+ "items": planStepSchema+ ],+ "verificationCriteria": [+ "type": "array",+ "maxItems": 8,+ "items": ["type": "string"]+ ],+ "fallbacks": [+ "type": "array",+ "maxItems": 8,+ "items": ["type": "string"]+ ],+ "clarificationPolicy": [+ "type": "object",+ "additionalProperties": false,+ "required": [+ "shouldAsk",+ "questions",+ "policy"+ ],+ "properties": [+ "shouldAsk": ["type": "boolean"],+ "questions": [+ "type": "array",+ "maxItems": 4,+ "items": ["type": "string"]+ ],+ "policy": ["type": "string"]+ ]+ ],+ "metadata": [+ "type": "object",+ "additionalProperties": ["type": "string"]+ ]+ ]+ ]+ }++ 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"+ }++ guard mediaSelectionIsValidIfRequired(+ definition: definition,+ metadata: metadata,+ normalizedEntities: normalizedEntities+ ) else {+ return nil+ }++ 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+ }++ var confidence = wire.confidence+ var needsConfirmation = wire.needsConfirmation || missingRequiredEntity != nil+ var actionPlan = wire.actionPlan.tools.isEmpty ? nil : wire.actionPlan+ if definition.metadata["modelPlanned"] == "true",+ let modelActionPlan = actionPlan {+ let repairedPlan = repairedModelActionPlan(+ modelActionPlan,+ normalizedEntities: normalizedEntities+ )+ if repairedPlan != modelActionPlan {+ metadata["modelPlan.repaired"] = "true"+ actionPlan = repairedPlan+ }+ }+ if let tableRepair = repairedSpreadsheetQueryIfNeeded(+ actionPlan: actionPlan,+ normalizedEntities: normalizedEntities,+ wire: wire+ ) {+ entities[tableRepair.entityName] = tableRepair.text+ normalizedEntities[tableRepair.entityName] = tableRepair.text+ metadata["modelPlan.repairedTableText"] = "true"+ }+ if let conversationReason = textInputConversationReason(+ actionPlan: actionPlan,+ normalizedEntities: normalizedEntities+ ) ?? documentConversationReason(+ actionPlan: actionPlan,+ normalizedEntities: normalizedEntities,+ originalCommand: originalCommand+ ) {+ confidence = min(confidence, 0.2)+ needsConfirmation = false+ actionPlan = nil+ metadata["responseMode"] = "conversation"+ metadata["assistantResponse"] = "I can help, but I need a clearer thing to write before opening an app."+ metadata["notActionableReason"] = conversationReason+ }+ 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+ 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 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 tools = wire.planSteps.compactMap { step -> LocalAppActionPlanTool? in+ let toolName = step.toolName.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !toolName.isEmpty else { return nil }+ return LocalAppActionPlanTool(rawValue: toolName)+ }+ let inputEntity = firstNonEmpty(wire.planSteps.map(\.inputEntity)) ?? ""+ let controlID = firstNonEmpty(wire.planSteps.map(\.controlID)) ?? ""+ let focusKey = firstNonEmpty(wire.planSteps.map(\.focusKey)) ?? ""+ let verification: LocalAppActionPlanVerification = wire.planSteps.contains { step in+ step.toolName == LocalAppActionPlanTool.verifyVisibleText.rawValue+ } || wire.verificationCriteria.contains { criterion in+ criterion.localizedCaseInsensitiveContains("visible")+ } ? .visibleText : .commandAttempted++ return LocalAppActionPlan(+ tools: tools,+ inputEntity: inputEntity,+ controlID: controlID,+ focusKey: focusKey,+ verification: verification+ )+ }++ 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.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,+ "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 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[LocalAppTaskIntentParser.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 repairedModelActionPlan(+ _ actionPlan: LocalAppActionPlan,+ normalizedEntities: [String: String]+ ) -> LocalAppActionPlan {+ var plan = actionPlan+ if plan.inputEntity.isEmpty {+ plan.inputEntity = "query"+ }+ if plan.controlID.isEmpty {+ plan.controlID = defaultControlID(for: plan.tools)+ }+ if plan.focusKey.isEmpty {+ plan.focusKey = defaultFocusKey(for: plan.tools)+ }++ let inputValue = normalizedEntities[plan.inputEntity] ?? normalizedEntities["query"] ?? ""+ guard !plan.isExecutable,+ !inputValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ else {+ return plan+ }++ if plan.tools.contains(.newDocument) || plan.tools.contains(.focusTextEntry) {+ return LocalAppActionPlan(+ tools: repairedTools(+ from: plan.tools,+ appending: [.setText, .verifyCommand]+ ),+ inputEntity: plan.inputEntity,+ controlID: plan.controlID,+ focusKey: plan.focusKey,+ verification: plan.verification+ )+ }++ if plan.tools.contains(.focusAddressBar) {+ return LocalAppActionPlan(+ tools: repairedTools(+ from: plan.tools,+ appending: [.setText, .pressReturn, .verifyCommand]+ ),+ inputEntity: plan.inputEntity,+ controlID: plan.controlID,+ focusKey: plan.focusKey,+ verification: plan.verification+ )+ }++ return LocalAppActionPlan(+ tools: LocalAppActionPlan.defaultSearchSubmitPlan.tools,+ inputEntity: plan.inputEntity,+ controlID: plan.controlID,+ focusKey: plan.focusKey,+ verification: plan.verification+ )+ }++ private static func defaultControlID(for tools: [LocalAppActionPlanTool]) -> String {+ if tools.contains(.focusAddressBar) {+ return "addressBar"+ }+ if tools.contains(.focusTextEntry) || tools.contains(.newDocument) {+ return "editor"+ }+ return "search"+ }++ private static func defaultFocusKey(for tools: [LocalAppActionPlanTool]) -> String {+ if tools.contains(.focusAddressBar) {+ return "Command+L"+ }+ if tools.contains(.focusTextEntry) || tools.contains(.newDocument) {+ return ""+ }+ return "Command+F"+ }++ private static func repairedTools(+ from tools: [LocalAppActionPlanTool],+ appending repairTools: [LocalAppActionPlanTool]+ ) -> [LocalAppActionPlanTool] {+ var repaired = tools+ for tool in repairTools where !repaired.contains(tool) {+ repaired.append(tool)+ }+ return repaired+ }++ private static func repairedSpreadsheetQueryIfNeeded(+ actionPlan: LocalAppActionPlan?,+ normalizedEntities: [String: String],+ wire: TaskIntentWire+ ) -> (entityName: String, text: String)? {+ guard let actionPlan,+ actionPlan.tools.contains(.newDocument),+ actionPlan.tools.contains(.setText)+ else {+ return nil+ }++ let appName = normalizedEntities["appName"] ?? wire.entities["appName"] ?? wire.targetAppName+ guard LocalAppTaskIntentParser.normalizedPhrase(appName) == "numbers" else {+ return nil+ }++ let entityName = actionPlan.inputEntity.isEmpty ? "query" : actionPlan.inputEntity+ let query = (normalizedEntities[entityName] ?? normalizedEntities["query"] ?? "")+ .trimmingCharacters(in: .whitespacesAndNewlines)+ guard !query.isEmpty,+ !query.contains("\n"),+ !query.contains("\t")+ else {+ return nil+ }++ let subject = query+ .replacingOccurrences(of: "\n", with: " ")+ .replacingOccurrences(of: "\t", with: " ")+ .trimmingCharacters(in: .whitespacesAndNewlines)+ guard !subject.isEmpty else { return nil }++ let clippedSubject = String(subject.prefix(160))+ return (+ entityName,+ "Request\tStatus\n\(clippedSubject)\tNeeds table data"+ )+ }++ private static func textInputConversationReason(+ actionPlan: LocalAppActionPlan?,+ normalizedEntities: [String: String]+ ) -> String? {+ guard let actionPlan,+ actionPlan.requiresTextInput+ else {+ return nil+ }++ let entityName = actionPlan.inputEntity.isEmpty ? "query" : actionPlan.inputEntity+ let query = (normalizedEntities[entityName] ?? normalizedEntities["query"] ?? "")+ .trimmingCharacters(in: .whitespacesAndNewlines)+ if query.isEmpty {+ return "missingTextPayload"+ }+ if isCopiedPromptPlaceholder(query) {+ return "promptPlaceholderPayload"+ }++ return nil+ }++ private static func mediaSelectionIsValidIfRequired(+ definition: LocalAppTaskDefinition,+ metadata: [String: String],+ normalizedEntities: [String: String]+ ) -> Bool {+ let capabilityID = metadata["appFinder.selectedCapabilityID"]+ ?? metadata["selectedCapabilityID"]+ ?? ""+ let requiresMediaSelection = capabilityID == "play_media"+ || definition.metadata["verificationMode"] == "playbackCommandAttempted"+ guard requiresMediaSelection else { return true }++ guard let kind = nonEmpty(metadata["mediaSelection.kind"])?.lowercased() else {+ return false+ }+ let blockedKinds: Set<String> = [+ "artist",+ "artist_only",+ "artist_page",+ "browse_artist"+ ]+ guard !blockedKinds.contains(kind) else { return false }++ let queryEntity = definition.verificationEntityName ?? "query"+ guard let query = nonEmpty(normalizedEntities[queryEntity] ?? normalizedEntities["query"]) else {+ return false+ }++ if let seed = nonEmpty(metadata["mediaSelection.seed"]),+ LocalAppTaskIntentParser.normalizedPhrase(query) == LocalAppTaskIntentParser.normalizedPhrase(seed) {+ return false+ }++ if kind.contains("representative") {+ return nonEmpty(metadata["mediaSelection.selectedTitle"]) != nil+ }++ return true+ }++ private static func documentConversationReason(+ actionPlan: LocalAppActionPlan?,+ normalizedEntities: [String: String],+ originalCommand: String+ ) -> String? {+ guard let actionPlan,+ actionPlan.tools.contains(.newDocument),+ actionPlan.tools.contains(.setText),+ !actionPlan.tools.contains(.pressReturn)+ else {+ return nil+ }++ let entityName = actionPlan.inputEntity.isEmpty ? "query" : actionPlan.inputEntity+ let query = (normalizedEntities[entityName] ?? normalizedEntities["query"] ?? "")+ .trimmingCharacters(in: .whitespacesAndNewlines)+ guard !query.isEmpty,+ !commandContainsQuoted(query, originalCommand: originalCommand),+ !query.contains("\n"),+ !query.contains("\t"),+ query.rangeOfCharacter(from: CharacterSet(charactersIn: ".?!:;,")) == nil+ else {+ return nil+ }++ let words = LocalAppTaskIntentParser.normalizedPhrase(query)+ .split(separator: " ")+ return words.count <= 5 ? "insufficientDocumentPayload" : nil+ }++ private static func isCopiedPromptPlaceholder(_ query: String) -> Bool {+ let normalizedQuery = LocalAppTaskIntentParser.normalizedPhrase(query)+ guard !normalizedQuery.isEmpty else { return false }++ return copiedPromptPayloadPhrases.contains { phrase in+ normalizedQuery.contains(LocalAppTaskIntentParser.normalizedPhrase(phrase))+ }+ }++ private static let copiedPromptPayloadPhrases = [+ "complete piece of text generated for the user writing request",+ "complete piece of text generated for the user's writing request",+ "generated for the user writing request",+ "the actual final text to type",+ "tab separated rows for the requested table",+ "column a column b row label value or data needed note"+ ]++ private static func commandContainsQuoted(+ _ query: String,+ originalCommand: String+ ) -> Bool {+ let trimmedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !trimmedQuery.isEmpty else { return false }+ let quotedPatterns = [+ "\"\(trimmedQuery)\"",+ "'\(trimmedQuery)'",+ "`\(trimmedQuery)`"+ ]+ return quotedPatterns.contains { originalCommand.localizedCaseInsensitiveContains($0) }+ }++ 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+ LocalAppTaskIntentParser.normalizedPhrase(candidate)+ == LocalAppTaskIntentParser.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 {+ LocalAppTaskIntentParser.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 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 struct GenericHarnessAmbiguityRiskWire: Decodable {+ var ambiguityClass: String+ var riskLevel: String+ var missingInformation: [String]+ var shouldAskBeforeActing: Bool+}++private struct GenericHarnessPlanStepWire: Decodable {+ var id: String+ var summary: String+ var toolName: String+ var inputEntity: String+ var controlID: String+ var focusKey: String+ var expectedObservation: String+}++private struct GenericHarnessClarificationPolicyWire: Decodable {+ var shouldAsk: Bool+ var questions: [String]+ var policy: String+}++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/DonkeyHarness/GenericHarnessSkillRegistry.swift b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessSkillRegistry.swiftindex 9aeff254..9421eefc 100644--- a/apps/Donkey/Sources/DonkeyHarness/GenericHarnessSkillRegistry.swift+++ b/apps/Donkey/Sources/DonkeyHarness/GenericHarnessSkillRegistry.swift@@ -233,13 +233,16 @@ public actor HarnessSkillRegistry {public struct HarnessSkillFileSystemSource: Sendable {public var roots: [URL]public var maxDepth: Int+ public var sourceKind: HarnessSkillSourceKindpublic init(roots: [URL],- maxDepth: Int = 4+ maxDepth: Int = 4,+ sourceKind: HarnessSkillSourceKind = .userDirectory) {self.roots = rootsself.maxDepth = max(0, maxDepth)+ self.sourceKind = sourceKind}public func discover() -> [HarnessSkillDescriptor] {@@ -318,13 +321,13 @@ public struct HarnessSkillFileSystemSource: Sendable {name: name,summary: summary,description: contents,- sourceKind: .userDirectory,+ sourceKind: sourceKind,instructionPath: url.path,tags: tags,providedToolNames: toolNames,scripts: scriptDescriptors(in: directory),metadata: [- "source": "filesystem",+ "source": sourceKind == .builtIn ? "builtInFilesystem" : "filesystem","directory": directory.path])diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swiftindex 1abca9e8..ac56318d 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift@@ -1170,7 +1170,7 @@ public struct LocalAppTaskCatalog: Sendable {}public static func genericAppOpenDefinition(target: LocalAppTarget) -> LocalAppTaskDefinition {- LocalAppTaskDefinition(+ return LocalAppTaskDefinition(taskType: genericAppOpenTaskType,targetApp: target,triggerTerms: [],@@ -1400,7 +1400,7 @@ public enum BuiltInLocalAppTaskDefinitions {}public static var weatherLookup: LocalAppTaskDefinition {- LocalAppTaskDefinition(+ return LocalAppTaskDefinition(taskType: "weather_lookup",targetApp: LocalAppTarget(appName: "Weather",@@ -1462,7 +1462,31 @@ public enum BuiltInLocalAppTaskDefinitions {}public static var mediaPlayback: LocalAppTaskDefinition {- LocalAppTaskDefinition(+ var metadata: [String: String] = [+ "catalogEntry": "built-in-media-playback",+ "displayTitle": "media playback",+ "taskLabelTemplate": "Play {query}",+ "verificationTextKey": "query",+ "verificationMode": "playbackCommandAttempted",+ "automationBackend": "appleScript",+ "appleScript.action": "music.playMediaQuery",+ "appleScript.entityName": "query",+ "appleScript.successOutputs": "played-library-track,searched-ui-first-result",+ "screenshotFallback": "missingVerificationOrControls",+ "domain": "media",+ "visualFallback": "localModel",+ "ocrFallbackDefault": "false",+ "skillID": "music-media",+ "skillScriptID": "scripts-play-media-query-applescript"+ ]+ if let template = BuiltInLocalAppSkillPacks.scriptSource(+ skillID: "music-media",+ relativePath: "scripts/play-media-query.applescript"+ ) {+ metadata["appleScript.template"] = template+ }++ return LocalAppTaskDefinition(taskType: "media_playback",targetApp: LocalAppTarget(appName: "Music",@@ -1511,20 +1535,7 @@ public enum BuiltInLocalAppTaskDefinitions {],observationStrategies: [.accessibility, .windowMetadata, .screenshotForLocalModel],verificationEntityName: "query",- metadata: [- "catalogEntry": "built-in-media-playback",- "displayTitle": "media playback",- "taskLabelTemplate": "Play {query}",- "verificationTextKey": "query",- "verificationMode": "playbackCommandAttempted",- "automationBackend": "appleScript",- "appleScript.action": "music.playMediaQuery",- "appleScript.entityName": "query",- "screenshotFallback": "missingVerificationOrControls",- "domain": "media",- "visualFallback": "localModel",- "ocrFallbackDefault": "false"- ]+ metadata: metadata)}diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swiftnew file mode 100644index 00000000..2de3addf--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskSkillContext.swift@@ -0,0 +1,165 @@+import DonkeyContracts+import DonkeyHarness+import Foundation++public enum BuiltInLocalAppSkillPacks {+ public static var rootURL: URL? {+ Bundle.module.resourceURL?.appendingPathComponent("BuiltInSkills", isDirectory: true)+ }++ public static func descriptors() -> [HarnessSkillDescriptor] {+ guard let rootURL else { return [] }+ return HarnessSkillFileSystemSource(+ roots: [rootURL],+ sourceKind: .builtIn+ ).discover()+ }++ public static func instructionSnippet(+ for descriptor: HarnessSkillDescriptor,+ maxCharacters: Int = 1_200+ ) -> String {+ let header = [+ "Skill: \(descriptor.name)",+ "Skill ID: \(descriptor.id)",+ descriptor.tags.isEmpty ? "" : "Tags: \(descriptor.tags.joined(separator: ", "))",+ descriptor.providedToolNames.isEmpty ? "" : "Tools: \(descriptor.providedToolNames.joined(separator: ", "))"+ ]+ .filter { !$0.isEmpty }+ .joined(separator: "\n")++ let body = bounded(+ strippedSkillMetadata(from: descriptor.description),+ maxCharacters: max(200, maxCharacters - header.count - 2)+ )+ return [header, body]+ .filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }+ .joined(separator: "\n")+ }++ public static func scriptSource(+ skillID: String,+ relativePath: String+ ) -> String? {+ guard let descriptor = descriptors().first(where: { $0.id == skillID }),+ let directory = descriptor.metadata["directory"]+ else {+ return nil+ }+ let url = URL(fileURLWithPath: directory, isDirectory: true)+ .appendingPathComponent(relativePath, isDirectory: false)+ guard let source = try? String(contentsOf: url, encoding: .utf8) else {+ return nil+ }+ let trimmed = source.trimmingCharacters(in: .whitespacesAndNewlines)+ return trimmed.isEmpty ? nil : source+ }++ private static func strippedSkillMetadata(from contents: String) -> String {+ contents+ .split(whereSeparator: \.isNewline)+ .map(String.init)+ .filter { line in+ let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)+ let lowered = trimmed.lowercased()+ return !lowered.hasPrefix("id:")+ && !lowered.hasPrefix("description:")+ && !lowered.hasPrefix("tags:")+ && !lowered.hasPrefix("tools:")+ }+ .joined(separator: "\n")+ .trimmingCharacters(in: .whitespacesAndNewlines)+ }++ private static func bounded(_ value: String, maxCharacters: Int) -> String {+ guard value.count > maxCharacters else { return value }+ return String(value.prefix(maxCharacters)).trimmingCharacters(in: .whitespacesAndNewlines)+ }+}++public struct LocalAppTaskSkillContext: Equatable, Sendable {+ public var snippets: [String]++ public init(snippets: [String]) {+ self.snippets = snippets+ }++ public static func defaultContext(+ taskDefinitions: [LocalAppTaskDefinition],+ appFinderCatalog: [LocalAppFinderCatalogEntry],+ maxSkills: Int = 8+ ) -> LocalAppTaskSkillContext {+ let descriptors = selectedBuiltInSkillDescriptors(+ taskDefinitions: taskDefinitions,+ appFinderCatalog: appFinderCatalog,+ maxSkills: maxSkills+ )+ return LocalAppTaskSkillContext(+ snippets: descriptors.map {+ BuiltInLocalAppSkillPacks.instructionSnippet(for: $0)+ }+ )+ }++ private static func selectedBuiltInSkillDescriptors(+ taskDefinitions: [LocalAppTaskDefinition],+ appFinderCatalog: [LocalAppFinderCatalogEntry],+ maxSkills: Int+ ) -> [HarnessSkillDescriptor] {+ let descriptors = BuiltInLocalAppSkillPacks.descriptors()+ 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: " "))+ let availableTokens = taskTokens.union(catalogTokens)+ let scored: [(descriptor: HarnessSkillDescriptor, score: Int)] = descriptors.map { descriptor in+ let descriptorTokens = tokens(+ in: ([descriptor.id, descriptor.name, descriptor.summary] + descriptor.tags)+ .joined(separator: " ")+ )+ let score = descriptorTokens.intersection(availableTokens).count+ return (descriptor: descriptor, score: score)+ }+ .sorted {+ if $0.score == $1.score {+ return $0.descriptor.name < $1.descriptor.name+ }+ return $0.score > $1.score+ }++ let matching = scored.filter { $0.score > 0 }.map { $0.descriptor }+ if !matching.isEmpty {+ return Array(matching.prefix(max(0, maxSkills)))+ }++ return Array(descriptors.prefix(max(0, maxSkills)))+ }++ private static func tokens(in value: String) -> Set<String> {+ Set(+ value.lowercased()+ .split { !$0.isLetter && !$0.isNumber }+ .map(String.init)+ .filter { !$0.isEmpty }+ )+ }+}diff --git a/apps/Donkey/Sources/DonkeyRuntime/MacAppleScriptActionEngineInputBackend.swift b/apps/Donkey/Sources/DonkeyRuntime/MacAppleScriptActionEngineInputBackend.swiftindex 57ca11f3..e2279c8b 100644--- a/apps/Donkey/Sources/DonkeyRuntime/MacAppleScriptActionEngineInputBackend.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/MacAppleScriptActionEngineInputBackend.swift@@ -133,10 +133,6 @@ public struct MacAppleScriptActionEngineInputBackend: ActionEngineInputBackend {)}- static func musicPlaybackScript(query: String) -> String {- AppleScriptActionScriptGenerator.musicPlaybackScript(query: query)- }-private static func acceptedOutputs(for command: ActionEngineCommand) -> Set<String> {if let explicitOutputs = command.metadata["appleScript.successOutputs"] {return Set(explicitOutputs@@ -145,13 +141,6 @@ public struct MacAppleScriptActionEngineInputBackend: ActionEngineInputBackend {.filter { !$0.isEmpty })}- if command.metadata["appleScript.action"] == "music.playMediaQuery" {- return [- "played-library-track",- "searched-ui-first-result"- ]- }-return []}@@ -197,53 +186,9 @@ enum AppleScriptActionScriptGenerator {)}- if action == "music.playMediaQuery",- !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {- return AppleScriptActionScript(- action: action,- kind: "builtInAction",- source: musicPlaybackScript(query: query)- )- }-return nil}- static func musicPlaybackScript(query: String) -> String {- let escapedQuery = appleScriptStringLiteral(query)- return """- set donkeyQuery to \(escapedQuery)- tell application "Music"- activate- delay 0.1- try- set donkeyMatches to search library playlist 1 for donkeyQuery only songs- if (count of donkeyMatches) > 0 then- play item 1 of donkeyMatches- return "played-library-track"- end if- end try- end tell- try- tell application "System Events"- tell process "Music"- set frontmost to true- keystroke "f" using command down- delay 0.12- keystroke donkeyQuery- delay 0.12- key code 36- delay 0.25- key code 36- end tell- end tell- return "searched-ui-first-result"- on error donkeyFallbackError- return "ui-search-error:" & donkeyFallbackError- end try- """- }-private static func renderTemplate(_ template: String,command: ActionEngineCommand,diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/browser-navigation/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/browser-navigation/SKILL.mdnew file mode 100644index 00000000..1809828d--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/browser-navigation/SKILL.md@@ -0,0 +1,11 @@+# Browser Navigation+id: browser-navigation+description: Plan opening websites and URLs in a supported browser.+tags: browser, website, navigation, local-app+tools: app.openOrFocus, app.observe, ui.focusAddressBar, ui.setText, ui.pressReturn, app.verifyCommand++Use this skill for website or URL navigation when the app finder catalog exposes a supported browser capability.++Set `query` to the normalized URL or website string to open. Prefer the user's named browser when present; otherwise choose a supported browser catalog entry.++When planning generic `local_app_interaction`, use `goal=open requested website`, `inputEntity=query`, `controlID=addressBar`, `focusKey=Command+L`, and tools `app.openOrFocus`, `app.observe`, `ui.focusAddressBar`, `ui.setText`, `ui.pressReturn`, `app.verifyCommand`.diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music-media/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music-media/SKILL.mdnew file mode 100644index 00000000..9efbc62d--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music-media/SKILL.md@@ -0,0 +1,15 @@+# Music Media+id: music-media+description: Plan low-risk media playback in Apple Music or another supported media app.+tags: media, music, playback, local-app+tools: app.openOrFocus, app.observe, ui.focusSearch, ui.setText, ui.pressReturn, app.verifyCommand++Use this skill for play or listen requests when a supported media app or a `play_media` catalog capability is available.++For explicit songs, albums, or playlists, put the concrete playable title plus artist when known in `query`.++For vague artist or genre requests, choose one concrete representative song or album before returning task JSON. Do not use an artist-only query unless the user explicitly asks to open an artist page, artist radio, station, or browsing surface.++Set `metadata.mediaSelection.kind` to `explicit_song`, `explicit_album`, `explicit_playlist`, `representative_song`, or `representative_album`. For representative choices, also set `metadata.mediaSelection.seed`, `metadata.mediaSelection.selectedTitle`, and a short `metadata.mediaSelection.reason`.++When planning generic `local_app_interaction`, use `targetAppName` and `entities.appName` from the supported catalog entry. Use `goal=play media`, `inputEntity=query`, `controlID=search`, `focusKey=Command+F`, and tools `app.openOrFocus`, `app.observe`, `ui.focusSearch`, `ui.setText`, `ui.pressReturn`, `app.verifyCommand`. If visible results are present, prefer a playable song row matching the requested seed over artist, playlist, category, or unrelated rows.diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music-media/scripts/play-media-query.applescript b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music-media/scripts/play-media-query.applescriptnew file mode 100644index 00000000..5fec6085--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/music-media/scripts/play-media-query.applescript@@ -0,0 +1,29 @@+set donkeyQuery to {query}+tell application "Music"+ activate+ delay 0.1+ try+ set donkeyMatches to search library playlist 1 for donkeyQuery only songs+ if (count of donkeyMatches) > 0 then+ play item 1 of donkeyMatches+ return "played-library-track"+ end if+ end try+end tell+try+ tell application "System Events"+ tell process "Music"+ set frontmost to true+ keystroke "f" using command down+ delay 0.12+ keystroke donkeyQuery+ delay 0.12+ key code 36+ delay 0.25+ key code 36+ end tell+ end tell+ return "searched-ui-first-result"+on error donkeyFallbackError+ return "ui-search-error:" & donkeyFallbackError+end trydiff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/notes-writing/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/notes-writing/SKILL.mdnew file mode 100644index 00000000..30eebf81--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/notes-writing/SKILL.md@@ -0,0 +1,13 @@+# Notes Writing+id: notes-writing+description: Plan writing finished text into a supported notes or text editor app.+tags: notes, writing, text, local-app+tools: app.openOrFocus, app.observe, ui.newDocument, ui.setText, app.verifyCommand++Use this skill for writing into a notes or text-editor app when the requested content is meaningful enough to type safely.++Set `query` to the complete final text to type. Do not set `query` to a category label, a restatement of the request, or placeholder text from instructions. If the writing form is clear but details are sparse, compose a short finished piece that satisfies the requested form.++If the requested object is malformed or nonsensical, choose conversation and ask for a clearer payload instead of opening the app.++When planning generic `local_app_interaction`, use `goal=write requested text`, `inputEntity=query`, `controlID=editor`, and tools `app.openOrFocus`, `app.observe`, `ui.newDocument`, `ui.setText`, `app.verifyCommand`.diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/spreadsheet-tables/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/spreadsheet-tables/SKILL.mdnew file mode 100644index 00000000..d5127db7--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/spreadsheet-tables/SKILL.md@@ -0,0 +1,13 @@+# Spreadsheet Tables+id: spreadsheet-tables+description: Plan creating compact tables in a supported spreadsheet app.+tags: spreadsheet, table, numbers, local-app+tools: app.openOrFocus, app.observe, ui.newDocument, ui.setText, app.verifyCommand++Use this skill for simple table or spreadsheet creation when a supported spreadsheet app is available.++Set `query` to compact tab-separated table content, including a header row. If exact live data is unavailable, make a table-shaped brief with a data-needed note instead of a single sentence.++When a table request needs fresh data from another local app before creating the final spreadsheet, keep the final destination app as `targetAppName` and record the source-to-destination sequence in `metadata.appChain` as a JSON string array of app names.++When planning generic `local_app_interaction`, use `goal=create requested table`, `inputEntity=query`, `controlID=editor`, and tools `app.openOrFocus`, `app.observe`, `ui.newDocument`, `ui.setText`, `app.verifyCommand`.diff --git a/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/weather-lookup/SKILL.md b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/weather-lookup/SKILL.mdnew file mode 100644index 00000000..e041aee1--- /dev/null+++ b/apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/weather-lookup/SKILL.md@@ -0,0 +1,11 @@+# Weather Lookup+id: weather-lookup+description: Plan low-risk weather lookup workflows when a weather capability is provided.+tags: weather, lookup, local-app+tools: app.openOrFocus, app.observe, ui.focusSearch, ui.setText, ui.pressReturn, app.verifyVisibleText++Use this skill when a supported weather lookup definition or catalog capability is available.++Set the required location entity to the requested city or place. Use the task definition's entity name when it is more specific than `query`.++For search-style weather workflows, focus the search field, enter the normalized location, submit the search, and verify the visible result contains the requested place.diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swiftindex acc54f3c..51bee952 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift@@ -5,7 +5,7 @@ import Foundationimport Testingprivate let defaultLocalRuntimeModelID = "qwen2.5-0.5b-instruct-q4_k_m"-// Only used in explicit local-generate adapter unit tests; it is not a default runtime dependency.+// Only used in explicit local-generate planner-hint unit tests; it is not a default runtime dependency.private let explicitLocalGenerateFixtureModelID = "qwen3:8b"@Suite@@ -332,140 +332,6 @@ struct AIHarnessAdapterTests {#expect(failed.metadata["sidecar.reason"] == "nonZeroExit")}- @Test- func localGenerateTaskIntentAdapterBuildsLocalRequestAndDecodesValidatedIntent() async throws {- let httpClient = FakeAIHTTPClient(- data: localGenerateResponseData(- response: """- {"taskType":"weather_lookup","targetAppName":"Weather","entities":{"city":"SF"},"normalizedEntities":{"city":"San Francisco"},"confidence":0.93,"needsConfirmation":false,"actionPlan":{"tools":[],"inputEntity":"","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{"source":"test"}}- """- ),- statusCode: 200- )- let adapter = LocalGenerateTaskIntentAdapter(- router: AIModelRouter(- registry: AIModelRegistry(- entries: [- entry(- id: "local-intent",- role: .taskIntent,- provider: .ollama,- modelID: explicitLocalGenerateFixtureModelID,- endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,- promptVersion: "task-intent-v1"- )- ]- )- ),- httpClient: httpClient- )-- let result = await adapter.parseTaskIntent(- TaskIntentAdapterRequest(- command: "show me the weather for SF",- taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,- sourceTraceID: "trace-intent"- )- )-- #expect(result.intent?.taskType == "weather_lookup")- #expect(result.intent?.targetApp.appName == "Weather")- #expect(result.intent?.normalizedEntities["city"] == "San Francisco")- #expect(result.intent?.parserSource == .localModel)- #expect(result.intent?.sourceModelCallID == "model-call-trace-intent")- #expect(result.trace.status == .completed)- #expect(result.trace.role == .taskIntent)- #expect(result.trace.provider == .ollama)-- let request = try #require(httpClient.requests.first)- #expect(request.url?.absoluteString == "http://127.0.0.1:11434/api/generate")- let body = try #require(request.httpBodyJSONObject)- #expect(body["model"] as? String == explicitLocalGenerateFixtureModelID)- #expect(body["stream"] as? Bool == false)- #expect(body["format"] as? [String: Any] != nil)- #expect(body["keep_alive"] as? String == "10m")- let options = try #require(body["options"] as? [String: Any])- #expect(options["num_predict"] as? Int == 512)- #expect(options["num_ctx"] as? Int == 2048)- #expect((body["prompt"] as? String)?.contains("Use only the provided task definitions") == true)- #expect((body["prompt"] as? String)?.contains("choose by capability and target app") == true)- #expect((body["prompt"] as? String)?.contains("Do not include reasoning") == true)- #expect((body["prompt"] as? String)?.contains("play/listen media requests") == true)- #expect((body["prompt"] as? String)?.contains("media-selection planning") == true)- #expect((body["prompt"] as? String)?.contains("mediaSelection.selectedTitle") == true)- #expect((body["prompt"] as? String)?.contains("For website navigation") == true)- #expect((body["prompt"] as? String)?.contains("ui.newDocument") == true)- #expect((body["prompt"] as? String)?.contains("set_text_input_contract=inputEntityValueIsExactTextToEnter") == true)- #expect((body["prompt"] as? String)?.contains("action, destination or target app/item") == true)- #expect((body["prompt"] as? String)?.contains("metadata.responseMode=conversation") == true)- #expect((body["prompt"] as? String)?.contains("metadata.assistantResponse") == true)- #expect((body["prompt"] as? String)?.contains("taskType \"none\"") == true)- #expect((body["prompt"] as? String)?.contains("triggers=") == false)- #expect((body["prompt"] as? String)?.contains("metadata=") == false)- }-- @Test- func localGenerateTaskIntentAdapterUsesInstalledLocalModelWhenConfiguredModelIsMissing() async throws {- let httpClient = SequencedFakeAIHTTPClient(- responses: [- HTTPStub(- data: Data("{\"error\":\"model '\(explicitLocalGenerateFixtureModelID)' not found\"}".utf8),- statusCode: 404- ),- HTTPStub(- data: Data(#"{"models":[{"name":"kimi-k2.5:cloud","size":0},{"name":"llama3:latest","size":4700000000}]}"#.utf8),- statusCode: 200- ),- HTTPStub(- data: localGenerateResponseData(- response: """- {"taskType":"local_app_interaction","targetAppName":"Music","entities":{"appName":"Music","goal":"play media","query":"justin bieber"},"normalizedEntities":{"appName":"Music","goal":"play media","query":"Justin Bieber"},"confidence":0.91,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.focusSearch","ui.setText","ui.pressReturn","app.verifyCommand"],"inputEntity":"query","controlID":"search","focusKey":"Command+F","verification":"commandAttempted"},"metadata":{}}- """- ),- statusCode: 200- )- ]- )- let adapter = LocalGenerateTaskIntentAdapter(- router: AIModelRouter(- registry: AIModelRegistry(- entries: [- entry(- id: "local-intent",- role: .taskIntent,- provider: .ollama,- modelID: explicitLocalGenerateFixtureModelID,- endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,- promptVersion: "task-intent-v1"- )- ]- )- ),- httpClient: httpClient- )-- let result = await adapter.parseTaskIntent(- TaskIntentAdapterRequest(- command: "play some justin bieber",- taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,- contextSnippets: ["Music application com.apple.Music"],- sourceTraceID: "trace-local-generate-model-fallback"- )- )-- #expect(result.intent?.taskType == "local_app_interaction")- #expect(result.intent?.targetApp.appName == "Music")- #expect(result.intent?.normalizedEntities["query"] == "Justin Bieber")- #expect(result.trace.status == .completed)- #expect(result.trace.modelID == "llama3:latest")- #expect(result.trace.metadata["modelFallback.originalModelID"] == explicitLocalGenerateFixtureModelID)- #expect(result.trace.metadata["modelFallback.selectedModelID"] == "llama3:latest")- #expect(httpClient.requests.map { $0.url?.path } == ["/api/generate", "/api/tags", "/api/generate"])- let fallbackRequest = try #require(httpClient.requests.last)- let fallbackBody = try #require(fallbackRequest.httpBodyJSONObject)- #expect(fallbackBody["model"] as? String == "llama3:latest")- }-@Testfunc processBackedLocalLLMTaskIntentAdapterDecodesValidatedIntent() async throws {let adapter = ProcessBackedLocalLLMTaskIntentAdapter(@@ -563,11 +429,15 @@ struct AIHarnessAdapterTests {#expect(result.intent?.metadata["genericHarness.schemaVersion"] == "generic_harness_planning")#expect(result.intent?.metadata["genericHarness.intent.goal"] == "play Viva La Vida by Coldplay")#expect(instructions.contains("local_app_interaction"))- #expect(instructions.contains("media playback"))- #expect(instructions.contains("play/listen media requests"))- #expect(instructions.contains("media-selection planning"))- #expect(instructions.contains("mediaSelection.selectedTitle"))+ #expect(instructions.contains("App skill guidance"))#expect(instructions.contains("metadata.assistantResponse"))+ #expect(instructions.contains("play/listen media requests") == false)+ 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: music-media"))+ #expect(prompt.contains("mediaSelection.selectedTitle"))}@Test@@ -1195,35 +1065,25 @@ struct AIHarnessAdapterTests {@Testfunc localModelTaskIntentResolverValidatesAgainstCatalogAvailability() async {- let httpClient = FakeAIHTTPClient(- data: localGenerateResponseData(- response: """- {"taskType":"weather_lookup","targetAppName":"Weather","entities":{"city":"SF"},"normalizedEntities":{"city":"San Francisco"},"confidence":0.93,"needsConfirmation":false,"actionPlan":{"tools":[],"inputEntity":"","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{}}- """- ),- statusCode: 200- )let resolver = LocalModelTaskIntentResolver(catalog: LocalAppTaskCatalog(taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])),- adapter: LocalGenerateTaskIntentAdapter(- router: AIModelRouter(- registry: AIModelRegistry(- entries: [- entry(- id: "local-intent",- role: .taskIntent,- provider: .ollama,- modelID: explicitLocalGenerateFixtureModelID,- endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,- promptVersion: "task-intent-v1"- )- ]- )- ),- httpClient: httpClient+ adapter: FixedTaskIntentAdapter(+ intent: TaskIntent(+ intentID: "weather_lookup-san-francisco",+ taskType: "weather_lookup",+ targetApp: LocalAppTarget(+ appName: "Weather",+ bundleIdentifier: "com.apple.weather",+ titleContains: "Weather"+ ),+ entities: ["city": "SF"],+ normalizedEntities: ["city": "San Francisco"],+ confidence: 0.93,+ parserSource: .onlineModel+ )))@@ -1233,21 +1093,13 @@ struct AIHarnessAdapterTests {)#expect(result.resolution.status == .resolved)- #expect(result.resolution.intent?.parserSource == .localModel)+ #expect(result.resolution.intent?.parserSource == .onlineModel)#expect(result.resolution.availability?.isInstalled == true)#expect(result.trace.status == .completed)}@Testfunc localModelTaskIntentResolverResolvesDynamicLocalItemLookup() async {- let httpClient = FakeAIHTTPClient(- data: localGenerateResponseData(- response: """- {"taskType":"app_open","targetAppName":"Figma","entities":{"appName":"figma"},"normalizedEntities":{"appName":"Figma"},"confidence":0.94,"needsConfirmation":false,"actionPlan":{"tools":[],"inputEntity":"","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{}}- """- ),- statusCode: 200- )let resolver = LocalModelTaskIntentResolver(catalog: LocalAppTaskCatalog(taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,@@ -1256,22 +1108,16 @@ struct AIHarnessAdapterTests {installedApplicationNames: ["Figma": "com.figma.Desktop"])),- adapter: LocalGenerateTaskIntentAdapter(- router: AIModelRouter(- registry: AIModelRegistry(- entries: [- entry(- id: "local-intent",- role: .taskIntent,- provider: .ollama,- modelID: explicitLocalGenerateFixtureModelID,- endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,- promptVersion: "task-intent-v1"- )- ]- )- ),- httpClient: httpClient+ adapter: FixedTaskIntentAdapter(+ intent: TaskIntent(+ intentID: "app_open-figma",+ taskType: "app_open",+ targetApp: LocalAppTarget(appName: "Figma"),+ entities: ["appName": "figma"],+ normalizedEntities: ["appName": "Figma"],+ confidence: 0.94,+ parserSource: .onlineModel+ )))@@ -1434,35 +1280,23 @@ struct AIHarnessAdapterTests {@Testfunc localModelTaskIntentResolverAcceptsClosestLowConfidenceClassification() async {- let httpClient = FakeAIHTTPClient(- data: localGenerateResponseData(- response: """- {"taskType":"weather_lookup","targetAppName":"Weather","entities":{},"normalizedEntities":{},"confidence":0.2,"needsConfirmation":false,"actionPlan":{"tools":[],"inputEntity":"","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{}}- """- ),- statusCode: 200- )let resolver = LocalModelTaskIntentResolver(catalog: LocalAppTaskCatalog(taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])),- adapter: LocalGenerateTaskIntentAdapter(- router: AIModelRouter(- registry: AIModelRegistry(- entries: [- entry(- id: "local-intent",- role: .taskIntent,- provider: .ollama,- modelID: explicitLocalGenerateFixtureModelID,- endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,- promptVersion: "task-intent-v1"- )- ]- )- ),- httpClient: httpClient+ adapter: FixedTaskIntentAdapter(+ intent: TaskIntent(+ intentID: "weather_lookup-weather",+ taskType: "weather_lookup",+ targetApp: LocalAppTarget(+ appName: "Weather",+ bundleIdentifier: "com.apple.weather",+ titleContains: "Weather"+ ),+ confidence: 0.2,+ parserSource: .onlineModel+ )))@@ -1478,35 +1312,31 @@ struct AIHarnessAdapterTests {@Testfunc localModelTaskIntentResolverPreservesConversationResponseForMalformedTask() async {- let httpClient = FakeAIHTTPClient(- data: localGenerateResponseData(- response: """- {"taskType":"local_app_interaction","targetAppName":"Notes","entities":{"appName":"Notes","goal":"unclear writing request"},"normalizedEntities":{"appName":"Notes","goal":"unclear writing request"},"confidence":0.2,"needsConfirmation":false,"actionPlan":{"tools":[],"inputEntity":"query","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{"responseMode":"conversation","assistantResponse":"I can help with that, but I need a clearer thing to write before opening Notes."}}- """- ),- statusCode: 200- )let resolver = LocalModelTaskIntentResolver(catalog: LocalAppTaskCatalog(taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.Notes"])),- adapter: LocalGenerateTaskIntentAdapter(- router: AIModelRouter(- registry: AIModelRegistry(- entries: [- entry(- id: "local-intent",- role: .taskIntent,- provider: .ollama,- modelID: explicitLocalGenerateFixtureModelID,- endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,- promptVersion: "task-intent-v1"- )- ]- )- ),- httpClient: httpClient+ adapter: FixedTaskIntentAdapter(+ intent: TaskIntent(+ intentID: "local_app_interaction-notes",+ taskType: "local_app_interaction",+ targetApp: LocalAppTarget(appName: "Notes", bundleIdentifier: "com.apple.Notes"),+ entities: [+ "appName": "Notes",+ "goal": "unclear writing request"+ ],+ normalizedEntities: [+ "appName": "Notes",+ "goal": "unclear writing request"+ ],+ confidence: 0.2,+ parserSource: .onlineModel,+ metadata: [+ "responseMode": "conversation",+ "assistantResponse": "I can help with that, but I need a clearer thing to write before opening Notes."+ ]+ )))@@ -2436,6 +2266,39 @@ private struct RecordingTaskIntentAdapter: TaskIntentParsingAdapter {}}+private struct FixedTaskIntentAdapter: TaskIntentParsingAdapter {+ var intent: TaskIntent?+ var provider: AIModelProvider = .donkeyBackend+ var status: AIModelCallStatus = .completed+ var validationStatus = "schemaDecoded"+ var metadata: [String: String] = [:]++ func parseTaskIntent(_ request: TaskIntentAdapterRequest) async -> TaskIntentAdapterResult {+ var returnedIntent = intent+ if returnedIntent?.sourceModelCallID == nil {+ returnedIntent?.sourceModelCallID = "model-call-\(request.sourceTraceID)"+ }++ return TaskIntentAdapterResult(+ intent: returnedIntent,+ trace: AIModelCallTrace(+ id: "model-call-\(request.sourceTraceID)",+ role: .taskIntent,+ provider: provider,+ modelID: AIModelRegistryEntry.backendSelectedModelID,+ promptVersion: "task-intent-v1",+ schemaID: "generic_harness_planning",+ latencyMS: 12,+ timeoutMS: 12_000,+ status: status,+ validationStatus: validationStatus,+ sourceTraceID: request.sourceTraceID,+ metadata: metadata+ )+ )+ }+}+private func localLLMSidecarOutputData(outputText: String,metadata: [String: String]diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swiftindex 8aca036a..9d46b6f8 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift@@ -152,6 +152,21 @@ struct GenericHarnessTests {#expect(skills.first?.instructionPath?.hasSuffix("SKILL.md") == true)}+ @Test+ func builtInLocalAppSkillPacksProvideBoundedIntentGuidance() async throws {+ 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"))+ }+@Testfunc unknownToolIsRejectedByRegistry() async {let registry = BuiltInHarnessToolCatalog.registryWithBuiltInExecutors()diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/MacAppleScriptActionEngineInputBackendTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/MacAppleScriptActionEngineInputBackendTests.swiftindex 10a4c8dc..ed43fe8f 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/MacAppleScriptActionEngineInputBackendTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/MacAppleScriptActionEngineInputBackendTests.swift@@ -7,6 +7,10 @@ import Testingstruct MacAppleScriptActionEngineInputBackendTests {@Testfunc musicPlaybackCommandRunsEscapedAppleScript() async throws {+ let template = try #require(BuiltInLocalAppSkillPacks.scriptSource(+ skillID: "music-media",+ relativePath: "scripts/play-media-query.applescript"+ ))let runner = RecordingAppleScriptRunner(result: AppleScriptExecutionResult(succeeded: true,@@ -25,7 +29,9 @@ struct MacAppleScriptActionEngineInputBackendTests {metadata: ["automationBackend": "appleScript","appleScript.action": "music.playMediaQuery",- "appleScript.query": "Justin \"JB\" Bieber"+ "appleScript.query": "Justin \"JB\" Bieber",+ "appleScript.template": template,+ "appleScript.successOutputs": "played-library-track,searched-ui-first-result"]))@@ -38,6 +44,7 @@ struct MacAppleScriptActionEngineInputBackendTests {#expect(scripts.first?.contains(#"set donkeyQuery to "Justin \"JB\" Bieber""#) == true)#expect(scripts.first?.contains("tell application \"Music\"") == true)#expect(scripts.first?.contains("tell application \"System Events\"") == true)+ #expect(result.metadata["appleScript.scriptKind"] == "template")}@Testdiff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex 81d3bb9d..2026690f 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -13,6 +13,11 @@ New agent capabilities should plug into that module through tools, skills,scripts, plugins, catalogs, or memory. Do not add app-specific branches,phrase lists, or one-off workflow conditionals to the core harness.+Bundled local-app skills now carry the app-specific planning guidance for+Music/media, browser navigation, notes/text writing, spreadsheet tables, and+weather lookup. Task-intent model calls receive those skills as bounded skill+context alongside task definitions, app catalog data, and memory.+The existing pointer-prompt and local-app runner code still exists while theproduct migrates onto the generic harness. New work should build toward thegeneric registry and avoid expanding the older app-specific paths.@@ -204,6 +209,10 @@ AppleScript execution may run only a validated, generated, or user-reviewedartifact through the guarded automation backend, with target app, permissions,action metadata, and verification evidence attached.+App-specific AppleScript belongs in skill-local scripts or generated artifacts.+The guarded backend renders explicit `appleScript.source` or+`appleScript.template` metadata; it should not grow app-named script helpers.+Do not add app-named Swift helpers such as `musicPlaybackScript` or`openFooScript`. If an app needs automation knowledge, put it in a skill,plugin, catalog entry, generated artifact, or user-reviewed definition.@@ -231,6 +240,11 @@ need. Loading a skill adds selected instructions to bounded planning context.Skills are shared infrastructure. They should be reusable by any future agentor task, not private scratch memory for one run.+Built-in app skills live as resource skill packs under+`apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/`. They are loaded+through the same skill descriptor shape as user/plugin skills and compacted+before being sent to model boundaries.+## Skill ScriptsSkill packs may include generated scripts under a skill-local `scripts/`diff --git a/docs/guides/decision-system.md b/docs/guides/decision-system.mdindex b4071117..4099d072 100644--- a/docs/guides/decision-system.md+++ b/docs/guides/decision-system.md@@ -94,6 +94,6 @@ control profiles before they can influence executable planning.## Source Entry Points- Prompt handling: `apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift`-- Hosted decision adapter: `apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift`+- Hosted decision adapter: `apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift`- Catalog validation: `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift`- Generic lifecycle bridge: `apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift`diff --git a/plans/master-plan.md b/plans/master-plan.mdindex 1d8956da..51d92e6b 100644--- a/plans/master-plan.md+++ b/plans/master-plan.md@@ -21,17 +21,13 @@ even when there are no active tasks.## Current Sequence-1. Move app-specific behavior into skills. Music, Notes, Numbers, browser- workflows, app knowledge, and future app-specific behavior should live in- skill packs, plugin/catalog data, generated artifacts, or memory instead of- core Swift prompt branches.-2. Build the application-learning task. It should safely explore an app, capture+1. Build the application-learning task. It should safely explore an app, capturescreenshots and Accessibility trees, distill surfaces/workflows, generatescripts where useful, validate them, and save a reusable skill pack.-3. Wire interruption and permission gates into the UI. The notch/task UI should+2. Wire interruption and permission gates into the UI. The notch/task UI shouldcontrol generic harness tasks and show the exact pending approval orchanged-course state.-4. Delete old app-specific paths once the generic path covers them. Remove+3. Delete old app-specific paths once the generic path covers them. Removehardcoded Music/Notes/Numbers/media/weather-style prompt rules, catalogspecial cases, repair logic, and demo-only workflow branches.diff --git a/scripts/evals/run_task_intent_sidecar_evals.py b/scripts/evals/run_task_intent_sidecar_evals.pyindex a5cc4341..4921d15a 100644--- a/scripts/evals/run_task_intent_sidecar_evals.py+++ b/scripts/evals/run_task_intent_sidecar_evals.py@@ -29,6 +29,7 @@ DEFAULT_COMPARISON_REPORT_PATH = DEFAULT_COMPARISON_DIR / "comparison.latest.jsoDEFAULT_MODEL_CONFIG_PATH = Path("config/local-llm-models.json")DEFAULT_CANDIDATE_CONFIG_PATH = Path("evals/task-intent/local-llm-model-candidates.json")DEFAULT_SIDECAR = Path("scripts/local-runtime-runners/donkey_runtime_runner.py")+DEFAULT_SKILL_ROOT = Path("apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills")SCHEMA_ID = "task_intent_v1"@@ -235,10 +236,22 @@ def context_snippets(cases: list[dict[str, Any]]) -> dict[str, str]:return snippets+def skill_snippets(root: Path = DEFAULT_SKILL_ROOT) -> list[str]:+ if not root.exists():+ return []+ snippets: list[str] = []+ for path in sorted(root.glob("*/SKILL.md")):+ text = path.read_text(encoding="utf-8").strip()+ if text:+ snippets.append(text[:1200])+ return snippets++def build_request(case: dict[str, Any],model_id: str,snippets: dict[str, str],+ skills: list[str],cache_directory: Path | None = None,) -> dict[str, Any]:app_info = case.get("app") or {}@@ -260,6 +273,7 @@ def build_request("command": case["command"],"taskDefinitions": TASK_DEFINITIONS,"contextSnippets": (local_context + fallback_context)[:8],+ "skillSnippets": skills[:8],"sourceTraceID": case["id"].replace("/", "-"),"modelID": model_id,"metadata": {@@ -720,6 +734,7 @@ def run_eval_suite(runtime_state_dir: Path | None = None,) -> tuple[dict[str, Any], list[EvalResult]]:snippets = context_snippets(all_cases)+ skills = skill_snippets()results: list[EvalResult] = []extra_env = {"DONKEY_LOCAL_LLM_TIMEOUT_SECONDS": str(timeout_seconds)}if model_path is not None:@@ -731,7 +746,7 @@ def run_eval_suite(extra_env["DONKEY_RUNTIME_STATE_DIR"] = str(runtime_state_dir)for index, case in enumerate(cases, start=1):- request = build_request(case, model_id, snippets, cache_directory)+ request = build_request(case, model_id, snippets, skills, cache_directory)if dry_run:response, stderr, latency_ms = dry_run_response(case)else:diff --git a/scripts/local-runtime-runners/donkey_runtime_runner.py b/scripts/local-runtime-runners/donkey_runtime_runner.pyindex e6324473..acccf4da 100644--- a/scripts/local-runtime-runners/donkey_runtime_runner.py+++ b/scripts/local-runtime-runners/donkey_runtime_runner.py@@ -599,6 +599,7 @@ def local_llm_prompt_and_limit(request: dict[str, Any]) -> tuple[str, int]:command,task_definitions,request.get("contextSnippets", []),+ request.get("skillSnippets", []),request.get("appFinderCatalog", []),),task_intent_schema(task_definitions),@@ -642,6 +643,7 @@ def repair_invalid_task_intent_with_compact_model(compact_prompt_text = compact_task_intent_prompt(command,task_definitions,+ request.get("skillSnippets", []),request.get("appFinderCatalog", []),)try:@@ -663,6 +665,7 @@ def repair_invalid_task_intent_with_compact_model(compact_text,command=command,task_definitions=task_definitions,+ app_finder_catalog=request.get("appFinderCatalog", []),)if repaired is None:return output_text, {@@ -682,6 +685,7 @@ def compact_task_intent_output(llm: Any, request: dict[str, Any]) -> tuple[str,compact_prompt_text = compact_task_intent_prompt(command,task_definitions,+ request.get("skillSnippets", []),request.get("appFinderCatalog", []),)try:@@ -703,6 +707,7 @@ def compact_task_intent_output(llm: Any, request: dict[str, Any]) -> tuple[str,compact_text,command=command,task_definitions=task_definitions,+ app_finder_catalog=request.get("appFinderCatalog", []),)if materialized is None:return "", {@@ -745,9 +750,9 @@ def task_intent_payload_looks_valid(intent: Any) -> bool:def compact_task_intent_prompt(command: str,task_definitions: list[dict[str, Any]],+ skill_snippets: list[Any] | None = None,app_finder_catalog: list[dict[str, Any]] | None = None,) -> str:- known_apps = ["Music", "Safari", "Notes", "Numbers"]catalog_apps = [str(entry.get("appName") or "").strip()for entry in (app_finder_catalog or [])@@ -759,7 +764,8 @@ def compact_task_intent_prompt(for definition in task_definitionsif str((definition.get("targetApp") or {}).get("appName") or "").strip()]- app_names = ordered_unique(catalog_apps + known_apps + discovered_apps + ["Local App"])+ app_names = ordered_unique(catalog_apps + discovered_apps + ["Local App"])+ skill_guidance = "\n\n".join(str(item) for item in (skill_snippets or [])[:8] if str(item).strip())return "\n".join(["<|im_start|>system",@@ -768,15 +774,13 @@ def compact_task_intent_prompt("<|im_start|>user","Classify this Mac command into an executable local app action or no action.","Choose appName from: " + ", ".join(app_names),- "Prefer a concrete app name. Do not choose Local App when Music, Safari, Notes, or Numbers fits.",+ "Prefer a concrete app name from supported catalog or skill guidance. Do not choose Local App when a supported named app fits.","If this is not an executable local app action, set appName to none, query to empty, and confidence to 0.",- "For play/listen media requests, choose Music when available. If the request is vague like play some <artist>, pick a concrete playable song or album first and put '<selected title> <artist>' in query; do not use an artist-only query unless the user explicitly asks for the artist page/station.",+ "Apply App skill guidance for app-specific workflows and control strategies.",f"Command: {command}",- "JSON keys: appName, goal, query, confidence.",- "For music playback, appName is Music and query is the artist/song.",- "For website navigation, appName is Safari and query is the website or URL.",- "For writing text, appName is Notes and query is the text to write.",- "For tables or spreadsheets, appName is Numbers and query is the table content or subject.",+ "App skill guidance:",+ skill_guidance,+ "JSON keys: appName, goal, query, confidence, capabilityID, controlID, focusKey, tools.","<|im_end|>","<|im_start|>assistant",]@@ -833,6 +837,7 @@ def materialize_compact_task_intent(*,command: str,task_definitions: list[dict[str, Any]],+ app_finder_catalog: list[dict[str, Any]] | None = None,) -> dict[str, Any] | None:compact = decode_compact_object(compact_text)if not isinstance(compact, dict):@@ -843,17 +848,46 @@ def materialize_compact_task_intent(app_name = str(compact.get("appName") or "").strip()if not app_name or normalized_words(app_name) == ["local", "app"]:return None- if normalized_words(app_name) != ["music"]:- return Noneconfidence = compact_confidence(compact.get("confidence"))if confidence < 0.55:return Nonegoal = str(compact.get("goal") or "").strip() or "use local app"- if normalized_words(app_name) == ["music"]:- goal = "play media"query = compact_query(compact.get("query"), command)+ if not query:+ return None++ selection = compact_app_finder_selection(compact, app_name, app_finder_catalog or [])+ if app_finder_catalog and selection is None:+ return None+ tools = compact_tools(compact.get("tools"))+ capability_id = ""+ control_profile = ""+ if selection is not None:+ entry, capability = selection+ app_name = str(entry.get("appName") or app_name)+ capability_id = str(capability.get("id") or "")+ profiles = capability.get("controlProfiles") if isinstance(capability.get("controlProfiles"), list) else []+ control_profile = str(compact.get("controlProfile") or (profiles[0] if profiles else "") or "")+ if not tools:+ tools = compact_tools_for_control_profile(control_profile)+ if not tools:+ tools = ["app.openOrFocus", "app.observe", "ui.focusTextEntry", "ui.setText", "app.verifyCommand"]++ control_id = str(compact.get("controlID") or "").strip() or compact_control_id_for_tools(tools)+ focus_key = str(compact.get("focusKey") or "").strip() or compact_focus_key_for_tools(tools)+ metadata: dict[str, Any] = {}+ if selection is not None:+ entry, _ = selection+ metadata.update(+ {+ "appFinder.selectedAppID": str(entry.get("appID") or ""),+ "appFinder.selectedCapabilityID": capability_id,+ "appFinder.controlProfile": control_profile,+ "appFinder.supportStatus": str(entry.get("supportStatus") or ""),+ }+ )return {"taskType": "local_app_interaction",@@ -871,21 +905,97 @@ def materialize_compact_task_intent("confidence": confidence,"needsConfirmation": False,"actionPlan": {- "tools": [- "app.openOrFocus",- "app.observe",- "ui.focusSearch",- "ui.setText",- "ui.pressReturn",- "app.verifyCommand",- ],+ "tools": tools,"inputEntity": "query",- "controlID": "search",- "focusKey": "Command+F",+ "controlID": control_id,+ "focusKey": focus_key,"verification": "commandAttempted",},- "metadata": {},+ "metadata": metadata,+ }+++def compact_app_finder_selection(+ compact: dict[str, Any],+ app_name: str,+ app_finder_catalog: list[dict[str, Any]],+) -> tuple[dict[str, Any], dict[str, Any]] | None:+ if not app_finder_catalog:+ return None+ requested_id = str(compact.get("appID") or "").strip()+ requested_capability_id = str(compact.get("capabilityID") or compact.get("selectedCapabilityID") or "").strip()+ app_words = normalized_words(app_name)+ for entry in app_finder_catalog:+ if not isinstance(entry, dict) or str(entry.get("supportStatus") or "") != "supported":+ continue+ entry_matches = requested_id and requested_id == str(entry.get("appID") or "")+ entry_matches = entry_matches or normalized_words(str(entry.get("appName") or "")) == app_words+ if not entry_matches:+ continue+ capabilities = entry.get("capabilities") if isinstance(entry.get("capabilities"), list) else []+ for capability in capabilities:+ if not isinstance(capability, dict):+ continue+ if not requested_capability_id or requested_capability_id == str(capability.get("id") or ""):+ return entry, capability+ return None+++def compact_tools(value: Any) -> list[str]:+ allowed = {+ "app.openOrFocus",+ "app.observe",+ "ui.newDocument",+ "ui.focusSearch",+ "ui.focusAddressBar",+ "ui.focusTextEntry",+ "ui.setText",+ "ui.pressReturn",+ "app.verifyCommand",+ "app.verifyVisibleText",}+ raw_items: list[Any]+ if isinstance(value, list):+ raw_items = value+ elif isinstance(value, str):+ raw_items = [item.strip() for item in re.split(r"[,|]", value)]+ else:+ raw_items = []+ result: list[str] = []+ for item in raw_items:+ tool = str(item).strip()+ if tool in allowed and tool not in result:+ result.append(tool)+ return result+++def compact_tools_for_control_profile(control_profile: str) -> list[str]:+ normalized = "_".join(normalized_words(control_profile))+ if "address" in normalized or "url" in normalized:+ return ["app.openOrFocus", "app.observe", "ui.focusAddressBar", "ui.setText", "ui.pressReturn", "app.verifyCommand"]+ if "new" in normalized or "document" in normalized or "editor" in normalized:+ return ["app.openOrFocus", "app.observe", "ui.newDocument", "ui.setText", "app.verifyCommand"]+ if "search" in normalized:+ return ["app.openOrFocus", "app.observe", "ui.focusSearch", "ui.setText", "ui.pressReturn", "app.verifyCommand"]+ return []+++def compact_control_id_for_tools(tools: list[str]) -> str:+ if "ui.focusAddressBar" in tools:+ return "addressBar"+ if "ui.focusSearch" in tools:+ return "search"+ if "ui.newDocument" in tools or "ui.focusTextEntry" in tools:+ return "editor"+ return ""+++def compact_focus_key_for_tools(tools: list[str]) -> str:+ if "ui.focusAddressBar" in tools:+ return "Command+L"+ if "ui.focusSearch" in tools:+ return "Command+F"+ return ""def decode_compact_object(compact_text: str) -> Any:@@ -894,7 +1004,19 @@ def decode_compact_object(compact_text: str) -> Any:return compactvalues: dict[str, Any] = {}- for key in ["appName", "goal", "query", "confidence"]:+ for key in [+ "appName",+ "goal",+ "query",+ "confidence",+ "appID",+ "capabilityID",+ "selectedCapabilityID",+ "controlProfile",+ "controlID",+ "focusKey",+ "tools",+ ]:match = re.search(rf"(?i)(?:^|[,\n])\s*{re.escape(key)}\s*:\s*([^,\n]+)", compact_text)if match:values[key] = match.group(1).strip().strip("\"'")@@ -910,9 +1032,7 @@ def compact_confidence(value: Any) -> float:def compact_query(value: Any, command: str) -> str:query = str(value or "").strip()- query_words = normalized_words(query)- command_words = set(normalized_words(command))- if len(query_words) >= 2 and all(word in command_words for word in query_words):+ if query:return queryreturn command.strip()@@ -1018,7 +1138,7 @@ def app_chain_repair_prompt(command: str, intent: dict[str, Any], context_snippe"If the command asks for fresh/current/reference data that should be found in another local app before creating the destination artifact, set needsChain=true.","When needsChain=true, appChain must be ordered source apps first and final destination app last.","Use only app names that appear in Available local apps when possible.",- "Examples: market data or market-cap tables use Stocks before Numbers; forecast tables use Weather before Numbers; place/distance tables use Maps before Numbers.",+ "Use app-chain examples or source-app preferences only when they appear in skill guidance, app catalog data, or memory context.",f"Command: {command}",f"Destination app: {target_app}","Current intent:",@@ -1089,11 +1209,11 @@ def document_text_payload_prompt(command: str) -> str:return "\n".join(["You repair missing document text for Donkey. Return strict JSON only.",- "Decide whether Command clearly asks to write or generate a meaningful finished text payload for Notes.",+ "Decide whether Command clearly asks to write or generate a meaningful finished text payload for the selected text app.","If it does, set canWrite=true and text to the final text to type. Text must be the content itself, not a label, not a restatement, and not instructions.","If details are sparse but the requested writing form is clear, write a short generic finished piece for that form.","If the requested object is malformed, nonsensical, or not a writing task, set canWrite=false, text=\"\", and assistantResponse to a brief clarification.",- "Example: Command 'write a people in notes' is malformed because 'a people' is not a meaningful writing form or payload; return canWrite=false.",+ "A malformed requested object is not a meaningful writing form or payload; return canWrite=false.",f"Command: {command}",])@@ -1319,6 +1439,7 @@ def task_intent_prompt(command: str,task_definitions: list[dict[str, Any]],context_snippets: list[Any] | None = None,+ skill_snippets: list[Any] | None = None,app_finder_catalog: list[dict[str, Any]] | None = None,) -> str:task_lines: list[str] = []@@ -1356,6 +1477,7 @@ def task_intent_prompt(]task_lines.append(" | ".join(item for item in parts if item))context = "\n".join(str(item) for item in (context_snippets or [])[:8] if str(item).strip())+ skill_guidance = "\n\n".join(str(item) for item in (skill_snippets or [])[:8] if str(item).strip())app_finder_catalog_json = json.dumps(compact_app_finder_catalog(app_finder_catalog),separators=(",", ":"),@@ -1369,34 +1491,20 @@ def task_intent_prompt("If Command is a question, greeting, conversation, malformed request, or lacks a real executable payload, do not invent one. Return taskType \"none\", targetAppName \"none\", empty entities and normalizedEntities, confidence 0, needsConfirmation=false, actionPlan.tools=[], and metadata.responseMode=conversation with metadata.assistantResponse containing a brief natural-language reply.","If Command is an executable local task with one ordinary missing detail, set needsConfirmation=true and include missingEntity in metadata.","If Command is executable, choose by capability and target app, not exact wording. Use only the provided task definitions; do not invent task types, unsupported entities, or actions.",- "For play/listen media requests, treat the turn as executable when a supported play_media capability or media_playback task is available; choose Music or another supported media app, set query to the requested artist/song/album, and do not downgrade it to conversation.",- "For every media playback request, include metadata.mediaSelection.kind. For explicit playable requests use explicit_song, explicit_album, or explicit_playlist. For vague artist-level media requests such as 'play some <artist>', do media-selection planning before returning JSON: pick one concrete playable song or album by that artist using model knowledge, set query to '<selected title> <artist>', and include metadata.mediaSelection.kind=representative_song or representative_album, metadata.mediaSelection.seed=<artist>, metadata.mediaSelection.selectedTitle=<title>, and metadata.mediaSelection.reason. Do not use an artist-only query unless the user explicitly asks to open the artist page, play an artist radio/station, or browse the artist.",- "If visible search results are provided in context for a media request, choose the highest-confidence playable Song row whose artist matches the requested seed; skip Artist, Playlist, category, and different-artist rows.","If no capability fits, choose conversation with taskType \"none\" and a helpful metadata.assistantResponse rather than a failed local-action message.","For dynamic local-item capabilities, app/file/folder names may come from the request, relevant local cache, or default-app inference; the catalog will verify availability before execution.",+ "Apply App skill guidance for app-specific workflows, control strategies, required metadata, and output shapes. Do not invent app-specific behavior that is absent from task definitions, catalog data, memory, or loaded skill guidance.","For write/create document requests: if the requested content is malformed or not meaningful enough to type, choose conversation; do not fabricate a document payload just to make the task executable.","For local_app_interaction, select the most likely local app for the user's goal, set entities.goal, and when text must be entered set entities.query plus normalizedEntities.query.","For local_app_interaction, fill actionPlan.tools with allowed tools only: app.openOrFocus, app.observe, ui.newDocument, ui.focusSearch, ui.focusAddressBar, ui.focusTextEntry, ui.setText, ui.pressReturn, app.verifyCommand, app.verifyVisibleText.",- "For website navigation, choose Safari or the user's browser, set query to the URL, use ui.focusAddressBar with controlID=addressBar and focusKey=Command+L, then ui.setText and ui.pressReturn.",- "For writing in Notes, choose Notes, create the requested prose in query, and use ui.newDocument followed by ui.setText.","For generative writing requests, query must be the complete final text to type, not a single category label, restatement of the request, or placeholder copied from these instructions.","If the writing type is clear but topic/details are sparse, compose a short generic piece that satisfies the requested writing type and put that complete text in query.",- "For spreadsheet or table creation, choose Numbers, put compact tab-separated table content in query, and use ui.newDocument followed by ui.setText. If exact live data is unavailable, make a table-shaped brief with a data-needed note; do not output a single sentence.",- "For spreadsheet/table requests that require fresh data from another local app, set targetAppName to the final destination app and include the source-to-destination chain in metadata.appChain as a JSON string array of app names. Example: a market-cap table should use metadata.appChain=[\"Stocks\",\"Numbers\"] and targetAppName=Numbers.","When ui.setText is present, entities.query and normalizedEntities.query must be non-empty.","If you cannot produce non-empty text for ui.setText, choose conversation; never return ui.setText with an empty query.",- "For sparse writing requests such as 'write a [form] in Notes', infer the requested form and write a short finished piece. If the requested object is malformed or nonsensical, choose conversation.",- "Example malformed writing boundary: 'write a people in Notes' is not a meaningful writing form or payload, so choose conversation rather than writing a definition.",- "entities.appName must be the human app name, such as Safari, Notes, Numbers, or Music; do not put a bundle identifier in appName.",+ "entities.appName must be the human app name, not a bundle identifier.","For local_app_interaction, set actionPlan.inputEntity to query when ui.setText should type the query, and set actionPlan.controlID/focusKey for the UI control strategy.","actionPlan must be one nested object containing tools, inputEntity, controlID, focusKey, and verification. Do not put inputEntity, controlID, focusKey, or verification at the top level.",- "The examples below show output structure only. Replace every example entity value with values inferred from Command and local cache; do not copy example query text unless the user asked for that exact text.",- "Media playback output shape when media_playback is provided: taskType=media_playback, targetAppName=Music, entities.query=<concrete playable title plus artist>, normalizedEntities.query=<concrete playable title plus artist>, metadata.mediaSelection.* when the user gave only an artist/genre/seed.",- "Media playback output shape for generic local_app_interaction: targetAppName=Music, entities.appName=Music, entities.goal=play media, entities.query=<concrete playable title plus artist>, actionPlan.tools=[app.openOrFocus, app.observe, ui.focusSearch, ui.setText, ui.pressReturn, app.verifyCommand], inputEntity=query, controlID=search, focusKey=Command+F, metadata.appFinder.selectedCapabilityID=play_media when selected from the app finder catalog, metadata.mediaSelection.* when the user gave only an artist/genre/seed.",- 'Example vague artist request output shape: {"taskType":"local_app_interaction","targetAppName":"Music","entities":{"appName":"Music","goal":"play media","query":"Viva La Vida Coldplay"},"normalizedEntities":{"appName":"Music","goal":"play media","query":"Viva La Vida Coldplay"},"confidence":0.9,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.focusSearch","ui.setText","ui.pressReturn","app.verifyCommand"],"inputEntity":"query","controlID":"search","focusKey":"Command+F","verification":"commandAttempted"},"metadata":{"appFinder.selectedCapabilityID":"play_media","mediaSelection.kind":"representative_song","mediaSelection.seed":"Coldplay","mediaSelection.selectedTitle":"Viva La Vida","mediaSelection.reason":"User asked for some Coldplay, so choose a concrete well-known song instead of an artist-only search."}}',- 'Example website output shape: {"taskType":"local_app_interaction","targetAppName":"Safari","entities":{"appName":"Safari","goal":"open requested website","query":"https://example.org"},"normalizedEntities":{"appName":"Safari","goal":"open requested website","query":"https://example.org"},"confidence":0.9,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.focusAddressBar","ui.setText","ui.pressReturn","app.verifyCommand"],"inputEntity":"query","controlID":"addressBar","focusKey":"Command+L","verification":"commandAttempted"},"metadata":{}}',- "Writing output shape: targetAppName=Notes, entities.appName=Notes, entities.goal=write requested text, entities.query=<the actual final text to type>, actionPlan.tools=[app.openOrFocus, app.observe, ui.newDocument, ui.setText, app.verifyCommand], inputEntity=query, controlID=editor.",- "Table output shape: targetAppName=Numbers, entities.appName=Numbers, entities.goal=create requested table, entities.query=<tab-separated rows for the requested table>, actionPlan.tools=[app.openOrFocus, app.observe, ui.newDocument, ui.setText, app.verifyCommand], inputEntity=query, controlID=editor.",+ "Use examples only when they are supplied by bounded skill guidance or task definitions. Replace every example entity value with values inferred from Command and local cache; do not copy example query text unless the user asked for that exact text.",'Conversation output shape: {"taskType":"none","targetAppName":"none","entities":{},"normalizedEntities":{},"confidence":0,"needsConfirmation":false,"actionPlan":{"tools":[],"inputEntity":"","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{"responseMode":"conversation","assistantResponse":"Hi! What would you like to work on?"}}','Example malformed request output shape: {"taskType":"none","targetAppName":"none","entities":{},"normalizedEntities":{},"confidence":0,"needsConfirmation":false,"actionPlan":{"tools":[],"inputEntity":"","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{"responseMode":"conversation","assistantResponse":"I can help, but I need a clearer thing to write before opening an app."}}',"For every other task type, actionPlan.tools must be empty.",@@ -1407,6 +1515,8 @@ def task_intent_prompt(f"Command: {command}","Relevant local cache:",context,+ "App skill guidance:",+ skill_guidance,"App finder catalog JSON:",app_finder_catalog_json,"Supported task capabilities:",