Open source CapCut alternative.
TypeScript
Update local task intent adapter flow
David Lecef8c4429556
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swiftindex a0eb41a2..567fa4cc 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift@@ -33,6 +33,11 @@ struct DocumentFormFillReviewRequest: Equatable, Sendable {var traceID: String}+private struct PointerPromptModelIntentInput: Equatable, Sendable {+ var command: String+ var contextSnippets: [String]+}+struct PointerPromptCommandContext: Sendable {var task: PointerPromptNotchTaskvar recentEvents: [PointerPromptTaskEvent]@@ -236,19 +241,26 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {let coordinator = await coordinatorRegistry.coordinator(for: taskID)var taskLiveRunner = liveRunnertaskLiveRunner.coordinator = coordinator- let modelCommand = Self.modelCommand(+ let modelInput = Self.modelInput(for: command,context: context,contextPacket: routing.contextPacket)- let redaction = redactor.redact(modelCommand, surface: .modelContext)+ let commandRedaction = redactor.redact(modelInput.command, surface: .modelContext)+ let contextRedactions = modelInput.contextSnippets.map {+ redactor.redact($0, surface: .modelContext)+ }+ let redactedContextSnippets = contextRedactions.map(\.redactedText)+ let redactionCount = commandRedaction.redactionCount+ + contextRedactions.reduce(0) { $0 + $1.redactionCount }let memoryProposalDecisions = (try? ProviderDecodedMemoryProposalHandler.decisions(from: Data("[]".utf8),decidedAt: Self.now())) ?? []let parseStartedAt = Self.uptimeMilliseconds()let localModelResult = await localModelResolver.resolve(- command: modelCommand,+ command: commandRedaction.redactedText,+ contextSnippets: redactedContextSnippets,sourceTraceID: traceID)let resolution = localModelResult.resolution@@ -264,14 +276,14 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {)}logModelResolution(- command: modelCommand,+ command: commandRedaction.redactedText,traceID: traceID,resolution: resolution,trace: localModelResult.trace,latencyMS: parseLatencyMS)if let projectedVisualizationPlan = LocalAppTaskAgentVisualizationBuilder.projectedPlan(- command: modelCommand,+ command: commandRedaction.redactedText,traceID: traceID,resolution: resolution) {@@ -281,7 +293,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {)}let semanticMemoryResults = await retrieveSemanticMemory(- command: modelCommand,+ command: commandRedaction.redactedText,resolution: resolution)let modelObservability = AIModelObservabilityReportBuilder.build(from: [localModelResult.trace])@@ -297,7 +309,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {"modelObservability.callCount": String(modelObservability.callCount),"modelObservability.acceptedCount": String(modelObservability.acceptedCount),"modelObservability.recoverySuccessCount": String(modelObservability.recoverySuccessCount),- "redaction.modelContext.count": String(redaction.redactionCount),+ "redaction.modelContext.count": String(redactionCount),"semanticMemory.resultCount": String(semanticMemoryResults.count),"semanticMemory.recordIDs": semanticMemoryResults.map(\.record.id).joined(separator: ","),"semanticMemory.targetID": semanticMemoryTargetID(for: resolution) ?? "",@@ -362,7 +374,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {}let result = await taskLiveRunner.run(- command: modelCommand,+ command: commandRedaction.redactedText,traceID: traceID,resolution: resolution,metadata: modelMetadata@@ -502,11 +514,15 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {?? trace.metadata["modelFallback.reason"]?? ""let modelDetail = resolution.metadata["model.detail"]+ ?? resolution.metadata["model.error"]?? resolution.metadata["model.http.bodyPreview"]?? resolution.metadata["model.fallback.http.bodyPreview"]+ ?? resolution.metadata["model.sidecar.outputPreview"]?? trace.metadata["detail"]+ ?? trace.metadata["error"]?? trace.metadata["http.bodyPreview"]?? trace.metadata["fallback.http.bodyPreview"]+ ?? trace.metadata["sidecar.outputPreview"]?? ""let fallbackStatus = trace.metadata["fallback.status"] ?? ""let latency = Self.formatLatency(latencyMS)@@ -575,6 +591,13 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {!assistantResponse.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {return assistantResponse}+ if resolution.metadata["reason"] == "localModelIntentUnavailable" {+ let modelStatus = resolution.metadata["modelCallStatus"] ?? ""+ if modelStatus == AIModelCallStatus.providerOutage.rawValue+ || modelStatus == AIModelCallStatus.timeout.rawValue {+ return "The local command parser is not available right now, so I couldn't safely run that local action."+ }+ }return "I couldn't find a supported local action for that yet."}@@ -725,23 +748,34 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {)}- private static func modelCommand(+ private static func modelInput(for command: String,context: PointerPromptCommandContext?,contextPacket: AppHarnessContextPacket- ) -> String {+ ) -> PointerPromptModelIntentInput {+ let modelCommand = contextPacket.currentTurn.textguard let context, context.isFollowUp else {- return contextPacket.currentTurn.text+ return PointerPromptModelIntentInput(+ command: modelCommand,+ contextSnippets: []+ )}- return [+ let taskContext = ["Existing task title: \(context.task.title)","Existing task original request: \(context.task.commandText)",- "Existing task status: \(context.task.status.rawValue)",- contextPacket.promptText+ "Existing task status: \(context.task.status.rawValue)"].compactMap(\.self).joined(separator: "\n\n")++ return PointerPromptModelIntentInput(+ command: modelCommand,+ contextSnippets: [+ taskContext,+ contextPacket.promptText+ ]+ )}private static func runtimeCapabilities(for catalog: LocalAppTaskCatalog) -> [String] {diff --git a/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift b/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swiftindex 889bbd30..1c6c7145 100644--- a/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift+++ b/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift@@ -110,7 +110,7 @@ public struct AIModelRegistry: Codable, Equatable, Sendable {modelID: "qwen2.5-0.5b-instruct-q4_k_m",endpoint: URL(string: "local://qwen2.5-0.5b-instruct-q4_k_m/task-intent")!,capabilities: [.textInput, .structuredOutputs],- timeoutMS: 20_000,+ timeoutMS: 30_000,promptVersion: "task-intent-v1",evalStatus: .candidate,docsURL: URL(string: "local://donkey/local-llm")!,diff --git a/apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swift b/apps/Donkey/Sources/DonkeyAI/LocalGeneratePlannerHintAdapter.swiftsimilarity index 96%rename from apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swiftrename to apps/Donkey/Sources/DonkeyAI/LocalGeneratePlannerHintAdapter.swiftindex d69ab979..1de041e2 100644--- a/apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/LocalGeneratePlannerHintAdapter.swift@@ -2,7 +2,7 @@ import DonkeyContractsimport DonkeyRuntimeimport Foundation-public struct OllamaPlannerHintAdapter: Sendable {+public struct LocalGeneratePlannerHintAdapter: Sendable {public static let schemaID = "planner_hint_v1"public var router: AIModelRouter@@ -204,12 +204,12 @@ public struct OllamaPlannerHintAdapter: Sendable {}public struct ProviderBackedSlowPlannerHintGenerator: SlowPlannerHintGenerating {- public var localAdapter: OllamaPlannerHintAdapter+ public var localAdapter: LocalGeneratePlannerHintAdapterpublic var onlineAdapter: OpenAIPlannerHintAdapterpublic var providerOrder: [AIModelProvider]public init(- localAdapter: OllamaPlannerHintAdapter = OllamaPlannerHintAdapter(),+ localAdapter: LocalGeneratePlannerHintAdapter = LocalGeneratePlannerHintAdapter(),onlineAdapter: OpenAIPlannerHintAdapter = OpenAIPlannerHintAdapter(),providerOrder: [AIModelProvider] = [.openAI]) {@@ -269,12 +269,12 @@ public struct ProviderBackedSlowPlannerHintGenerator: SlowPlannerHintGenerating}}-private struct OllamaGenerateResponse: Decodable {+private struct LocalGenerateResponse: Decodable {var response: String?}-private extension OllamaPlannerHintAdapter {+private extension LocalGeneratePlannerHintAdapter {static func outputText(from data: Data) throws -> String? {- try JSONDecoder().decode(OllamaGenerateResponse.self, from: data).response+ try JSONDecoder().decode(LocalGenerateResponse.self, from: data).response}}diff --git a/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift b/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swiftsimilarity index 94%rename from apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swiftrename to apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swiftindex 3e79bf30..2c6ad391 100644--- a/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift@@ -164,6 +164,16 @@ public struct ProcessBackedLocalLLMTaskIntentAdapter: TaskIntentParsingAdapter {))} catch {+ if let sidecarError = decodeSidecarError(+ result.outputData,+ entry: entry,+ request: request,+ sidecarResult: result,+ decodeError: error+ ) {+ return sidecarError+ }+return self.result(entry: entry,request: request,@@ -178,6 +188,34 @@ public struct ProcessBackedLocalLLMTaskIntentAdapter: TaskIntentParsingAdapter {}}+ 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 {@@ -263,7 +301,12 @@ private struct LocalLLMTaskIntentSidecarResponse: Codable, Equatable, Sendable {var metadata: [String: String]}-public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {+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@@ -316,7 +359,7 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {if response.statusCode == 404,fallbackFromModelID == nil,- let fallbackModelID = try? await fallbackOllamaModelID(+ let fallbackModelID = try? await fallbackLocalGenerateModelID(for: entry,excluding: [entry.modelID]),@@ -367,7 +410,7 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {definitions: request.taskDefinitions,originalCommand: request.command,sourceModelCallID: "model-call-\(request.sourceTraceID)",- parserName: "ollama-task-intent-v1"+ parserName: "local-generate-task-intent-v1")else {return result(@@ -413,11 +456,11 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {}}- private func fallbackOllamaModelID(+ private func fallbackLocalGenerateModelID(for entry: AIModelRegistryEntry,excluding excludedModelIDs: Set<String>) async throws -> String? {- var request = URLRequest(url: Self.ollamaAPIURL(for: entry.endpoint, path: "tags"))+ 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)@@ -425,14 +468,14 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {return nil}- let tags = try JSONDecoder().decode(OllamaTagsResponse.self, from: data)+ let tags = try JSONDecoder().decode(LocalGenerateTagsResponse.self, from: data)return Self.preferredInstalledModelID(from: tags.models,excluding: excludedModelIDs)}- private static func ollamaAPIURL(for endpoint: URL, path: String) -> URL {+ private static func localGenerateAPIURL(for endpoint: URL, path: String) -> URL {var components = URLComponents(url: endpoint, resolvingAgainstBaseURL: false)components?.path = "/api/\(path)"components?.query = nil@@ -440,7 +483,7 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {}private static func preferredInstalledModelID(- from models: [OllamaModelTag],+ from models: [LocalGenerateModelTag],excluding excludedModelIDs: Set<String>) -> String? {let candidates = models@@ -593,7 +636,9 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {"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: targetAppName=Music, entities.appName=Music, entities.goal=play media, entities.query=<artist/song/album to play>, actionPlan.tools=[app.openOrFocus, app.observe, ui.focusSearch, ui.setText, ui.pressReturn, app.verifyCommand], inputEntity=query, controlID=search, focusKey=Command+F.","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.",@@ -673,12 +718,13 @@ public struct LocalModelTaskIntentResolver: Sendable {public func resolve(command: String,+ contextSnippets: [String] = [],sourceTraceID: String) async -> (resolution: LocalAppTaskCatalogResolution, trace: AIModelCallTrace) {let request = TaskIntentAdapterRequest(command: command,taskDefinitions: catalog.taskDefinitions,- contextSnippets: [],+ contextSnippets: contextSnippets,sourceTraceID: sourceTraceID)let result = await adapter.parseTaskIntent(request)@@ -692,10 +738,13 @@ public struct LocalModelTaskIntentResolver: Sendable {for key in ["reason","detail",+ "error",+ "backend.provider","http.status","http.bodyPreview","modelOutput.empty","modelOutput.preview",+ "sidecar.outputPreview","fallback.status","fallback.validation","fallback.reason",@@ -720,15 +769,15 @@ public struct LocalModelTaskIntentResolver: Sendable {}}-private struct OllamaTaskIntentResponse: Decodable {+private struct LocalGenerateTaskIntentResponse: Decodable {var response: String?}-private struct OllamaTagsResponse: Decodable {- var models: [OllamaModelTag]+private struct LocalGenerateTagsResponse: Decodable {+ var models: [LocalGenerateModelTag]}-private struct OllamaModelTag: Decodable {+private struct LocalGenerateModelTag: Decodable {var name: Stringvar size: Int64?}@@ -1245,8 +1294,8 @@ private struct TaskIntentWire: Decodable {var metadata: [String: String]}-private extension OllamaTaskIntentAdapter {+private extension LocalGenerateTaskIntentAdapter {static func outputText(from data: Data) throws -> String? {- try JSONDecoder().decode(OllamaTaskIntentResponse.self, from: data).response+ try JSONDecoder().decode(LocalGenerateTaskIntentResponse.self, from: data).response}}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swiftindex 21a089db..9a5fff39 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift@@ -5,8 +5,8 @@ import Foundationimport Testingprivate let defaultLocalRuntimeModelID = "qwen2.5-0.5b-instruct-q4_k_m"-// Only used in explicit Ollama adapter unit tests; it is not a default runtime dependency.-private let explicitOllamaFixtureModelID = "qwen3:8b"+// Only used in explicit local-generate adapter unit tests; it is not a default runtime dependency.+private let explicitLocalGenerateFixtureModelID = "qwen3:8b"@Suitestruct AIHarnessAdapterTests {@@ -87,7 +87,7 @@ struct AIHarnessAdapterTests {#expect(selected.role == .taskIntent)#expect(selected.provider == .localRuntime)#expect(selected.modelID == defaultLocalRuntimeModelID)- #expect(selected.timeoutMS == 20_000)+ #expect(selected.timeoutMS == 30_000)}@Test@@ -340,16 +340,16 @@ struct AIHarnessAdapterTests {}@Test- func ollamaTaskIntentAdapterBuildsLocalRequestAndDecodesValidatedIntent() async throws {+ func localGenerateTaskIntentAdapterBuildsLocalRequestAndDecodesValidatedIntent() async throws {let httpClient = FakeAIHTTPClient(- data: ollamaResponseData(+ 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 = OllamaTaskIntentAdapter(+ let adapter = LocalGenerateTaskIntentAdapter(router: AIModelRouter(registry: AIModelRegistry(entries: [@@ -357,7 +357,7 @@ struct AIHarnessAdapterTests {id: "local-intent",role: .taskIntent,provider: .ollama,- modelID: explicitOllamaFixtureModelID,+ modelID: explicitLocalGenerateFixtureModelID,endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,promptVersion: "task-intent-v1")@@ -387,7 +387,7 @@ struct AIHarnessAdapterTests {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 == explicitOllamaFixtureModelID)+ #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")@@ -406,11 +406,11 @@ struct AIHarnessAdapterTests {}@Test- func ollamaTaskIntentAdapterUsesInstalledLocalModelWhenConfiguredModelIsMissing() async throws {+ func localGenerateTaskIntentAdapterUsesInstalledLocalModelWhenConfiguredModelIsMissing() async throws {let httpClient = SequencedFakeAIHTTPClient(responses: [HTTPStub(- data: Data("{\"error\":\"model '\(explicitOllamaFixtureModelID)' not found\"}".utf8),+ data: Data("{\"error\":\"model '\(explicitLocalGenerateFixtureModelID)' not found\"}".utf8),statusCode: 404),HTTPStub(@@ -418,7 +418,7 @@ struct AIHarnessAdapterTests {statusCode: 200),HTTPStub(- data: ollamaResponseData(+ 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":{}}"""@@ -427,7 +427,7 @@ struct AIHarnessAdapterTests {)])- let adapter = OllamaTaskIntentAdapter(+ let adapter = LocalGenerateTaskIntentAdapter(router: AIModelRouter(registry: AIModelRegistry(entries: [@@ -435,7 +435,7 @@ struct AIHarnessAdapterTests {id: "local-intent",role: .taskIntent,provider: .ollama,- modelID: explicitOllamaFixtureModelID,+ modelID: explicitLocalGenerateFixtureModelID,endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,promptVersion: "task-intent-v1")@@ -450,7 +450,7 @@ struct AIHarnessAdapterTests {command: "play some justin bieber",taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,contextSnippets: ["Music application com.apple.Music"],- sourceTraceID: "trace-ollama-model-fallback"+ sourceTraceID: "trace-local-generate-model-fallback"))@@ -459,7 +459,7 @@ struct AIHarnessAdapterTests {#expect(result.intent?.normalizedEntities["query"] == "Justin Bieber")#expect(result.trace.status == .completed)#expect(result.trace.modelID == "llama3:latest")- #expect(result.trace.metadata["modelFallback.originalModelID"] == explicitOllamaFixtureModelID)+ #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)@@ -533,6 +533,63 @@ struct AIHarnessAdapterTests {#expect(result.trace.status == .completed)}+ @Test+ func processBackedLocalLLMTaskIntentAdapterTreatsSidecarErrorPayloadAsProviderOutage() async {+ let adapter = ProcessBackedLocalLLMTaskIntentAdapter(+ router: AIModelRouter(registry: .defaultHybridPlanner),+ sidecarRunner: FakeSidecarRunner(+ result: LocalJSONSidecarResult(+ status: .completed,+ outputData: Data("""+ {"status":"error","metadata":{"reason":"localLLMGenerationFailed","detail":"Failed to create llama_context","backend.provider":"llama-cpp-python"}}+ """.utf8),+ latencyMS: 14,+ metadata: ["sidecar.role": "taskIntent"]+ )+ )+ )++ let result = await adapter.parseTaskIntent(+ TaskIntentAdapterRequest(+ command: "play some justin bieber",+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,+ sourceTraceID: "trace-local-llm-error"+ )+ )++ #expect(result.intent == nil)+ #expect(result.trace.status == .providerOutage)+ #expect(result.trace.validationStatus == "notValidated")+ #expect(result.trace.metadata["reason"] == "localLLMGenerationFailed")+ #expect(result.trace.metadata["detail"] == "Failed to create llama_context")+ #expect(result.trace.metadata["backend.provider"] == "llama-cpp-python")+ }++ @Test+ func localModelTaskIntentResolverPassesContextSnippetsSeparatelyFromCommand() async {+ let recorder = TaskIntentRequestRecorder()+ let resolver = LocalModelTaskIntentResolver(+ catalog: LocalAppTaskCatalog.defaultLocal(),+ adapter: RecordingTaskIntentAdapter(recorder: recorder)+ )++ _ = await resolver.resolve(+ command: "play some justin bieber",+ contextSnippets: [+ "Existing task title: play some justin bieber",+ "Recent thread: assistant could not find a supported action"+ ],+ sourceTraceID: "trace-context-snippets"+ )++ let request = await recorder.lastRequest()+ #expect(request?.command == "play some justin bieber")+ #expect(request?.contextSnippets == [+ "Existing task title: play some justin bieber",+ "Recent thread: assistant could not find a supported action"+ ])+ }+@Testfunc processBackedLocalLLMTaskIntentAdapterDecodesWrappedStructuredOutput() async throws {let adapter = ProcessBackedLocalLLMTaskIntentAdapter(@@ -723,7 +780,7 @@ struct AIHarnessAdapterTests {@Testfunc localModelTaskIntentResolverValidatesAgainstCatalogAvailability() async {let httpClient = FakeAIHTTPClient(- data: ollamaResponseData(+ 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":{}}"""@@ -735,7 +792,7 @@ struct AIHarnessAdapterTests {taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])),- adapter: OllamaTaskIntentAdapter(+ adapter: LocalGenerateTaskIntentAdapter(router: AIModelRouter(registry: AIModelRegistry(entries: [@@ -743,7 +800,7 @@ struct AIHarnessAdapterTests {id: "local-intent",role: .taskIntent,provider: .ollama,- modelID: explicitOllamaFixtureModelID,+ modelID: explicitLocalGenerateFixtureModelID,endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,promptVersion: "task-intent-v1")@@ -768,7 +825,7 @@ struct AIHarnessAdapterTests {@Testfunc localModelTaskIntentResolverResolvesDynamicLocalItemLookup() async {let httpClient = FakeAIHTTPClient(- data: ollamaResponseData(+ 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":{}}"""@@ -783,7 +840,7 @@ struct AIHarnessAdapterTests {installedApplicationNames: ["Figma": "com.figma.Desktop"])),- adapter: OllamaTaskIntentAdapter(+ adapter: LocalGenerateTaskIntentAdapter(router: AIModelRouter(registry: AIModelRegistry(entries: [@@ -791,7 +848,7 @@ struct AIHarnessAdapterTests {id: "local-intent",role: .taskIntent,provider: .ollama,- modelID: explicitOllamaFixtureModelID,+ modelID: explicitLocalGenerateFixtureModelID,endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,promptVersion: "task-intent-v1")@@ -920,7 +977,7 @@ struct AIHarnessAdapterTests {@Testfunc localModelTaskIntentResolverAcceptsClosestLowConfidenceClassification() async {let httpClient = FakeAIHTTPClient(- data: ollamaResponseData(+ data: localGenerateResponseData(response: """{"taskType":"weather_lookup","targetAppName":"Weather","entities":{},"normalizedEntities":{},"confidence":0.2,"needsConfirmation":false,"actionPlan":{"tools":[],"inputEntity":"","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{}}"""@@ -932,7 +989,7 @@ struct AIHarnessAdapterTests {taskDefinitions: BuiltInLocalAppTaskDefinitions.benchmarkFixtures,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])),- adapter: OllamaTaskIntentAdapter(+ adapter: LocalGenerateTaskIntentAdapter(router: AIModelRouter(registry: AIModelRegistry(entries: [@@ -940,7 +997,7 @@ struct AIHarnessAdapterTests {id: "local-intent",role: .taskIntent,provider: .ollama,- modelID: explicitOllamaFixtureModelID,+ modelID: explicitLocalGenerateFixtureModelID,endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,promptVersion: "task-intent-v1")@@ -964,7 +1021,7 @@ struct AIHarnessAdapterTests {@Testfunc localModelTaskIntentResolverPreservesConversationResponseForMalformedTask() async {let httpClient = FakeAIHTTPClient(- data: ollamaResponseData(+ 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."}}"""@@ -976,7 +1033,7 @@ struct AIHarnessAdapterTests {taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.Notes"])),- adapter: OllamaTaskIntentAdapter(+ adapter: LocalGenerateTaskIntentAdapter(router: AIModelRouter(registry: AIModelRegistry(entries: [@@ -984,7 +1041,7 @@ struct AIHarnessAdapterTests {id: "local-intent",role: .taskIntent,provider: .ollama,- modelID: explicitOllamaFixtureModelID,+ modelID: explicitLocalGenerateFixtureModelID,endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,promptVersion: "task-intent-v1")@@ -1346,23 +1403,23 @@ struct AIHarnessAdapterTests {}@Test- func ollamaAdapterBuildsLocalGenerateRequestAndDecodesStructuredHint() async throws {+ func localGenerateAdapterBuildsLocalGenerateRequestAndDecodesStructuredHint() async throws {let httpClient = FakeAIHTTPClient(- data: ollamaResponseData(+ data: localGenerateResponseData(response: """{"id":"local-hint-1","goal":"recover locally","policyName":"local-planner-policy","priorities":["observe menu"],"preferredActions":["observe"],"avoidActions":["tapTarget"],"confidence":0.74,"expiryMilliseconds":3000}"""),statusCode: 200)- let adapter = OllamaPlannerHintAdapter(+ let adapter = LocalGeneratePlannerHintAdapter(router: AIModelRouter(registry: AIModelRegistry(entries: [entry(id: "local-planner",provider: .ollama,- modelID: explicitOllamaFixtureModelID,+ modelID: explicitLocalGenerateFixtureModelID,endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!)]@@ -1382,7 +1439,7 @@ struct AIHarnessAdapterTests {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 == explicitOllamaFixtureModelID)+ #expect(body["model"] as? String == explicitLocalGenerateFixtureModelID)#expect(body["stream"] as? Bool == false)#expect(body["format"] as? [String: Any] != nil)#expect(request.value(forHTTPHeaderField: "Authorization") == nil)@@ -1390,14 +1447,14 @@ struct AIHarnessAdapterTests {@Testfunc providerBackedSlowPlannerFallsBackFromLocalToOnlineProvider() async {- let localAdapter = OllamaPlannerHintAdapter(+ let localAdapter = LocalGeneratePlannerHintAdapter(router: AIModelRouter(registry: AIModelRegistry(entries: [entry(id: "local-planner",provider: .ollama,- modelID: explicitOllamaFixtureModelID,+ modelID: explicitLocalGenerateFixtureModelID,endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!)]@@ -1578,12 +1635,12 @@ struct AIHarnessAdapterTests {return Data("{\"id\":\"resp-1\",\"output_text\":\"\(escaped)\"}".utf8)}- private func ollamaResponseData(response: String) -> Data {+ private func localGenerateResponseData(response: String) -> Data {let escaped = response.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"").replacingOccurrences(of: "\n", with: "\\n")- return Data("{\"model\":\"\(explicitOllamaFixtureModelID)\",\"response\":\"\(escaped)\",\"done\":true}".utf8)+ return Data("{\"model\":\"\(explicitLocalGenerateFixtureModelID)\",\"response\":\"\(escaped)\",\"done\":true}".utf8)}private func providerOutput(@@ -1776,6 +1833,43 @@ private struct FakeSidecarRunner: LocalJSONSidecarRunning {}}+private actor TaskIntentRequestRecorder {+ private var requests: [TaskIntentAdapterRequest] = []++ func record(_ request: TaskIntentAdapterRequest) {+ requests.append(request)+ }++ func lastRequest() -> TaskIntentAdapterRequest? {+ requests.last+ }+}++private struct RecordingTaskIntentAdapter: TaskIntentParsingAdapter {+ var recorder: TaskIntentRequestRecorder++ func parseTaskIntent(_ request: TaskIntentAdapterRequest) async -> TaskIntentAdapterResult {+ await recorder.record(request)+ return TaskIntentAdapterResult(+ intent: nil,+ trace: AIModelCallTrace(+ id: "model-call-recording",+ role: .taskIntent,+ provider: .localRuntime,+ modelID: defaultLocalRuntimeModelID,+ promptVersion: "task-intent-v1",+ schemaID: "task_intent_v1",+ latencyMS: nil,+ timeoutMS: 4_000,+ status: .providerOutage,+ validationStatus: "notValidated",+ sourceTraceID: request.sourceTraceID,+ metadata: ["reason": "recordingAdapter"]+ )+ )+ }+}+private func localLLMSidecarOutputData(outputText: String,metadata: [String: String]diff --git a/docs/guides/decision-system.md b/docs/guides/decision-system.mdindex 30febf82..abfa0ce3 100644--- a/docs/guides/decision-system.md+++ b/docs/guides/decision-system.md@@ -95,6 +95,6 @@ Weather, Music, and document form-fill fixtures remain useful for tests and repl- Prompt command handling starts in `apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift`.- Harness routing and context packet assembly live in `apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swift`.-- Task-intent parsing protocol and the process-backed local runtime adapter live in `apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift`; the Ollama adapter in that file is an explicit adapter, not the default runtime path.+- Task-intent parsing protocol and the process-backed local runtime adapter live in `apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift`; the local-generate adapter in that file is an explicit adapter for Ollama-compatible providers, not the default runtime path.- Catalog validation and generic local-app interaction materialization live in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift`.- Guarded execution lives in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift` and the action-engine backends.