Open source CapCut alternative.
TypeScript
Make local LLM runtime self-sufficient
David Le7024b4f8e626
diff --git a/AGENTS.md b/AGENTS.mdindex 1ac1a371..eef2f48f 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -11,6 +11,12 @@ Use `plans/master-plan.md` as the active implementation driver when it exists anUse other `plans/` files only for background unless the user explicitly asks to plan from them or the master plan names them as cleanup targets. Do not let older plans override the current master plan.+## Harness And LLM Work++Before changing the agent harness, task-intent routing, local-model adapters, LLM prompts, memory retrieval for prompt handling, or local-app decision code, read `docs/guides/agent-harness.md`.++Never infer semantic intent by string matching raw user input. Do not add phrase lists, prefixes, suffixes, regexes, app-name checks, greeting/help classifiers, or other natural-language command-text matching to decide what the user wants. Raw user text has too many variations to handle reliably. Pass the turn through an LLM or another typed model/runtime boundary first, get structured output, then do deterministic matching only on that structured output or on non-semantic technical fields.+## Site ProjectBefore changing `site/` UI, routes, API handlers, or data access patterns:diff --git a/apps/Donkey/Sources/Donkey/LocalRuntimeOnboardingWindowController.swift b/apps/Donkey/Sources/Donkey/LocalRuntimeOnboardingWindowController.swiftindex 92f8e2c4..02788d6f 100644--- a/apps/Donkey/Sources/Donkey/LocalRuntimeOnboardingWindowController.swift+++ b/apps/Donkey/Sources/Donkey/LocalRuntimeOnboardingWindowController.swift@@ -27,6 +27,7 @@ final class LocalRuntimeOnboardingWindowController: NSWindowController {await model.refresh()guard model.needsSetup else { return }showSetup()+ await model.setup()}}diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swiftindex 44674f91..a0eb41a2 100644--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift@@ -101,7 +101,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {AgentVisualizationPlanResolverRequest(command: command,runtimeCapabilities: Self.runtimeCapabilities(for: catalog),- cacheSnippets: memoryStore?.contextSnippets(for: command) ?? [],+ cacheSnippets: [],sourceTraceID: traceID))@@ -531,8 +531,6 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {private func routingHint(for routing: AppHarnessRoutingResult) -> String {let router = routing.outcome.metadata["router"] ?? ""switch router {- case "simpleArithmetic":- return "Answered a simple arithmetic question locally; no app workflow was run."case "followUpActionContext":return "Follow-up turn is being treated as an action for the existing task."case "modelIntent":@@ -769,7 +767,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {),recentEvents: context?.recentEvents ?? [],assets: context?.assets ?? [],- memory: SQLiteAgentMemoryStore.shared?.contextSnippets(for: command) ?? [],+ memory: [],policy: ["localInput": "guarded"])}diff --git a/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift b/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swiftindex c13f7f07..06bb3c5c 100644--- a/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift+++ b/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift@@ -104,16 +104,16 @@ public struct AIModelRegistry: Codable, Equatable, Sendable {public static let defaultHybridPlanner = AIModelRegistry(entries: [AIModelRegistryEntry(- id: "local-runtime-task-intent-qwen3",+ id: "local-runtime-task-intent-qwen3-0-6b",role: .taskIntent,provider: .localRuntime,- modelID: "qwen3:8b",- endpoint: URL(string: "local://qwen3-8b/task-intent")!,+ modelID: "qwen3-0.6b-q4_0",+ endpoint: URL(string: "local://qwen3-0.6b-q4_0/task-intent")!,capabilities: [.textInput, .structuredOutputs],timeoutMS: 20_000,promptVersion: "task-intent-v1",evalStatus: .candidate,- docsURL: URL(string: "https://ollama.com/library/qwen3")!,+ docsURL: URL(string: "local://donkey/local-llm")!,rollbackID: nil,metadata: ["local": "true",@@ -121,23 +121,6 @@ public struct AIModelRegistry: Codable, Equatable, Sendable {"sidecarEnvironmentVariable": "DONKEY_LOCAL_LLM_RUNNER"]),- AIModelRegistryEntry(- id: "ollama-task-intent-local",- role: .taskIntent,- provider: .ollama,- modelID: "qwen3:8b",- endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,- capabilities: [.textInput, .structuredOutputs],- timeoutMS: 20_000,- promptVersion: "task-intent-v1",- evalStatus: .candidate,- docsURL: URL(string: "https://docs.ollama.com/api")!,- rollbackID: nil,- metadata: [- "local": "true",- "docsSource": "official Ollama API docs"- ]- ),AIModelRegistryEntry(id: "local-voice-transcription-parakeet-tdt-0.6b-v3",role: .voiceTranscription,@@ -164,23 +147,6 @@ public struct AIModelRegistry: Codable, Equatable, Sendable {"fallbackPolicy": "none"]),- AIModelRegistryEntry(- id: "ollama-planner-hint-local",- role: .plannerHint,- provider: .ollama,- modelID: "qwen3:8b",- endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,- capabilities: [.textInput, .structuredOutputs],- timeoutMS: 8_000,- promptVersion: "planner-hint-v1",- evalStatus: .candidate,- docsURL: URL(string: "https://docs.ollama.com/api")!,- rollbackID: nil,- metadata: [- "local": "true",- "docsSource": "official Ollama API docs"- ]- ),AIModelRegistryEntry(id: "openai-planner-hint-default",role: .plannerHint,diff --git a/apps/Donkey/Sources/DonkeyAI/LocalTaskFollowUpResolver.swift b/apps/Donkey/Sources/DonkeyAI/LocalTaskFollowUpResolver.swiftindex e5e4a7aa..93495663 100644--- a/apps/Donkey/Sources/DonkeyAI/LocalTaskFollowUpResolver.swift+++ b/apps/Donkey/Sources/DonkeyAI/LocalTaskFollowUpResolver.swift@@ -116,6 +116,9 @@ public struct ProcessBackedLocalLLMTaskFollowUpResolver: PointerPromptFollowUpRecandidates: request.candidates,sourceTraceID: request.sourceTraceID,modelID: entry.modelID,+ cacheDirectory: LocalModelRuntimeExecutableResolver().modelCacheDirectoryPath(+ environmentVariableName: "DONKEY_LOCAL_LLM_RUNNER"+ ),metadata: ["schemaID": Self.schemaID,"promptVersion": entry.promptVersion@@ -232,6 +235,7 @@ private struct LocalLLMTaskFollowUpSidecarRequest: Codable, Equatable, Sendablevar candidates: [PointerPromptFollowUpCandidate]var sourceTraceID: Stringvar modelID: String+ var cacheDirectory: String?var metadata: [String: String]}diff --git a/apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swift b/apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swiftindex 106914ee..d69ab979 100644--- a/apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/OllamaPlannerHintAdapter.swift@@ -211,7 +211,7 @@ public struct ProviderBackedSlowPlannerHintGenerator: SlowPlannerHintGeneratingpublic init(localAdapter: OllamaPlannerHintAdapter = OllamaPlannerHintAdapter(),onlineAdapter: OpenAIPlannerHintAdapter = OpenAIPlannerHintAdapter(),- providerOrder: [AIModelProvider] = [.ollama, .openAI]+ providerOrder: [AIModelProvider] = [.openAI]) {self.localAdapter = localAdapterself.onlineAdapter = onlineAdapterdiff --git a/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift b/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swiftindex e9296966..3e79bf30 100644--- a/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift@@ -85,6 +85,9 @@ public struct ProcessBackedLocalLLMTaskIntentAdapter: TaskIntentParsingAdapter {contextSnippets: request.contextSnippets,sourceTraceID: request.sourceTraceID,modelID: entry.modelID,+ cacheDirectory: LocalModelRuntimeExecutableResolver().modelCacheDirectoryPath(+ environmentVariableName: "DONKEY_LOCAL_LLM_RUNNER"+ ),metadata: ["schemaID": Self.schemaID,"promptVersion": entry.promptVersion@@ -251,6 +254,7 @@ private struct LocalLLMTaskIntentSidecarRequest: Codable, Equatable, Sendable {var contextSnippets: [String]var sourceTraceID: Stringvar modelID: String+ var cacheDirectory: String?var metadata: [String: String]}@@ -653,56 +657,6 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {}}-public struct FallbackTaskIntentParsingAdapter: TaskIntentParsingAdapter {- public var primary: any TaskIntentParsingAdapter- public var fallback: any TaskIntentParsingAdapter-- public init(- primary: any TaskIntentParsingAdapter,- fallback: any TaskIntentParsingAdapter- ) {- self.primary = primary- self.fallback = fallback- }-- public func parseTaskIntent(_ request: TaskIntentAdapterRequest) async -> TaskIntentAdapterResult {- let primaryResult = await primary.parseTaskIntent(request)- guard primaryResult.intent == nil,- [.invalidOutput, .providerOutage, .timeout].contains(primaryResult.trace.status)- else {- return primaryResult- }-- let fallbackResult = await fallback.parseTaskIntent(request)- guard fallbackResult.intent != nil else {- var trace = primaryResult.trace- trace.metadata["fallback.status"] = fallbackResult.trace.status.rawValue- trace.metadata["fallback.validation"] = fallbackResult.trace.validationStatus- trace.metadata["fallback.provider"] = fallbackResult.trace.provider.rawValue- trace.metadata["fallback.modelID"] = fallbackResult.trace.modelID- if let reason = fallbackResult.trace.metadata["reason"] ?? fallbackResult.trace.metadata["modelFallback.reason"] {- trace.metadata["fallback.reason"] = reason- }- if let httpStatus = fallbackResult.trace.metadata["http.status"] {- trace.metadata["fallback.http.status"] = httpStatus- }- if let bodyPreview = fallbackResult.trace.metadata["http.bodyPreview"] {- trace.metadata["fallback.http.bodyPreview"] = bodyPreview- }- if let selectedModelID = fallbackResult.trace.metadata["modelFallback.selectedModelID"] {- trace.metadata["fallback.modelFallback.selectedModelID"] = selectedModelID- }- return TaskIntentAdapterResult(intent: nil, trace: trace)- }-- var trace = fallbackResult.trace- trace.metadata["fallback.primaryStatus"] = primaryResult.trace.status.rawValue- trace.metadata["fallback.primaryValidation"] = primaryResult.trace.validationStatus- trace.metadata["fallback.used"] = "true"- return TaskIntentAdapterResult(intent: fallbackResult.intent, trace: trace)- }-}-public struct LocalModelTaskIntentResolver: Sendable {public var catalog: LocalAppTaskCatalogpublic var adapter: any TaskIntentParsingAdapter@@ -710,10 +664,7 @@ public struct LocalModelTaskIntentResolver: Sendable {public init(catalog: LocalAppTaskCatalog,adapter: any TaskIntentParsingAdapter = PriorityQueuedTaskIntentParsingAdapter(- base: FallbackTaskIntentParsingAdapter(- primary: ProcessBackedLocalLLMTaskIntentAdapter(),- fallback: OllamaTaskIntentAdapter()- )+ base: ProcessBackedLocalLLMTaskIntentAdapter())) {self.catalog = catalog@@ -724,14 +675,13 @@ public struct LocalModelTaskIntentResolver: Sendable {command: String,sourceTraceID: String) async -> (resolution: LocalAppTaskCatalogResolution, trace: AIModelCallTrace) {- let result = await adapter.parseTaskIntent(- TaskIntentAdapterRequest(- command: command,- taskDefinitions: catalog.taskDefinitions,- contextSnippets: SQLiteAgentMemoryStore.shared?.contextSnippets(for: command) ?? [],- sourceTraceID: sourceTraceID- )+ let request = TaskIntentAdapterRequest(+ command: command,+ taskDefinitions: catalog.taskDefinitions,+ contextSnippets: [],+ sourceTraceID: sourceTraceID)+ let result = await adapter.parseTaskIntent(request)guard let intent = result.intent else {var metadata = [diff --git a/apps/Donkey/Sources/DonkeyAI/PointerCoachCursorGuideResolver.swift b/apps/Donkey/Sources/DonkeyAI/PointerCoachCursorGuideResolver.swiftindex c77ac2a2..3cf7b37d 100644--- a/apps/Donkey/Sources/DonkeyAI/PointerCoachCursorGuideResolver.swift+++ b/apps/Donkey/Sources/DonkeyAI/PointerCoachCursorGuideResolver.swift@@ -103,6 +103,9 @@ public struct ProcessBackedLocalLLMAgentVisualizationPlanResolver: AgentVisualizcacheSnippets: request.cacheSnippets,sourceTraceID: request.sourceTraceID,modelID: entry.modelID,+ cacheDirectory: LocalModelRuntimeExecutableResolver().modelCacheDirectoryPath(+ environmentVariableName: "DONKEY_LOCAL_LLM_RUNNER"+ ),metadata: ["schemaID": Self.schemaID,"promptVersion": entry.promptVersion@@ -314,6 +317,7 @@ private struct LocalLLMAgentVisualizationPlanSidecarRequest: Codable, Equatable,var cacheSnippets: [String]var sourceTraceID: Stringvar modelID: String+ var cacheDirectory: String?var metadata: [String: String]}diff --git a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnClassifier.swift b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnClassifier.swiftindex d6c37405..d3d23e38 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnClassifier.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnClassifier.swift@@ -1,28 +1,22 @@import DonkeyContracts-import Foundationpublic enum AppHarnessTurnClassificationKind: String, Equatable, Sendable {- case actionable- case answercase unknown}public struct AppHarnessTurnClassification: Equatable, Sendable {public var kind: AppHarnessTurnClassificationKind- public var response: String?public var router: Stringpublic var missingDetail: String?public var metadata: [String: String]public init(kind: AppHarnessTurnClassificationKind,- response: String? = nil,router: String,missingDetail: String? = nil,metadata: [String: String] = [:]) {self.kind = kind- self.response = responseself.router = routerself.missingDetail = missingDetailself.metadata = metadata@@ -33,31 +27,13 @@ public struct AppHarnessTurnClassifier: Sendable {public init() {}public func classify(- text: String,+ text _: String,request _: AppHarnessTurnRequest,catalog _: LocalAppTaskCatalog) -> AppHarnessTurnClassification {- let trimmedText = text.trimmingCharacters(in: .whitespacesAndNewlines)- let memoryCandidates = (try? SQLiteAgentMemoryStore.shared?.search(query: AgentMemoryQuery(- text: trimmedText,- scope: .global,- kinds: [.localItem, .negativeLookup, .taskDefinition],- budget: AgentMemoryRetrievalBudget(maxRecords: 3, maxPromptCharacters: 800, minRelevance: 0.05)- ))) ?? []let classifierMetadata = [- "classifier": "fast-local-v1",- "memory.candidateKinds": memoryCandidates.map { $0.record.kind.rawValue }.joined(separator: ","),- "memory.candidateNames": memoryCandidates.map(\.record.value).joined(separator: ",")+ "classifier": "model-intent-required-v1"]- if let response = Self.simpleArithmeticResponse(for: trimmedText) {- return AppHarnessTurnClassification(- kind: .answer,- response: response,- router: "simpleArithmetic",- metadata: classifierMetadata- )- }-return AppHarnessTurnClassification(kind: .unknown,router: "modelIntentRequired",@@ -65,46 +41,4 @@ public struct AppHarnessTurnClassifier: Sendable {metadata: classifierMetadata)}-- private static func simpleArithmeticResponse(for text: String) -> String? {- let pattern = #"(-?\d+(?:\.\d+)?)\s*([+\-*/×x÷])\s*(-?\d+(?:\.\d+)?)"#- guard let regex = try? NSRegularExpression(pattern: pattern),- let match = regex.firstMatch(- in: text,- range: NSRange(text.startIndex..<text.endIndex, in: text)- ),- let lhsRange = Range(match.range(at: 1), in: text),- let operatorRange = Range(match.range(at: 2), in: text),- let rhsRange = Range(match.range(at: 3), in: text),- let lhs = Double(text[lhsRange]),- let rhs = Double(text[rhsRange])- else {- return nil- }-- let operation = String(text[operatorRange])- let value: Double- switch operation {- case "+":- value = lhs + rhs- case "-":- value = lhs - rhs- case "*", "x", "X", "×":- value = lhs * rhs- case "/", "÷":- guard rhs != 0 else { return "I can't divide by zero." }- value = lhs / rhs- default:- return nil- }-- return "\(formatNumber(lhs)) \(operation) \(formatNumber(rhs)) = \(formatNumber(value))."- }-- private static func formatNumber(_ value: Double) -> String {- if value.rounded() == value {- return String(Int(value))- }- return String(value)- }}diff --git a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swift b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swiftindex 8713293d..dbf48d99 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swift@@ -460,11 +460,6 @@ public struct AppHarnessTurnRouter: Sendable {)}- let modelIntentResolution = LocalAppTaskCatalogResolution(- status: .unsupportedCommand,- metadata: ["reason": "modelIntentRequired"]- )-let classification = turnClassifier.classify(text: trimmedText,request: request,@@ -478,42 +473,21 @@ public struct AppHarnessTurnRouter: Sendable {decision: decision(kind: .runLocalTask,traceID: traceID,- resolution: modelIntentResolution,metadata: ["router": "followUpActionContext"]),- resolution: modelIntentResolution,metadata: ["router": "followUpActionContext"]))}- if classification.kind == .answer,- let response = classification.response {- return AppHarnessRoutingResult(- contextPacket: packet,- outcome: AppHarnessRoutingOutcome(- decision: decision(- kind: .respond,- traceID: traceID,- message: response,- metadata: ["router": classification.router]- ),- assistantResponse: response,- metadata: ["router": classification.router].merging(classification.metadata) { current, _ in current }- )- )- }-return AppHarnessRoutingResult(contextPacket: packet,outcome: AppHarnessRoutingOutcome(decision: decision(kind: .runLocalTask,traceID: traceID,- resolution: modelIntentResolution,metadata: ["router": "modelIntent"]),- resolution: modelIntentResolution,metadata: ["router": "modelIntent"].merging(classification.metadata) { current, _ in current }))diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swiftindex 8b9f4abc..9e12de52 100644--- a/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalModelRuntimeSetup.swift@@ -468,18 +468,17 @@ public struct LocalModelRuntimeSetupManager: Sendable {displayName: "Local command parser LLM",environmentVariableName: "DONKEY_LOCAL_LLM_RUNNER",expectedExecutableRelativePath: "bin/donkey-local-llm",- modelName: "qwen3:8b",- downloadPageURL: URL(string: "https://ollama.com/library/qwen3"),+ modelName: "qwen3-0.6b-q4_0",+ downloadPageURL: nil,manifestURL: Self.defaultPackageManifestURL(for: .localLLM),installSteps: ["Click Set Up in Donkey after installing the app.",- "Donkey asks the local LLM runner to download and cache qwen3:8b.",+ "Donkey downloads and verifies the configured local command-parser model weights.","Donkey records bin/donkey-local-llm in Application Support."],metadata: ["sidecar.role": "localLLM",- "modelWeights.provider": "ollama",- "modelWeights.ollamaModel": "qwen3:8b"+ "modelWeights.provider": "donkey-managed-download"])]@@ -827,9 +826,7 @@ public struct LocalModelRuntimeSetupManager: Sendable {)}- guard let response = try? Self.decoder().decode(LocalModelRuntimeHealthResponse.self, from: result.outputData),- response.status == "ok"- else {+ guard let response = try? Self.decoder().decode(LocalModelRuntimeHealthResponse.self, from: result.outputData) else {return LocalModelRuntimeHealthReport(runtimeID: runtimeID,state: .invalidOutput,@@ -838,6 +835,30 @@ public struct LocalModelRuntimeSetupManager: Sendable {)}+ let metadata = result.metadata.merging(response.metadata) { current, _ in current }+ guard response.status == "ok" else {+ return LocalModelRuntimeHealthReport(+ runtimeID: runtimeID,+ state: .failed,+ runtimeVersion: response.runtimeVersion,+ modelID: response.modelID,+ sidecarProtocolVersion: response.protocolVersion,+ latencyMS: result.latencyMS,+ metadata: metadata+ )+ }+ if ["missing", "notConfigured", "externalUnavailable"].contains(metadata["modelWeights.status"] ?? "") {+ return LocalModelRuntimeHealthReport(+ runtimeID: runtimeID,+ state: .failed,+ runtimeVersion: response.runtimeVersion,+ modelID: response.modelID,+ sidecarProtocolVersion: response.protocolVersion,+ latencyMS: result.latencyMS,+ metadata: metadata+ )+ }+return LocalModelRuntimeHealthReport(runtimeID: runtimeID,state: .healthy,@@ -845,7 +866,7 @@ public struct LocalModelRuntimeSetupManager: Sendable {modelID: response.modelID,sidecarProtocolVersion: response.protocolVersion,latencyMS: result.latencyMS,- metadata: result.metadata.merging(response.metadata) { current, _ in current }+ metadata: metadata)}@@ -1007,6 +1028,17 @@ public struct LocalModelRuntimeSetupManager: Sendable {try configuredEnvironment()[environmentVariableName]}+ public func modelCacheDirectoryPath(environmentVariableName: String) throws -> String? {+ guard let spec = specs.first(where: { $0.environmentVariableName == environmentVariableName }) else {+ return nil+ }+ let registry = try loadRegistry()+ guard let installation = registry.installations[spec.id.rawValue] else {+ return nil+ }+ return modelCacheDirectory(for: installation).path+ }+@discardableResultpublic func removeRuntime(runtimeID: LocalModelRuntimeID,@@ -1272,4 +1304,8 @@ public struct LocalModelRuntimeExecutableResolver: Sendable {public func executablePath(environmentVariableName: String) -> String? {try? setupManagerFactory().executablePath(environmentVariableName: environmentVariableName)}++ public func modelCacheDirectoryPath(environmentVariableName: String) -> String? {+ try? setupManagerFactory().modelCacheDirectoryPath(environmentVariableName: environmentVariableName)+ }}diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swiftindex ea83fe6f..b83bc7a6 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift@@ -4,6 +4,10 @@ import DonkeyRuntimeimport Foundationimport Testing+private let defaultLocalRuntimeModelID = "qwen3-0.6b-q4_0"+// Only used in explicit Ollama adapter unit tests; it is not a default runtime dependency.+private let explicitOllamaFixtureModelID = "qwen3:8b"+@Suitestruct AIHarnessAdapterTests {@Test@@ -52,7 +56,7 @@ struct AIHarnessAdapterTests {let registry = AIModelRegistry(entries: [entry(id: "online", provider: .openAI, modelID: "gpt-5.2", evalStatus: .candidate),- entry(id: "local", provider: .ollama, modelID: "qwen3:8b", evalStatus: .candidate)+ entry(id: "local", provider: .localRuntime, modelID: defaultLocalRuntimeModelID, evalStatus: .candidate)])let router = AIModelRouter(registry: registry)@@ -65,7 +69,7 @@ struct AIHarnessAdapterTests {)#expect(selected.id == "local")- #expect(selected.provider == .ollama)+ #expect(selected.provider == .localRuntime)}@Test@@ -79,13 +83,28 @@ struct AIHarnessAdapterTests {))- #expect(selected.id == "local-runtime-task-intent-qwen3")+ #expect(selected.id == "local-runtime-task-intent-qwen3-0-6b")#expect(selected.role == .taskIntent)#expect(selected.provider == .localRuntime)- #expect(selected.modelID == "qwen3:8b")+ #expect(selected.modelID == defaultLocalRuntimeModelID)#expect(selected.timeoutMS == 20_000)}+ @Test+ func defaultPlannerHintRouteDoesNotUseOllama() throws {+ let router = AIModelRouter(registry: .defaultHybridPlanner)++ let selected = try router.route(+ AIModelRouteRequest(+ jobType: .plannerHint,+ privacyMode: .privacySensitive+ )+ )++ #expect(selected.id == "openai-planner-hint-default")+ #expect(selected.provider == .openAI)+ }+@Testfunc localModelPriorityWorkerPreemptsLowerPriorityWorkCooperatively() async throws {let worker = LocalModelPriorityWorker()@@ -338,7 +357,7 @@ struct AIHarnessAdapterTests {id: "local-intent",role: .taskIntent,provider: .ollama,- modelID: "qwen3:8b",+ modelID: explicitOllamaFixtureModelID,endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,promptVersion: "task-intent-v1")@@ -368,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 == "qwen3:8b")+ #expect(body["model"] as? String == explicitOllamaFixtureModelID)#expect(body["stream"] as? Bool == false)#expect(body["format"] as? [String: Any] != nil)#expect(body["keep_alive"] as? String == "10m")@@ -391,7 +410,7 @@ struct AIHarnessAdapterTests {let httpClient = SequencedFakeAIHTTPClient(responses: [HTTPStub(- data: Data(#"{"error":"model 'qwen3:8b' not found"}"#.utf8),+ data: Data("{\"error\":\"model '\(explicitOllamaFixtureModelID)' not found\"}".utf8),statusCode: 404),HTTPStub(@@ -416,7 +435,7 @@ struct AIHarnessAdapterTests {id: "local-intent",role: .taskIntent,provider: .ollama,- modelID: "qwen3:8b",+ modelID: explicitOllamaFixtureModelID,endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,promptVersion: "task-intent-v1")@@ -440,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"] == "qwen3:8b")+ #expect(result.trace.metadata["modelFallback.originalModelID"] == explicitOllamaFixtureModelID)#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)@@ -456,7 +475,7 @@ struct AIHarnessAdapterTests {result: LocalJSONSidecarResult(status: .completed,outputData: Data("""- {"outputText":"{\\"taskType\\":\\"media_playback\\",\\"targetAppName\\":\\"Music\\",\\"entities\\":{\\"query\\":\\"cold play\\"},\\"normalizedEntities\\":{\\"query\\":\\"Cold Play\\"},\\"confidence\\":0.91,\\"needsConfirmation\\":false,\\"actionPlan\\":{\\"tools\\":[],\\"inputEntity\\":\\"\\",\\"controlID\\":\\"\\",\\"focusKey\\":\\"\\",\\"verification\\":\\"commandAttempted\\"},\\"metadata\\":{\\"source\\":\\"test\\"}}","metadata":{"local.provider":"ollama-sidecar"}}+ {"outputText":"{\\"taskType\\":\\"media_playback\\",\\"targetAppName\\":\\"Music\\",\\"entities\\":{\\"query\\":\\"cold play\\"},\\"normalizedEntities\\":{\\"query\\":\\"Cold Play\\"},\\"confidence\\":0.91,\\"needsConfirmation\\":false,\\"actionPlan\\":{\\"tools\\":[],\\"inputEntity\\":\\"\\",\\"controlID\\":\\"\\",\\"focusKey\\":\\"\\",\\"verification\\":\\"commandAttempted\\"},\\"metadata\\":{\\"source\\":\\"test\\"}}","metadata":{"local.provider":"donkey-local-llm-sidecar"}}""".utf8),latencyMS: 14,metadata: ["sidecar.role": "taskIntent"]@@ -478,7 +497,7 @@ struct AIHarnessAdapterTests {#expect(result.intent?.metadata["parser"] == "local-llm-sidecar-v1")#expect(result.trace.provider == .localRuntime)#expect(result.trace.status == .completed)- #expect(result.trace.metadata["local.provider"] == "ollama-sidecar")+ #expect(result.trace.metadata["local.provider"] == "donkey-local-llm-sidecar")}@Test@@ -489,7 +508,7 @@ struct AIHarnessAdapterTests {result: LocalJSONSidecarResult(status: .completed,outputData: Data("""- {"outputText":"{\\"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\\",\\"ui.pressReturn\\",\\"app.verifyCommand\\"],\\"inputEntity\\":\\"query\\",\\"controlID\\":\\"search\\",\\"focusKey\\":\\"Command+F\\",\\"verification\\":\\"commandAttempted\\"},\\"metadata\\":{}}","metadata":{"local.provider":"ollama-sidecar"}}+ {"outputText":"{\\"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\\",\\"ui.pressReturn\\",\\"app.verifyCommand\\"],\\"inputEntity\\":\\"query\\",\\"controlID\\":\\"search\\",\\"focusKey\\":\\"Command+F\\",\\"verification\\":\\"commandAttempted\\"},\\"metadata\\":{}}","metadata":{"local.provider":"donkey-local-llm-sidecar"}}""".utf8),latencyMS: 14,metadata: ["sidecar.role": "taskIntent"]@@ -528,7 +547,7 @@ struct AIHarnessAdapterTests {{"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":{}}```""",- metadata: ["local.provider": "ollama-sidecar"]+ metadata: ["local.provider": "donkey-local-llm-sidecar"]),latencyMS: 14,metadata: ["sidecar.role": "taskIntent"]@@ -562,7 +581,7 @@ struct AIHarnessAdapterTests {outputText: "",metadata: ["reason": "localLLMGenerationFailed",- "detail": "ollama HTTP 404: model 'qwen3:8b' not found"+ "detail": "local LLM backend unavailable for \(defaultLocalRuntimeModelID)"]),latencyMS: 14,@@ -584,7 +603,7 @@ struct AIHarnessAdapterTests {#expect(result.trace.validationStatus == "notValidated")#expect(result.trace.metadata["reason"] == "localLLMGenerationFailed")#expect(result.trace.metadata["modelOutput.empty"] == "true")- #expect(result.trace.metadata["detail"]?.contains("qwen3:8b") == true)+ #expect(result.trace.metadata["detail"]?.contains(defaultLocalRuntimeModelID) == true)}@Test@@ -599,8 +618,7 @@ struct AIHarnessAdapterTests {{"taskType":"local_app_interaction","targetAppName":"com.apple.Music","entities":{"appName":"Music","goal":"play some justin bieber"},"normalizedEntities":{"query":"Justin Bieber"},"confidence":1.0,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","ui.focusSearch"],"inputEntity":"query","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{}}""",metadata: [- "local.provider": "ollama-sidecar",- "modelFallback.selectedModelID": "llama3:latest"+ "local.provider": "donkey-local-llm-sidecar"]),latencyMS: 14,@@ -669,7 +687,7 @@ struct AIHarnessAdapterTests {status: .completed,outputData: try localLLMSidecarOutputData(outputText: example.outputText,- metadata: ["local.provider": "ollama-sidecar"]+ metadata: ["local.provider": "donkey-local-llm-sidecar"]),latencyMS: 14,metadata: ["sidecar.role": "taskIntent"]@@ -725,7 +743,7 @@ struct AIHarnessAdapterTests {id: "local-intent",role: .taskIntent,provider: .ollama,- modelID: "qwen3:8b",+ modelID: explicitOllamaFixtureModelID,endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,promptVersion: "task-intent-v1")@@ -773,7 +791,7 @@ struct AIHarnessAdapterTests {id: "local-intent",role: .taskIntent,provider: .ollama,- modelID: "qwen3:8b",+ modelID: explicitOllamaFixtureModelID,endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,promptVersion: "task-intent-v1")@@ -819,6 +837,27 @@ struct AIHarnessAdapterTests {#expect(result.trace.metadata["fallback.reason"] == nil)}+ @Test+ func localModelTaskIntentResolverDoesNotFallbackToCommandTextWhenRuntimeUnavailable() async {+ let resolver = LocalModelTaskIntentResolver(+ catalog: LocalAppTaskCatalog(+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,+ availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.Music"])+ ),+ adapter: UnavailableTaskIntentAdapter()+ )++ let result = await resolver.resolve(+ command: "play some justin bieber",+ sourceTraceID: "trace-resolve-no-command-text-fallback"+ )++ #expect(result.resolution.status == .needsConfirmation)+ #expect(result.resolution.intent == nil)+ #expect(result.resolution.metadata["reason"] == "localModelIntentUnavailable")+ #expect(result.trace.status == .providerOutage)+ }+@Testfunc localModelTaskIntentResolverAsksForDetailsInsteadOfUnsupportedWhenRuntimeUnavailable() async {let resolver = LocalModelTaskIntentResolver(@@ -839,6 +878,45 @@ struct AIHarnessAdapterTests {#expect(result.resolution.metadata["modelCallStatus"] == "providerOutage")}+ @Test+ func localModelTaskIntentResolverPreservesStructuredConversationForGreeting() async throws {+ let adapter = ProcessBackedLocalLLMTaskIntentAdapter(+ router: AIModelRouter(registry: .defaultHybridPlanner),+ sidecarRunner: FakeSidecarRunner(+ result: LocalJSONSidecarResult(+ status: .completed,+ outputData: try localLLMSidecarOutputData(+ outputText: """+ {"taskType":"local_app_interaction","targetAppName":"Local App","entities":{},"normalizedEntities":{},"confidence":0.2,"needsConfirmation":false,"actionPlan":{"tools":[],"inputEntity":"","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{"responseMode":"conversation","assistantResponse":"Hello! How can I help?"}}+ """,+ metadata: ["local.provider": "donkey-local-llm"]+ ),+ latencyMS: 14,+ metadata: ["sidecar.role": "taskIntent"]+ )+ )+ )+ let resolver = LocalModelTaskIntentResolver(+ catalog: LocalAppTaskCatalog(+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,+ availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: [])+ ),+ adapter: adapter+ )++ let result = await resolver.resolve(+ command: "hello there",+ sourceTraceID: "trace-structured-greeting"+ )++ #expect(result.resolution.status == .needsConfirmation)+ #expect(result.resolution.intent?.taskType == "local_app_interaction")+ #expect(result.resolution.metadata["reason"] == "lowConfidenceIntent")+ #expect(result.resolution.metadata["responseMode"] == "conversation")+ #expect(result.resolution.metadata["assistantResponse"] == "Hello! How can I help?")+ #expect(result.trace.status == .completed)+ }+@Testfunc localModelTaskIntentResolverAcceptsClosestLowConfidenceClassification() async {let httpClient = FakeAIHTTPClient(@@ -862,7 +940,7 @@ struct AIHarnessAdapterTests {id: "local-intent",role: .taskIntent,provider: .ollama,- modelID: "qwen3:8b",+ modelID: explicitOllamaFixtureModelID,endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,promptVersion: "task-intent-v1")@@ -906,7 +984,7 @@ struct AIHarnessAdapterTests {id: "local-intent",role: .taskIntent,provider: .ollama,- modelID: "qwen3:8b",+ modelID: explicitOllamaFixtureModelID,endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,promptVersion: "task-intent-v1")@@ -939,7 +1017,7 @@ struct AIHarnessAdapterTests {outputText: """{"taskType":"local_app_interaction","targetAppName":"Notes","entities":{"appName":"Notes","goal":"write requested text","query":"a people"},"normalizedEntities":{"appName":"Notes","goal":"write requested text","query":"a people"},"confidence":0.9,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","ui.newDocument","ui.setText"],"inputEntity":"query","controlID":"editor","focusKey":"","verification":"commandAttempted"},"metadata":{}}""",- metadata: ["local.provider": "ollama-sidecar"]+ metadata: ["local.provider": "donkey-local-llm-sidecar"]),latencyMS: 14,metadata: ["sidecar.role": "taskIntent"]@@ -974,7 +1052,7 @@ struct AIHarnessAdapterTests {outputText: """{"taskType":"local_app_interaction","targetAppName":"Notes","entities":{"appName":"Notes","goal":"write requested text","query":"hello"},"normalizedEntities":{"appName":"Notes","goal":"write requested text","query":"hello"},"confidence":0.9,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","ui.newDocument","ui.setText"],"inputEntity":"query","controlID":"editor","focusKey":"","verification":"commandAttempted"},"metadata":{}}""",- metadata: ["local.provider": "ollama-sidecar"]+ metadata: ["local.provider": "donkey-local-llm-sidecar"]),latencyMS: 14,metadata: ["sidecar.role": "taskIntent"]@@ -1007,7 +1085,7 @@ struct AIHarnessAdapterTests {outputText: """{"taskType":"local_app_interaction","targetAppName":"Notes","entities":{"appName":"Notes","goal":"write requested text","query":"A complete piece of text generated for the user writing request."},"normalizedEntities":{"appName":"Notes","goal":"write requested text","query":"A complete piece of text generated for the user writing request."},"confidence":0.9,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","ui.newDocument","ui.setText"],"inputEntity":"query","controlID":"editor","focusKey":"","verification":"commandAttempted"},"metadata":{}}""",- metadata: ["local.provider": "ollama-sidecar"]+ metadata: ["local.provider": "donkey-local-llm-sidecar"]),latencyMS: 14,metadata: ["sidecar.role": "taskIntent"]@@ -1041,7 +1119,7 @@ struct AIHarnessAdapterTests {outputText: """{"taskType":"local_app_interaction","targetAppName":"Notes","entities":{"appName":"Notes","goal":"write requested text","query":""},"normalizedEntities":{"appName":"Notes","goal":"write requested text","query":""},"confidence":0.9,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","ui.newDocument","ui.setText"],"inputEntity":"query","controlID":"editor","focusKey":"","verification":"commandAttempted"},"metadata":{}}""",- metadata: ["local.provider": "ollama-sidecar"]+ metadata: ["local.provider": "donkey-local-llm-sidecar"]),latencyMS: 14,metadata: ["sidecar.role": "taskIntent"]@@ -1075,7 +1153,7 @@ struct AIHarnessAdapterTests {outputText: """{"taskType":"local_app_interaction","targetAppName":"Numbers","entities":{"appName":"Numbers","goal":"create requested table","query":"Market capital of the 10 largest companies in S&P"},"normalizedEntities":{"appName":"Numbers","goal":"create requested table","query":"Market capital of the 10 largest companies in S&P"},"confidence":0.9,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.newDocument","ui.setText"],"inputEntity":"query","controlID":"editor","focusKey":"","verification":"commandAttempted"},"metadata":{}}""",- metadata: ["local.provider": "ollama-sidecar"]+ metadata: ["local.provider": "donkey-local-llm-sidecar"]),latencyMS: 14,metadata: ["sidecar.role": "taskIntent"]@@ -1284,7 +1362,7 @@ struct AIHarnessAdapterTests {entry(id: "local-planner",provider: .ollama,- modelID: "qwen3:8b",+ modelID: explicitOllamaFixtureModelID,endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!)]@@ -1304,7 +1382,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 == "qwen3:8b")+ #expect(body["model"] as? String == explicitOllamaFixtureModelID)#expect(body["stream"] as? Bool == false)#expect(body["format"] as? [String: Any] != nil)#expect(request.value(forHTTPHeaderField: "Authorization") == nil)@@ -1319,7 +1397,7 @@ struct AIHarnessAdapterTests {entry(id: "local-planner",provider: .ollama,- modelID: "qwen3:8b",+ modelID: explicitOllamaFixtureModelID,endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!)]@@ -1358,6 +1436,13 @@ struct AIHarnessAdapterTests {#expect(result.metadata["selectedModelID"] == "gpt-5.2")}+ @Test+ func providerBackedSlowPlannerDefaultOrderSkipsOllama() {+ let planner = ProviderBackedSlowPlannerHintGenerator()++ #expect(planner.providerOrder == [.openAI])+ }+@Testfunc semanticMemoryRetrievalUsesBudgetsAndTargetScope() async {let records = [@@ -1498,7 +1583,7 @@ struct AIHarnessAdapterTests {.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"").replacingOccurrences(of: "\n", with: "\\n")- return Data("{\"model\":\"qwen3:8b\",\"response\":\"\(escaped)\",\"done\":true}".utf8)+ return Data("{\"model\":\"\(explicitOllamaFixtureModelID)\",\"response\":\"\(escaped)\",\"done\":true}".utf8)}private func providerOutput(@@ -1717,7 +1802,7 @@ private struct UnavailableTaskIntentAdapter: TaskIntentParsingAdapter {id: "model-call-unavailable",role: .taskIntent,provider: .localRuntime,- modelID: "qwen3:8b",+ modelID: defaultLocalRuntimeModelID,promptVersion: "task-intent-v1",schemaID: "task_intent_v1",latencyMS: nil,diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swiftindex 9a242981..1f567e8f 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AppHarnessTurnRouterTests.swift@@ -16,13 +16,12 @@ struct AppHarnessTurnRouterTests {#expect(result.outcome.decision.kind == .runLocalTask)#expect(result.outcome.decision.traceID == "trace-chat")#expect(result.outcome.metadata["router"] == "modelIntent")- #expect(result.outcome.resolution?.status == .unsupportedCommand)- #expect(result.outcome.resolution?.metadata["reason"] == "modelIntentRequired")+ #expect(result.outcome.resolution == nil)#expect(result.outcome.assistantResponse == nil)}@Test- func simpleArithmeticRoutesToLocalAnswerWithoutCommandWords() {+ func arithmeticQuestionAlsoDefersToModelIntentRouting() {let result = router().route(request: AppHarnessTurnRequest(turn: AppHarnessTurn(text: "What is 2+2?", source: .typedPrompt)@@ -30,9 +29,10 @@ struct AppHarnessTurnRouterTests {traceID: "trace-math")- #expect(result.outcome.decision.kind == .respond)- #expect(result.outcome.metadata["router"] == "simpleArithmetic")- #expect(result.outcome.assistantResponse == "2 + 2 = 4.")+ #expect(result.outcome.decision.kind == .runLocalTask)+ #expect(result.outcome.metadata["router"] == "modelIntent")+ #expect(result.outcome.resolution == nil)+ #expect(result.outcome.assistantResponse == nil)}@Test@@ -46,7 +46,7 @@ struct AppHarnessTurnRouterTests {#expect(result.outcome.decision.kind == .runLocalTask)#expect(result.outcome.metadata["router"] == "modelIntent")- #expect(result.outcome.resolution?.status == .unsupportedCommand)+ #expect(result.outcome.resolution == nil)}@Test@@ -60,7 +60,7 @@ struct AppHarnessTurnRouterTests {#expect(result.outcome.decision.kind == .runLocalTask)#expect(result.outcome.metadata["router"] == "modelIntent")- #expect(result.outcome.resolution?.status == .unsupportedCommand)+ #expect(result.outcome.resolution == nil)}@Test@@ -74,8 +74,7 @@ struct AppHarnessTurnRouterTests {#expect(result.outcome.decision.kind == .runLocalTask)#expect(result.outcome.metadata["router"] == "modelIntent")- #expect(result.outcome.resolution?.status == .unsupportedCommand)- #expect(result.outcome.resolution?.metadata["reason"] == "modelIntentRequired")+ #expect(result.outcome.resolution == nil)}@Test@@ -90,7 +89,7 @@ struct AppHarnessTurnRouterTests {#expect(result.contextPacket.currentTurn.source == .voiceTranscript)#expect(result.outcome.decision.kind == .runLocalTask)#expect(result.outcome.metadata["router"] == "modelIntent")- #expect(result.outcome.resolution?.status == .unsupportedCommand)+ #expect(result.outcome.resolution == nil)}@Test@@ -104,8 +103,7 @@ struct AppHarnessTurnRouterTests {#expect(result.outcome.decision.kind == .runLocalTask)#expect(result.outcome.metadata["router"] == "modelIntent")- #expect(result.outcome.resolution?.status == .unsupportedCommand)- #expect(result.outcome.resolution?.metadata["reason"] == "modelIntentRequired")+ #expect(result.outcome.resolution == nil)}@Testdiff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swiftindex 5c7db0ed..41bc193b 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/LocalModelRuntimeSetupTests.swift@@ -360,6 +360,38 @@ struct LocalModelRuntimeSetupTests {#expect(report.modelID == "nvidia/parakeet-tdt-0.6b-v3")}+ @Test+ func recheckHealthFailsWhenModelWeightsAreMissing() async throws {+ let root = temporaryDirectory()+ let download = temporaryDirectory()+ defer {+ try? FileManager.default.removeItem(at: root)+ try? FileManager.default.removeItem(at: download)+ }+ let healthExecutable = try makeHealthExecutable(+ root: download,+ relativePath: "bin/donkey-local-llm",+ runtimeID: "local-llm",+ runtimeVersion: "1.2.3",+ modelID: "qwen3-0.6b-q4_0",+ metadataJSON: #"{"modelWeights.status":"missing","modelWeights.provider":"donkey-managed-download"}"#+ )+ let manager = try LocalModelRuntimeSetupManager(baseDirectory: root)+ try manager.registerExecutable(+ runtimeID: .localLLM,+ executableURL: healthExecutable,+ downloadedDirectory: download,+ runtimeVersion: "1.2.3",+ modelID: "qwen3-0.6b-q4_0",+ sidecarProtocolVersion: "v1"+ )++ let report = try await manager.recheckHealth(runtimeID: .localLLM)++ #expect(report.state == .failed)+ #expect(report.metadata["modelWeights.status"] == "missing")+ }+@Testfunc prepareModelWeightsRunsSidecarPreparationProtocol() async throws {let root = temporaryDirectory()@@ -481,12 +513,13 @@ struct LocalModelRuntimeSetupTests {relativePath: String,runtimeID: String,runtimeVersion: String,- modelID: String+ modelID: String,+ metadataJSON: String = #"{"health":"ok"}"#) throws -> URL {let script = """#!/bin/shcat >/dev/null- printf '{"status":"ok","runtimeID":"\(runtimeID)","runtimeVersion":"\(runtimeVersion)","modelID":"\(modelID)","protocolVersion":"v1","metadata":{"health":"ok"}}'+ printf '{"status":"ok","runtimeID":"\(runtimeID)","runtimeVersion":"\(runtimeVersion)","modelID":"\(modelID)","protocolVersion":"v1","metadata":\(metadataJSON)}'"""let url = relativePath.split(separator: "/")diff --git a/docs/architecture.md b/docs/architecture.mdindex 03952f28..d002c605 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -233,7 +233,8 @@ registration, health checks, model-prep hooks, retryable first-run setup,settings access, repair/remove lifecycle helpers, support status export, andpackage-local Python wheelhouses built for the release target. The UIunderstanding backend is a packaged Swift sidecar using Apple Vision, and the-command parser LLM currently uses Ollama as a documented local prerequisite.+command parser LLM uses an app-managed `local-llm` sidecar with setup-downloaded+model weights instead of a user-managed Ollama prerequisite.## Slower AI Harnessdiff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex 4ac0260b..ce192833 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -140,6 +140,13 @@ text as an implicit action signal.## Intent Classification Rules+The core rule is model-first: never string-match raw user input to infer what+the user wants. Natural language has too many variations for phrase lists,+prefixes, suffixes, regexes, greeting classifiers, or app-name checks to be a+reliable decision boundary. Pass the turn through an LLM or another typed+model/runtime boundary first. Once structured output exists, deterministic code+may validate and match typed fields.+User intent must not be inferred with ad hoc phrase, prefix, suffix, substring,or regex checks against natural-language command text. Donkey has local LLMs,task definitions, runtime catalogs, and agent memory context for this job. Use them.@@ -149,10 +156,10 @@ recover those buckets by reading natural-language words out of the user'sprompt.Allowed deterministic checks are narrow primitives whose correctness does not-depend on open-ended language semantics: empty input, numeric-only arithmetic-expression extraction, exact schema validation, explicit metadata flags, and-bounded normalization of lookup text after a typed decision has already selected-a lookup path. These checks must stay generic and must not encode app-specific+depend on open-ended language semantics: empty input, exact schema validation,+explicit metadata flags, and bounded normalization of lookup text after a typed+decision has already selected a lookup path. These checks must stay generic and+must not encode app-specificor workflow-specific user phrasing.Disallowed checks include code that decides a user's semantic intent from@@ -192,11 +199,13 @@ what can be acted on, and what policies apply.A useful context packet includes the current turn, a bounded summary of recentthread events, relevant assets, active action state, selected app/window facts-when available, task definitions and supported capabilities, retrieved memory,-permission policy, safety state, and trace ids. The packet should be shaped for-the consumer: conversation response, intent classification, planner hint,-review-plan creation, memory retrieval, observation, and recovery do not need-the same fields.+when available, task definitions and supported capabilities, permission policy,+safety state, and trace ids. The packet should be shaped for the consumer:+conversation response, intent classification, planner hint, review-plan+creation, memory retrieval, observation, and recovery do not need the same+fields. Query-matched memory for natural-language prompt text should not be+added before intent classification; retrieve memory after the typed model+output provides a structured target or scope.Remote-bound context must be redacted before provider calls. Local-only contextcan include richer app and observation facts, but should still stay bounded and@@ -223,11 +232,10 @@ the harness should ask for that exact entity or invite an upload. The promptshould name the missing detail rather than using generic copy like "Need moredetail".-Action execution is for validated, supported tasks. The fast turn classifier can-answer narrow non-semantic turns such as numeric arithmetic; otherwise the local-model classifier or explicit runtime metadata produces a `TaskIntent`. Execution-may only continue after catalog validation confirms the target app/task,-required entities, app availability, and safety policy. The default runtime+Action execution is for validated, supported tasks. The local model classifier+or explicit runtime metadata produces a `TaskIntent`. Execution may only+continue after catalog validation confirms the target app/task, required+entities, app availability, and safety policy. The default runtimecapabilities are generic local-item open plus generic model-planned local-appinteraction; the latter materializes a transient task definition from anallowlisted typed `actionPlan` before execution. Weather lookup, mediadiff --git a/docs/guides/decision-system.md b/docs/guides/decision-system.mdindex 7f8da060..30febf82 100644--- a/docs/guides/decision-system.md+++ b/docs/guides/decision-system.md@@ -17,18 +17,17 @@ For document-writing plans, Donkey also validates the model output itself: a sho## Decision Flow-The pointer prompt records the user-visible turn, builds a bounded context packet, and routes it through the harness. Narrow non-semantic primitives, such as empty input and numeric arithmetic, can be handled directly. Semantic decisions go through typed model boundaries.+The pointer prompt records the user-visible turn, builds a bounded context packet, and routes it through the harness. Empty input can be handled directly. Semantic decisions go through typed model boundaries.For local app work, the model receives:- the current command- supported runtime task definitions-- relevant agent-memory snippets, such as installed local apps, files, folders, and learned task definitions- safety and execution expectations encoded in task metadataThe model returns strict JSON, not free-form instructions. The result is decoded into a `TaskIntent`. If the intent names an existing task definition, the catalog validates that definition. If it names the generic local-app interaction capability, the catalog resolves the requested app from local memory and app lookup, then materializes a transient task definition from the typed `actionPlan`.-For dynamic local-item and local-app interaction capabilities, the app or item name may be directly stated, retrieved from memory snippets, or inferred as the likely default local app for the user's goal. That inference is not execution authority; the catalog still resolves and verifies the target before any action runs.+For dynamic local-item and local-app interaction capabilities, the app or item name comes from the typed model output. Catalog and memory matching happen after that typed output exists, so lookup is scoped to structured fields such as `targetAppName`, `entities.appName`, or a resolved target id. That inference is not execution authority; the catalog still resolves and verifies the target before any action runs.The `TaskIntent` wire format always includes an `actionPlan` object. Non-planned task types must return an empty `actionPlan.tools` array; non-empty action plans are accepted only for task definitions that explicitly opt into model-planned local-app interaction.@@ -96,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 model adapters live in `apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.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.- 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.diff --git a/docs/guides/install-donkey.md b/docs/guides/install-donkey.mdindex 08e0f36d..9e169615 100644--- a/docs/guides/install-donkey.md+++ b/docs/guides/install-donkey.md@@ -81,9 +81,9 @@ DONKEY_RUNTIME_PACKAGE_MANIFEST_URLS="parakeet-transcriber=https://example.com/d./scripts/package-donkey-app.sh```-On first launch, Donkey shows one setup button for local runtimes. Setup downloads the configured sidecar packages, verifies their manifests/checksums/signatures, registers them in Application Support, asks them to prepare model weights, and health-checks them. The packages do not include Parakeet or YOLO model weights; they contain protocol-speaking runner entrypoints for the local command parser, Parakeet voice transcription, and YOLO screenshot segmentation. UI understanding ships as a local Swift sidecar that uses Apple's on-device Vision text recognition and does not need downloaded model weights. If setup fails, clicking the same button retries failed or not-yet-attempted runtimes while keeping completed installs. The setup window can also be reopened from the app settings.+On first launch, Donkey opens setup and starts installing required local runtimes. Setup downloads the configured sidecar packages, verifies their manifests/checksums/signatures, registers them in Application Support, asks them to prepare model weights, and health-checks them. The packages do not include model weights; they contain protocol-speaking runner entrypoints for the local command parser, Parakeet voice transcription, and YOLO screenshot segmentation. UI understanding ships as a local Swift sidecar that uses Apple's on-device Vision text recognition and does not need downloaded model weights. If setup fails, clicking the same button retries failed or not-yet-attempted runtimes while keeping completed installs. The setup window can also be reopened from the app settings.-Each sidecar supports setup-time model weight preparation. During setup, Donkey calls the sidecar with `prepareModelWeights`; the sidecar downloads or warms the configured model cache and reports cached/downloaded status before health check. The local command-parser LLM is setup-managed too: Donkey packages a `local-llm` sidecar that pulls `qwen3:8b` through Ollama by default, then actionable prompt turns are parsed through `DONKEY_LOCAL_LLM_RUNNER` instead of a direct in-app Ollama request. If the configured Ollama model is missing at runtime but another local, non-cloud Ollama model is installed, Donkey can retry the task-intent parse with that model and records the fallback in model metadata. The Parakeet runner can fetch the Hugging Face snapshot when `huggingface_hub` is available and transcribes through NVIDIA NeMo when the local Python backend is installed.+Each sidecar supports setup-time model weight preparation. During setup, Donkey calls the sidecar with `prepareModelWeights`; the sidecar downloads or warms the configured model cache and reports cached/downloaded status before health check. The local command-parser LLM is setup-managed too: Donkey packages a `local-llm` sidecar whose release manifest must include a model-weight download URL, checksum, and local inference backend requirement. The default package uses a Donkey-managed GGUF weight download with a `llama-cpp-python` backend. Actionable prompt turns are parsed through `DONKEY_LOCAL_LLM_RUNNER`; if that local runtime is unavailable, task-intent parsing fails clearly. Donkey does not fall back to a user-managed Ollama daemon. The Parakeet runner can fetch the Hugging Face snapshot when `huggingface_hub` is available and transcribes through NVIDIA NeMo when the local Python backend is installed.Configure model-weight URLs when packaging:@@ -92,7 +92,9 @@ DONKEY_PARAKEET_MODEL_URL="https://..." \DONKEY_PARAKEET_MODEL_SHA256="..." \DONKEY_YOLO_MODEL_URL="https://..." \DONKEY_YOLO_MODEL_SHA256="..." \-DONKEY_LOCAL_LLM_MODEL_ID="qwen3:8b" \+DONKEY_LOCAL_LLM_MODEL_ID="qwen3-0.6b-q4_0" \+DONKEY_LOCAL_LLM_MODEL_URL="https://..." \+DONKEY_LOCAL_LLM_MODEL_SHA256="..." \./scripts/package-donkey-app.sh```@@ -107,7 +109,35 @@ DONKEY_RUNTIME_REQUIRE_CRYPTO_SIGNATURES="1" \./scripts/package-donkey-app.sh```-If a model URL/backend is missing for a file-backed sidecar, Ollama is unavailable for the local LLM sidecar, or Parakeet's local Python backend is missing, setup or runtime calls fail clearly with a retryable needs-attention state instead of pretending the runtime is usable.+If a model URL/backend is missing for a sidecar or Parakeet's local Python backend is missing, setup or runtime calls fail clearly with a retryable needs-attention state instead of pretending the runtime is usable.++## Dev Runtime Manifests++For local development, `scripts/run-donkey-dev.sh` bootstraps local runtime packages and manifest files from `dist/LocalRuntimePackages/` before launching the debug app:++```bash+./scripts/run-donkey-dev.sh+```++If runtime packages are missing, stale, or still have the old local-LLM package without a model URL/checksum/backend requirement, the dev runner calls `scripts/package-donkey-app.sh` first. It then regenerates the dev manifest env file and loads it for the debug launch.++The dev runner automatically creates and loads:++```text+dist/donkey-dev-runtime-manifests.env+```++That env file points `DONKEY_RUNTIME_PACKAGE_MANIFEST_URLS` at generated `file://` manifests under `dist/LocalRuntimeDevManifests/`. Those dev manifests rewrite each runtime file entry to a local `file://` download URL, so the debug app can install runtimes into Application Support without first installing `/Applications/Donkey.app`.++After building the debug executable, `run-donkey-dev.sh` runs `scripts/setup-dev-local-runtimes.py`. The helper installs any missing, invalid, or stale-version local runtime packages into Application Support, then asks newly installed sidecars to prepare model weights and run a health check. For `local-llm`, that first prepare pass may create a managed Python environment, install `llama-cpp-python`, and download the configured GGUF model file; this is foreground work, not a silent background repair. Already-current runtime registrations are left alone, so the setup pass is a one-time dev bootstrap unless local packages change. Runtime setup failures are reported as warnings and the debug app still launches.++To regenerate the env file manually:++```bash+scripts/create-dev-runtime-manifests.py+```++Set `DONKEY_DEV_RUNTIME_AUTO_PACKAGE=0` to skip automatic package refresh. Set `DONKEY_DEV_RUNTIME_PACKAGE_REFRESH=1` to force a package refresh before launch. Set `DONKEY_DEV_RUNTIME_MANIFESTS=0` to make `run-donkey-dev.sh` skip manifest generation. Set `DONKEY_DEV_RUNTIME_SETUP=0` to skip the missing-runtime setup pass. Set `DONKEY_DEV_RUNTIME_PREPARE=0` to install/register missing packages without running model preparation or health checks. Set `DONKEY_DEV_RUNTIME_FORCE_SETUP=1` to reinstall from the dev manifests even when the registry already points at the same runtime version. Set `DONKEY_DEV_RUNTIME_ENV_FILE`, `DONKEY_DEV_RUNTIME_PACKAGE_DIR`, or `DONKEY_DEV_RUNTIME_BASE_DIR` to use different local paths.Developer diagnostics:diff --git a/evals/task-intent/README.md b/evals/task-intent/README.mdindex 8aec984b..f6112096 100644--- a/evals/task-intent/README.md+++ b/evals/task-intent/README.md@@ -43,7 +43,7 @@ Run a small live sidecar sample against the local LLM sidecar:```bashDONKEY_RUNTIME_ID=local-llm \-DONKEY_MODEL_ID=qwen3:8b \+DONKEY_MODEL_ID=qwen3-0.6b-q4_0 \python3 scripts/evals/run_task_intent_sidecar_evals.py --app Safari --limit 3```@@ -51,7 +51,7 @@ Run the full suite:```bashDONKEY_RUNTIME_ID=local-llm \-DONKEY_MODEL_ID=qwen3:8b \+DONKEY_MODEL_ID=qwen3-0.6b-q4_0 \python3 scripts/evals/run_task_intent_sidecar_evals.py```diff --git a/scripts/create-dev-runtime-manifests.py b/scripts/create-dev-runtime-manifests.pynew file mode 100755index 00000000..2228da86--- /dev/null+++ b/scripts/create-dev-runtime-manifests.py@@ -0,0 +1,106 @@+#!/usr/bin/env python3+"""Create file:// runtime manifests for local Donkey development."""++from __future__ import annotations++import json+import os+import shlex+import sys+from pathlib import Path+from typing import Any+++ROOT_DIR = Path(__file__).resolve().parents[1]+PACKAGE_DIR = Path(os.environ.get("DONKEY_DEV_RUNTIME_PACKAGE_DIR", ROOT_DIR / "dist" / "LocalRuntimePackages"))+MANIFEST_DIR = Path(os.environ.get("DONKEY_DEV_RUNTIME_MANIFEST_DIR", ROOT_DIR / "dist" / "LocalRuntimeDevManifests"))+ENV_FILE = Path(os.environ.get("DONKEY_DEV_RUNTIME_ENV_FILE", ROOT_DIR / "dist" / "donkey-dev-runtime-manifests.env"))++RUNTIME_ENV_NAMES = {+ "parakeet-transcriber": "DONKEY_PARAKEET_RUNTIME_MANIFEST_URL",+ "yolo-segmenter": "DONKEY_YOLO_RUNTIME_MANIFEST_URL",+ "ui-understander": "DONKEY_UI_UNDERSTANDER_RUNTIME_MANIFEST_URL",+ "local-llm": "DONKEY_LOCAL_LLM_RUNTIME_MANIFEST_URL",+}+++def main() -> int:+ if not PACKAGE_DIR.exists():+ print(+ f"Runtime package directory not found: {PACKAGE_DIR}\n"+ "Run ./scripts/package-donkey-app.sh once to create dist/LocalRuntimePackages.",+ file=sys.stderr,+ )+ return 2++ manifest_urls: dict[str, str] = {}+ warnings: list[str] = []+ for manifest_path in sorted(PACKAGE_DIR.glob("*/manifest.json")):+ manifest = json.loads(manifest_path.read_text())+ runtime_id = str(manifest.get("runtimeID") or manifest_path.parent.name)+ package_root = manifest_path.parent++ files = manifest.get("files")+ if not isinstance(files, list):+ print(f"Manifest has no files array: {manifest_path}", file=sys.stderr)+ return 2+ for item in files:+ if not isinstance(item, dict):+ print(f"Manifest file entry is not an object in {manifest_path}", file=sys.stderr)+ return 2+ relative_path = str(item.get("relativePath") or "")+ if not relative_path:+ print(f"Manifest file entry is missing relativePath in {manifest_path}", file=sys.stderr)+ return 2+ file_path = package_root / relative_path+ if not file_path.exists():+ print(f"Manifest references missing local file: {file_path}", file=sys.stderr)+ return 2+ item["downloadURL"] = file_path.resolve().as_uri()++ metadata = manifest.get("metadata")+ if runtime_id == "local-llm" and isinstance(metadata, dict):+ if not str(metadata.get("modelWeights.downloadURL") or "").strip():+ warnings.append(+ "local-llm manifest has no modelWeights.downloadURL; setup will install the sidecar "+ "but model preparation/health will fail until DONKEY_LOCAL_LLM_MODEL_URL is provided "+ "or scripts/run-donkey-dev.sh refreshes the local runtime packages."+ )+ if not str(metadata.get("modelWeights.sha256") or "").strip():+ warnings.append(+ "local-llm manifest has no modelWeights.sha256; setup cannot verify downloaded model "+ "weights until DONKEY_LOCAL_LLM_MODEL_SHA256 is provided or the dev package defaults "+ "are refreshed."+ )++ dev_manifest_path = MANIFEST_DIR / runtime_id / "manifest.json"+ dev_manifest_path.parent.mkdir(parents=True, exist_ok=True)+ dev_manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n")+ manifest_urls[runtime_id] = dev_manifest_path.resolve().as_uri()++ if not manifest_urls:+ print(f"No runtime manifests found under {PACKAGE_DIR}", file=sys.stderr)+ return 2++ ENV_FILE.parent.mkdir(parents=True, exist_ok=True)+ joined_manifest_urls = ",".join(f"{runtime_id}={url}" for runtime_id, url in sorted(manifest_urls.items()))+ lines = [+ "# Generated by scripts/create-dev-runtime-manifests.py.",+ "# This file is local build output under dist/ and should not be committed.",+ f"export DONKEY_RUNTIME_PACKAGE_MANIFEST_URLS={shlex.quote(joined_manifest_urls)}",+ ]+ for runtime_id, env_name in sorted(RUNTIME_ENV_NAMES.items()):+ url = manifest_urls.get(runtime_id)+ if url:+ lines.append(f"export {env_name}={shlex.quote(url)}")+ ENV_FILE.write_text("\n".join(lines) + "\n")++ print(f"Wrote {ENV_FILE}")+ print(f"Wrote dev manifests under {MANIFEST_DIR}")+ for warning in warnings:+ print(f"warning: {warning}", file=sys.stderr)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/evals/run_task_intent_sidecar_evals.py b/scripts/evals/run_task_intent_sidecar_evals.pyindex 2dc205b1..025f7e43 100644--- a/scripts/evals/run_task_intent_sidecar_evals.py+++ b/scripts/evals/run_task_intent_sidecar_evals.py@@ -22,7 +22,7 @@ from typing import AnyDEFAULT_EVAL_PATH = Path("evals/task-intent/macos-default-apps-v1.jsonl")DEFAULT_REPORT_PATH = Path("evals/task-intent/macos-default-apps-v1.latest-report.json")DEFAULT_SIDECAR = Path("scripts/local-runtime-runners/donkey_runtime_runner.py")-DEFAULT_MODEL_ID = "qwen3:8b"+DEFAULT_MODEL_ID = "qwen3-0.6b-q4_0"SCHEMA_ID = "task_intent_v1"diff --git a/scripts/local-runtime-runners/donkey_runtime_runner.py b/scripts/local-runtime-runners/donkey_runtime_runner.pyindex a5790fe0..836e21f3 100644--- a/scripts/local-runtime-runners/donkey_runtime_runner.py+++ b/scripts/local-runtime-runners/donkey_runtime_runner.py@@ -3,8 +3,8 @@The app packages this file with small executable wrappers for each runtime. Itkeeps the Donkey sidecar protocol stable while allowing each runtime package to-prepare model weights and call a real local backend when the user's machine has-the required runtime installed.+prepare model weights and call a packaged local backend through the sidecar+protocol."""from __future__ import annotations@@ -19,7 +19,6 @@ import subprocessimport sysimport tempfileimport time-import urllib.errorimport urllib.requestfrom pathlib import Pathfrom typing import Any@@ -32,10 +31,12 @@ ROLE = os.environ.get("DONKEY_RUNTIME_ROLE", "")MODEL_URL = os.environ.get("DONKEY_MODEL_URL", "")MODEL_SHA256 = os.environ.get("DONKEY_MODEL_SHA256", "")MODEL_FILENAME = os.environ.get("DONKEY_MODEL_FILENAME", "model.bin")-OLLAMA_ENDPOINT = os.environ.get("DONKEY_OLLAMA_ENDPOINT", "http://127.0.0.1:11434")MANAGED_PYTHON_ENV = "DONKEY_RUNTIME_MANAGED_PYTHON"DEFAULT_RUNTIME_REQUIREMENTS: dict[str, list[str]] = {+ "local-llm": [+ "llama-cpp-python>=0.3,<0.4",+ ],"parakeet-transcriber": ["huggingface_hub>=0.25,<1",],@@ -112,7 +113,7 @@ def run_with_managed_python_if_needed(operation: Any, request: dict[str, Any]) -return Noneif RUNTIME_ID not in DEFAULT_RUNTIME_REQUIREMENTS:return None- if operation not in {"prepareModelWeights", None}:+ if operation not in {"prepareModelWeights", "healthCheck", None}:return Nonerequirements = runtime_requirements()@@ -241,12 +242,15 @@ def prepare_model_weights(request: dict[str, Any]) -> dict[str, Any]:if not isinstance(cache_dir, str) or not cache_dir:return error_payload("missingCacheDirectory")- if RUNTIME_ID == "local-llm":- return prepare_ollama_model(cache_dir)-target_dir = safe_model_dir(cache_dir)target_dir.mkdir(parents=True, exist_ok=True)+ if RUNTIME_ID == "local-llm" and not MODEL_URL:+ return error_payload(+ "missingModelWeightDownloadURL",+ {"cacheDirectory": cache_dir, "modelWeights.status": "notConfigured"},+ )+if RUNTIME_ID == "parakeet-transcriber" and not MODEL_URL:return prepare_huggingface_snapshot(cache_dir)@@ -285,67 +289,6 @@ def prepared(cache_dir: str, extra: dict[str, Any] | None = None) -> dict[str, A}-def prepare_ollama_model(cache_dir: str) -> dict[str, Any]:- if ollama_has_model(MODEL_ID):- return prepared(- cache_dir,- {- "modelWeights.status": "cached",- "modelWeights.provider": "ollama",- "modelWeights.ollamaModel": MODEL_ID,- },- )-- if shutil.which("ollama"):- completed = subprocess.run(- ["ollama", "pull", MODEL_ID],- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- text=True,- check=False,- )- if completed.returncode == 0:- return prepared(- cache_dir,- {- "modelWeights.provider": "ollama",- "modelWeights.ollamaModel": MODEL_ID,- },- )- return prepared(- cache_dir,- {- "reason": "ollamaPullFailed",- "modelWeights.status": "externalUnavailable",- "modelWeights.provider": "ollama",- "modelWeights.ollamaModel": MODEL_ID,- "stderr": completed.stderr[-400:],- },- )-- try:- payload = json.dumps({"model": MODEL_ID, "stream": False}).encode("utf-8")- post_json("/api/pull", payload, timeout=1800)- return prepared(- cache_dir,- {- "modelWeights.provider": "ollama",- "modelWeights.ollamaModel": MODEL_ID,- },- )- except Exception as exc: # noqa: BLE001- return prepared(- cache_dir,- {- "reason": "ollamaUnavailable",- "modelWeights.status": "externalUnavailable",- "modelWeights.provider": "ollama",- "modelWeights.ollamaModel": MODEL_ID,- "detail": str(exc),- },- )--def prepare_huggingface_snapshot(cache_dir: str) -> dict[str, Any]:try:from huggingface_hub import snapshot_download # type: ignore@@ -426,7 +369,13 @@ def download_model_file(url: str, target_file: Path, expected_sha256: str, cache)tmp_file.replace(target_file)- return prepared(cache_dir, {"modelWeights.path": str(target_file)})+ return prepared(+ cache_dir,+ {+ "modelWeights.path": str(target_file),+ "modelWeights.provider": "donkey-managed-download",+ },+ )def sha256_file(path: Path) -> str:@@ -441,22 +390,41 @@ def health_check(request: dict[str, Any]) -> dict[str, Any]:cache_dir = request.get("cacheDirectory")weights_status = "missing"provider = ""+ status = "ok"+ reason = ""- if RUNTIME_ID == "local-llm":- weights_status = "cached" if ollama_has_model(MODEL_ID) else "missing"- provider = "ollama"- elif isinstance(cache_dir, str) and cache_dir:+ if isinstance(cache_dir, str) and cache_dir:model_file = Path(cache_dir) / MODEL_FILENAMEmodel_dir = safe_model_dir(cache_dir)weights_status = "cached" if model_file.exists() or any(model_dir.glob("*")) else "missing"+ if model_file.exists():+ provider = "donkey-managed-download"++ if RUNTIME_ID == "local-llm" and not os.environ.get("DONKEY_LOCAL_LLM_COMMAND"):+ try:+ import llama_cpp # type: ignore # noqa: F401+ except Exception as exc: # noqa: BLE001+ status = "error"+ reason = "localLLMBackendUnavailable"+ provider = provider or "llama-cpp-python"+ extra_detail = str(exc)+ else:+ provider = provider or "llama-cpp-python"+ extra_detail = ""+ else:+ extra_detail = ""extra = {"runtime.package": "donkey-runner-package","modelWeights.status": weights_status,"modelWeights.provider": provider,}+ if reason:+ extra["reason"] = reason+ if extra_detail:+ extra["detail"] = extra_detailreturn {- "status": "ok",+ "status": status,"runtimeID": RUNTIME_ID,"runtimeVersion": RUNTIME_VERSION,"modelID": MODEL_ID,@@ -466,89 +434,167 @@ def health_check(request: dict[str, Any]) -> dict[str, Any]:def run_local_llm(request: dict[str, Any]) -> dict[str, Any]:- command = request.get("command", "")- schema_id = (request.get("metadata") or {}).get("schemaID", "")- is_task_intent_request = False- if schema_id == "task_followup_resolution_v1":- candidates = request.get("candidates", [])- prompt = task_followup_prompt(command, candidates)- schema = task_followup_schema(candidates)- max_tokens = 96- elif schema_id == "agent_visualization_plan":- prompt = agent_visualization_plan_prompt(- command,- request.get("runtimeCapabilities", []),- request.get("cacheSnippets", []),- )- schema = agent_visualization_plan_schema()- max_tokens = 240- else:- is_task_intent_request = True- task_definitions = request.get("taskDefinitions", [])- prompt = task_intent_prompt(command, task_definitions, request.get("contextSnippets", []))- schema = task_intent_schema(task_definitions)- max_tokens = 512- body = {- "model": selected_ollama_model(str(request.get("modelID") or MODEL_ID)),- "prompt": prompt,- "stream": False,- "format": schema,- "options": {- "num_ctx": 2048,- "num_predict": max_tokens,- "temperature": 0,- "top_p": 0.8,- },- "keep_alive": "10m",- }+ cache_dir = request.get("cacheDirectory")+ model_file = Path(cache_dir) / MODEL_FILENAME if isinstance(cache_dir, str) and cache_dir else None+ if model_file is None or not model_file.exists():+ return {+ "outputText": "",+ "metadata": metadata(+ {+ "reason": "localLLMModelWeightsMissing",+ "modelWeights.status": "missing",+ "modelWeights.provider": "donkey-managed-download",+ }+ ),+ }++ external_command = os.environ.get("DONKEY_LOCAL_LLM_COMMAND")+ if external_command:+ backend_request = dict(request)+ backend_metadata = dict(backend_request.get("metadata") or {})+ backend_metadata["modelWeights.path"] = str(model_file)+ backend_metadata["modelWeights.provider"] = "donkey-managed-download"+ backend_request["metadata"] = backend_metadata+ return run_external_json_command(external_command, backend_request)++ return run_llama_cpp_local_llm(request, model_file)+++def run_llama_cpp_local_llm(request: dict[str, Any], model_file: Path) -> dict[str, Any]:+ try:+ from llama_cpp import Llama # type: ignore+ except Exception as exc: # noqa: BLE001+ return {+ "outputText": "",+ "metadata": metadata(+ {+ "reason": "localLLMBackendUnavailable",+ "modelWeights.status": "cached",+ "modelWeights.path": str(model_file),+ "modelWeights.provider": "donkey-managed-download",+ "backend.provider": "llama-cpp-python",+ "detail": str(exc),+ }+ ),+ }++ prompt, max_tokens = local_llm_prompt_and_limit(request)started = time.monotonic()try:- response = post_json(- "/api/generate",- json.dumps(body).encode("utf-8"),- timeout=local_llm_timeout_seconds(),+ llm = Llama(+ model_path=str(model_file),+ n_ctx=local_llm_int_env("DONKEY_LOCAL_LLM_CONTEXT_TOKENS", 4096),+ n_threads=local_llm_int_env("DONKEY_LOCAL_LLM_THREADS", max(1, os.cpu_count() or 1)),+ verbose=False,+ )+ response = llm(+ prompt,+ max_tokens=max_tokens,+ temperature=0,+ top_p=0.8,+ stop=["<|im_end|>", "\n\n\n"],)latency_ms = (time.monotonic() - started) * 1000- output_text = str(response.get("response", ""))- response_metadata = {- "local.provider": "ollama-sidecar",- "http.status": "200",- "latency.localLLMGenerationMS": f"{latency_ms:.3f}",- }- requested_model = str(request.get("modelID") or MODEL_ID)- if body["model"] != requested_model:- response_metadata.update(- {- "modelFallback.originalModelID": requested_model,- "modelFallback.selectedModelID": body["model"],- "modelFallback.reason": "requestedModelUnavailable",- }- )- if is_task_intent_request:+ choices = response.get("choices") if isinstance(response, dict) else []+ output_text = ""+ if choices and isinstance(choices[0], dict):+ output_text = str(choices[0].get("text") or "").strip()+ schema_id = str((request.get("metadata") or {}).get("schemaID") or "")+ if schema_id in {"", "task_intent_v1"}:output_text, repair_metadata = repair_task_intent_output(output_text,- command=str(command),- model_id=str(body["model"]),+ command=str(request.get("command") or ""),+ model_id=MODEL_ID,context_snippets=request.get("contextSnippets", []),)- response_metadata.update(repair_metadata)+ else:+ repair_metadata = {}return {"outputText": output_text,- "metadata": metadata(response_metadata),+ "metadata": metadata(+ {+ "local.provider": "llama-cpp-python",+ "backend.provider": "llama-cpp-python",+ "latency.localLLMGenerationMS": f"{latency_ms:.3f}",+ "modelWeights.status": "cached",+ "modelWeights.path": str(model_file),+ "modelWeights.provider": "donkey-managed-download",+ **repair_metadata,+ }+ ),}except Exception as exc: # noqa: BLE001return {"outputText": "",- "metadata": metadata({"reason": "localLLMGenerationFailed", "detail": str(exc)}),+ "metadata": metadata(+ {+ "reason": "localLLMGenerationFailed",+ "modelWeights.status": "cached",+ "modelWeights.path": str(model_file),+ "modelWeights.provider": "donkey-managed-download",+ "backend.provider": "llama-cpp-python",+ "detail": str(exc),+ }+ ),}+def local_llm_prompt_and_limit(request: dict[str, Any]) -> tuple[str, int]:+ command = str(request.get("command") or "")+ schema_id = str((request.get("metadata") or {}).get("schemaID") or "")+ if schema_id == "task_followup_resolution_v1":+ candidates = request.get("candidates", [])+ return json_prompt(+ task_followup_prompt(command, candidates),+ task_followup_schema(candidates),+ ), 160+ if schema_id == "agent_visualization_plan":+ return json_prompt(+ agent_visualization_plan_prompt(+ command,+ request.get("runtimeCapabilities", []),+ request.get("cacheSnippets", []),+ ),+ agent_visualization_plan_schema(),+ ), 320+ task_definitions = request.get("taskDefinitions", [])+ return json_prompt(+ task_intent_prompt(command, task_definitions, request.get("contextSnippets", [])),+ task_intent_schema(task_definitions),+ ), 640+++def json_prompt(instructions: str, schema: dict[str, Any]) -> str:+ return "\n".join(+ [+ "<|im_start|>system",+ "You are Donkey's local structured-output command parser.",+ "Return only one valid JSON object. Do not include markdown, explanations, or thinking text.",+ "<|im_end|>",+ "<|im_start|>user",+ instructions,+ "JSON schema:",+ json.dumps(schema, separators=(",", ":")),+ "<|im_end|>",+ "<|im_start|>assistant",+ ]+ )+++def local_llm_int_env(name: str, default_value: int) -> int:+ try:+ return max(1, int(os.environ.get(name, str(default_value))))+ except ValueError:+ return default_value++def repair_task_intent_output(output_text: str,command: str,model_id: str,context_snippets: list[Any] | None = None,) -> tuple[str, dict[str, str]]:+ _ = (command, model_id, context_snippets)intent = decode_json_object(output_text)if not isinstance(intent, dict):return output_text, {}@@ -556,78 +602,9 @@ def repair_task_intent_output(output_metadata: dict[str, str] = {}if clear_empty_conversation_mode(intent):output_metadata["modelPlan.clearedEmptyConversationMode"] = "true"-- chain_metadata = repair_app_chain_metadata(- intent,- command=command,- model_id=model_id,- context_snippets=context_snippets or [],- )- output_metadata.update(chain_metadata)-- if not should_repair_document_text_payload(intent, command):- if output_metadata:- return json.dumps(intent, separators=(",", ":")), output_metadata- return output_text, {}-- started = time.monotonic()- try:- response = post_json(- "/api/generate",- json.dumps(- {- "model": model_id,- "prompt": document_text_payload_prompt(command),- "stream": False,- "format": document_text_payload_schema(),- "options": {- "num_ctx": 1024,- "num_predict": 220,- "temperature": 0.35,- "top_p": 0.9,- },- "keep_alive": "10m",- }- ).encode("utf-8"),- timeout=min(local_llm_timeout_seconds(), 15),- )- latency_ms = (time.monotonic() - started) * 1000- payload = decode_json_object(str(response.get("response", "")))- metadata = {- "modelPlan.textPayloadRepair": "attempted",- "latency.textPayloadRepairMS": f"{latency_ms:.3f}",- }- if isinstance(payload, dict) and bool(payload.get("canWrite")):- text = str(payload.get("text") or "").strip()- if text:- set_intent_query(intent, text)- intent_metadata = intent.setdefault("metadata", {})- if isinstance(intent_metadata, dict):- intent_metadata.pop("responseMode", None)- intent_metadata.pop("assistantResponse", None)- intent_metadata.pop("notActionableReason", None)- intent_metadata["modelPlan.repairedTextPayload"] = "true"- metadata["modelPlan.textPayloadRepair"] = "completed"- metadata.update(output_metadata)- return json.dumps(intent, separators=(",", ":")), metadata-- assistant_response = "I can help, but I need a clearer thing to write before opening an app."- if isinstance(payload, dict):- candidate_response = str(payload.get("assistantResponse") or "").strip()- if candidate_response:- assistant_response = candidate_response- mark_intent_as_conversation(intent, assistant_response, "contentGenerationDeclined")- metadata["modelPlan.textPayloadRepair"] = "conversation"- metadata.update(output_metadata)- return json.dumps(intent, separators=(",", ":")), metadata- except Exception as exc: # noqa: BLE001- output_metadata.update(- {- "modelPlan.textPayloadRepair": "failed",- "modelPlan.textPayloadRepairError": str(exc)[:240],- }- )+ if output_metadata:return json.dumps(intent, separators=(",", ":")), output_metadata+ return output_text, {}def clear_empty_conversation_mode(intent: dict[str, Any]) -> bool:@@ -653,65 +630,8 @@ def repair_app_chain_metadata(model_id: str,context_snippets: list[Any],) -> dict[str, str]:- if existing_app_chain(intent):- return {}- if not should_consider_app_chain_repair(intent):- return {}-- started = time.monotonic()- try:- response = post_json(- "/api/generate",- json.dumps(- {- "model": model_id,- "prompt": app_chain_repair_prompt(command, intent, context_snippets),- "stream": False,- "format": app_chain_repair_schema(),- "options": {- "num_ctx": 1024,- "num_predict": 180,- "temperature": 0,- "top_p": 0.8,- },- "keep_alive": "10m",- }- ).encode("utf-8"),- timeout=min(local_llm_timeout_seconds(), 15),- )- latency_ms = (time.monotonic() - started) * 1000- payload = decode_json_object(str(response.get("response", "")))- metadata = {- "modelPlan.appChainRepair": "attempted",- "latency.appChainRepairMS": f"{latency_ms:.3f}",- }- if not isinstance(payload, dict) or not bool(payload.get("needsChain")):- metadata["modelPlan.appChainRepair"] = "notNeeded"- return metadata-- app_chain = [str(item).strip() for item in payload.get("appChain", []) if str(item).strip()]- target_app = target_app_name(intent)- if target_app and (not app_chain or normalized_words(app_chain[-1]) != normalized_words(target_app)):- app_chain.append(target_app)- if len(app_chain) < 2:- metadata["modelPlan.appChainRepair"] = "invalid"- return metadata-- source_apps = [item for item in app_chain[:-1]]- intent_metadata = intent.setdefault("metadata", {})- if isinstance(intent_metadata, dict):- intent_metadata["appChain"] = json.dumps(app_chain, separators=(",", ":"))- intent_metadata["sourceApps"] = json.dumps(source_apps, separators=(",", ":"))- reason = str(payload.get("reason") or "").strip()- if reason:- intent_metadata["chainReason"] = reason- metadata["modelPlan.appChainRepair"] = "completed"- return metadata- except Exception as exc: # noqa: BLE001- return {- "modelPlan.appChainRepair": "failed",- "modelPlan.appChainRepairError": str(exc)[:240],- }+ _ = (intent, command, model_id, context_snippets)+ return {}def existing_app_chain(intent: dict[str, Any]) -> list[str]:@@ -940,35 +860,6 @@ def command_contains_quoted(query: str, command: str) -> bool:return any(f"{quote}{trimmed.lower()}{quote}" in lowered_command for quote in ["\"", "'", "`"])-def selected_ollama_model(requested_model_id: str) -> str:- names = ollama_model_names()- if requested_model_id in names or f"{requested_model_id}:latest" in names:- return requested_model_id-- for prefix in [- "qwen3",- "qwen2.5",- "llama3.1",- "llama3",- "mistral",- "gemma3",- "gemma2",- ]:- for name in names:- if name == prefix or name.startswith(f"{prefix}:"):- return name-- return requested_model_id---def local_llm_timeout_seconds() -> int:- raw_value = os.environ.get("DONKEY_LOCAL_LLM_TIMEOUT_SECONDS", "20")- try:- return max(1, int(raw_value))- except ValueError:- return 20--def task_followup_prompt(command: str, candidates: list[dict[str, Any]]) -> str:candidate_lines: list[str] = []for index, candidate in enumerate(candidates, start=1):@@ -1407,69 +1298,5 @@ def run_external_json_command(command: str, request: dict[str, Any]) -> dict[strreturn error_payload("externalCommandInvalidPayload")-def ollama_has_model(model_id: str) -> bool:- names = set(ollama_model_names())- if names:- return model_id in names or f"{model_id}:latest" in names- return False---def ollama_model_names() -> list[str]:- try:- tags = get_json("/api/tags", timeout=3)- models = tags.get("models", [])- names = []- for item in models:- if not isinstance(item, dict):- continue- name = str(item.get("name") or "")- size = int(item.get("size") or 0)- if name and ":cloud" not in name and size > 0:- names.append(name)- return names- except Exception: # noqa: BLE001- pass-- if shutil.which("ollama"):- completed = subprocess.run(- ["ollama", "list"],- stdout=subprocess.PIPE,- stderr=subprocess.DEVNULL,- text=True,- check=False,- )- if completed.returncode == 0:- names = []- for line in completed.stdout.splitlines()[1:]:- parts = line.split()- if not parts:- continue- name = parts[0]- if name and ":cloud" not in name:- names.append(name)- return names- return []---def get_json(path: str, timeout: int) -> dict[str, Any]:- with urllib.request.urlopen(OLLAMA_ENDPOINT + path, timeout=timeout) as response:- return json.loads(response.read().decode("utf-8"))---def post_json(path: str, payload: bytes, timeout: int) -> dict[str, Any]:- request = urllib.request.Request(- OLLAMA_ENDPOINT + path,- data=payload,- headers={"Content-Type": "application/json"},- method="POST",- )- try:- with urllib.request.urlopen(request, timeout=timeout) as response:- return json.loads(response.read().decode("utf-8"))- except urllib.error.HTTPError as exc:- detail = exc.read().decode("utf-8", errors="replace")- raise RuntimeError(f"ollama HTTP {exc.code}: {detail}") from exc--if __name__ == "__main__":raise SystemExit(main())diff --git a/scripts/package-donkey-app.sh b/scripts/package-donkey-app.shindex 46120acd..585e5a93 100755--- a/scripts/package-donkey-app.sh+++ b/scripts/package-donkey-app.sh@@ -208,7 +208,7 @@ mkdir -p "$RUNTIME_PACKAGE_DIR"make_runtime_package "parakeet-transcriber" "donkey-parakeet-transcriber" "nvidia/parakeet-tdt-0.6b-v3" "voiceTranscription" "${DONKEY_PARAKEET_MODEL_URL:-}" "${DONKEY_PARAKEET_MODEL_SHA256:-}" "${DONKEY_PARAKEET_MODEL_FILENAME:-parakeet-model.bin}" $'huggingface_hub>=0.25,<1'make_runtime_package "yolo-segmenter" "donkey-yolo-segmenter" "ultralytics/yolo26n-seg" "screenshotSegmentation" "${DONKEY_YOLO_MODEL_URL:-}" "${DONKEY_YOLO_MODEL_SHA256:-}" "${DONKEY_YOLO_MODEL_FILENAME:-yolo26n-seg.pt}" $'ultralytics>=8.3,<9\nopencv-python-headless>=4.10,<5'make_binary_runtime_package "ui-understander" "donkey-ui-understander" "$UI_UNDERSTANDER_EXECUTABLE" "apple-vision-text-recognition" "uiUnderstanding"-make_runtime_package "local-llm" "donkey-local-llm" "${DONKEY_LOCAL_LLM_MODEL_ID:-qwen3:8b}" "localLLM" "" "" "${DONKEY_LOCAL_LLM_MODEL_FILENAME:-ollama-qwen3-8b}"+make_runtime_package "local-llm" "donkey-local-llm" "${DONKEY_LOCAL_LLM_MODEL_ID:-qwen3-0.6b-q4_0}" "localLLM" "${DONKEY_LOCAL_LLM_MODEL_URL:-https://huggingface.co/ggml-org/Qwen3-0.6B-GGUF/resolve/main/Qwen3-0.6B-Q4_0.gguf}" "${DONKEY_LOCAL_LLM_MODEL_SHA256:-da2572f16c06133561ce56accaa822216f2391ef4d37fba427801cd6736417d4}" "${DONKEY_LOCAL_LLM_MODEL_FILENAME:-Qwen3-0.6B-Q4_0.gguf}" $'llama-cpp-python>=0.3,<0.4'RESOURCE_BUNDLE="$(find "$BUILD_DIR/.build" -path "*/release/Donkey_Donkey.bundle" -type d | head -n 1 || true)"if [ -n "$RESOURCE_BUNDLE" ]; thendiff --git a/scripts/run-donkey-dev.sh b/scripts/run-donkey-dev.shindex cd80c107..5e321079 100755--- a/scripts/run-donkey-dev.sh+++ b/scripts/run-donkey-dev.sh@@ -5,6 +5,11 @@ ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"APP_DIR="$ROOT_DIR/apps/Donkey"LOG_SCRIPT="$ROOT_DIR/scripts/tail-donkey-logs.sh"DONKEY_BIN="$APP_DIR/.build/debug/Donkey"+DEV_RUNTIME_MANIFEST_SCRIPT="$ROOT_DIR/scripts/create-dev-runtime-manifests.py"+DEV_RUNTIME_SETUP_SCRIPT="$ROOT_DIR/scripts/setup-dev-local-runtimes.py"+PACKAGE_SCRIPT="$ROOT_DIR/scripts/package-donkey-app.sh"+DEV_RUNTIME_PACKAGE_DIR="${DONKEY_DEV_RUNTIME_PACKAGE_DIR:-$ROOT_DIR/dist/LocalRuntimePackages}"+DEV_RUNTIME_ENV_FILE="${DONKEY_DEV_RUNTIME_ENV_FILE:-$ROOT_DIR/dist/donkey-dev-runtime-manifests.env}"LOG_PID=""cleanup() {@@ -50,11 +55,121 @@ start_logger() {LOG_PID="$!"}+runtime_manifest_env_is_configured() {+ [ -n "${DONKEY_RUNTIME_PACKAGE_MANIFEST_URLS:-}" ] \+ || [ -n "${DONKEY_PARAKEET_RUNTIME_MANIFEST_URL:-}" ] \+ || [ -n "${DONKEY_YOLO_RUNTIME_MANIFEST_URL:-}" ] \+ || [ -n "${DONKEY_UI_UNDERSTANDER_RUNTIME_MANIFEST_URL:-}" ] \+ || [ -n "${DONKEY_LOCAL_LLM_RUNTIME_MANIFEST_URL:-}" ]+}++dev_runtime_packages_need_refresh() {+ if [ "${DONKEY_DEV_RUNTIME_PACKAGE_REFRESH:-0}" = "1" ]; then+ return 0+ fi+ if [ ! -d "$DEV_RUNTIME_PACKAGE_DIR" ]; then+ return 0+ fi+ python3 - "$DEV_RUNTIME_PACKAGE_DIR" <<'PY'+import json+import sys+from pathlib import Path++package_dir = Path(sys.argv[1])+expected_runtimes = {"local-llm", "parakeet-transcriber", "ui-understander", "yolo-segmenter"}+for runtime_id in expected_runtimes:+ if not (package_dir / runtime_id / "manifest.json").exists():+ raise SystemExit(0)+manifest_path = package_dir / "local-llm" / "manifest.json"+if not manifest_path.exists():+ raise SystemExit(0)+try:+ manifest = json.loads(manifest_path.read_text())+except Exception:+ raise SystemExit(0)+metadata = manifest.get("metadata") if isinstance(manifest.get("metadata"), dict) else {}+files = manifest.get("files") if isinstance(manifest.get("files"), list) else []+requirements_path = package_dir / "local-llm" / "requirements.txt"+if not str(metadata.get("modelWeights.downloadURL") or "").strip():+ raise SystemExit(0)+if not str(metadata.get("modelWeights.sha256") or "").strip():+ raise SystemExit(0)+if not requirements_path.exists() or "llama-cpp-python" not in requirements_path.read_text():+ raise SystemExit(0)+if not files:+ raise SystemExit(0)+raise SystemExit(1)+PY+}++refresh_dev_runtime_packages_if_needed() {+ if runtime_manifest_env_is_configured; then+ return+ fi+ if [ "${DONKEY_DEV_RUNTIME_AUTO_PACKAGE:-1}" = "0" ]; then+ return+ fi+ if ! dev_runtime_packages_need_refresh; then+ return+ fi++ echo "Refreshing local runtime packages for dev setup..."+ "$PACKAGE_SCRIPT"+}++load_dev_runtime_manifests() {+ if runtime_manifest_env_is_configured; then+ echo "Using runtime manifest URLs from environment."+ return+ fi++ if [ "${DONKEY_DEV_RUNTIME_MANIFESTS:-1}" = "0" ]; then+ echo "Skipping dev runtime manifest setup because DONKEY_DEV_RUNTIME_MANIFESTS=0."+ return+ fi++ if [ -d "$DEV_RUNTIME_PACKAGE_DIR" ]; then+ echo "Refreshing local runtime manifest env from $DEV_RUNTIME_PACKAGE_DIR..."+ DONKEY_DEV_RUNTIME_PACKAGE_DIR="$DEV_RUNTIME_PACKAGE_DIR" \+ DONKEY_DEV_RUNTIME_ENV_FILE="$DEV_RUNTIME_ENV_FILE" \+ python3 "$DEV_RUNTIME_MANIFEST_SCRIPT" || true+ fi++ if [ -f "$DEV_RUNTIME_ENV_FILE" ]; then+ echo "Loading local runtime manifest env from $DEV_RUNTIME_ENV_FILE..."+ # shellcheck source=/dev/null+ source "$DEV_RUNTIME_ENV_FILE"+ return+ fi++ echo "No local runtime manifest env found. Check package output above, or set DONKEY_RUNTIME_PACKAGE_MANIFEST_URLS."+}++setup_missing_local_runtimes() {+ if [ "${DONKEY_DEV_RUNTIME_SETUP:-1}" = "0" ]; then+ echo "Skipping local runtime setup because DONKEY_DEV_RUNTIME_SETUP=0."+ return+ fi++ if ! runtime_manifest_env_is_configured; then+ echo "Skipping local runtime setup because no runtime manifest URLs are configured."+ return+ fi++ echo "Setting up missing local runtimes..."+ if ! python3 "$DEV_RUNTIME_SETUP_SCRIPT"; then+ echo "Warning: dev local runtime setup failed; continuing to launch Donkey." >&2+ fi+}+trap cleanup EXITecho "Stopping any running Donkey app..."killall Donkey >/dev/null 2>&1 || true+refresh_dev_runtime_packages_if_needed+load_dev_runtime_manifests+cd "$APP_DIR"echo "Building Donkey..."@@ -65,6 +180,8 @@ if [ ! -x "$DONKEY_BIN" ]; thenexit 1fi+setup_missing_local_runtimes+echo "Starting Donkey..."start_logger"$DONKEY_BIN"diff --git a/scripts/setup-dev-local-runtimes.py b/scripts/setup-dev-local-runtimes.pynew file mode 100755index 00000000..c28c2dd3--- /dev/null+++ b/scripts/setup-dev-local-runtimes.py@@ -0,0 +1,336 @@+#!/usr/bin/env python3+"""Install local runtime packages for `scripts/run-donkey-dev.sh`."""++from __future__ import annotations++import hashlib+import json+import os+import shutil+import subprocess+import sys+import tempfile+import urllib.request+from datetime import datetime, timezone+from pathlib import Path+from typing import Any+++RUNTIME_ENV_NAMES = {+ "local-llm": "DONKEY_LOCAL_LLM_RUNTIME_MANIFEST_URL",+ "parakeet-transcriber": "DONKEY_PARAKEET_RUNTIME_MANIFEST_URL",+ "ui-understander": "DONKEY_UI_UNDERSTANDER_RUNTIME_MANIFEST_URL",+ "yolo-segmenter": "DONKEY_YOLO_RUNTIME_MANIFEST_URL",+}++RUNTIME_EXECUTABLE_ENV_NAMES = {+ "local-llm": "DONKEY_LOCAL_LLM_RUNNER",+ "parakeet-transcriber": "DONKEY_PARAKEET_TRANSCRIBER",+ "ui-understander": "DONKEY_UI_UNDERSTANDER",+ "yolo-segmenter": "DONKEY_YOLO_SEGMENTER",+}++DEFAULT_BASE_DIR = (+ Path.home()+ / "Library"+ / "Application Support"+ / "Donkey"+ / "LocalModelRuntimes"+)+++def main() -> int:+ manifest_urls = configured_manifest_urls()+ if not manifest_urls:+ print("No local runtime manifest URLs are configured; skipping dev runtime setup.")+ return 0++ base_dir = Path(os.environ.get("DONKEY_DEV_RUNTIME_BASE_DIR", DEFAULT_BASE_DIR)).expanduser()+ registry = load_registry(base_dir)+ changed = False+ prepared_any = False++ for runtime_id, manifest_url in sorted(manifest_urls.items()):+ manifest = read_json_url(manifest_url)+ actual_runtime_id = str(manifest.get("runtimeID") or runtime_id)+ if actual_runtime_id != runtime_id:+ print(f"warning: manifest runtime mismatch for {runtime_id}: {actual_runtime_id}", file=sys.stderr)+ continue++ installation = registry.get("installations", {}).get(runtime_id)+ if installation_is_current(base_dir, installation, manifest):+ print(f"runtime {runtime_id}: already installed")+ continue++ installation = install_runtime(base_dir, manifest)+ registry.setdefault("installations", {})[runtime_id] = installation+ save_registry(base_dir, registry)+ changed = True+ print(f"runtime {runtime_id}: installed {installation['runtimeVersion']}")++ if os.environ.get("DONKEY_DEV_RUNTIME_PREPARE", "1") != "0":+ prepared_any = True+ prepare_and_check(base_dir, installation, manifest)++ if not changed:+ print("dev local runtime setup: nothing missing")+ elif not prepared_any:+ print("dev local runtime setup: installed missing packages; model preparation skipped")+ else:+ print("dev local runtime setup: finished missing-runtime pass")+ return 0+++def configured_manifest_urls() -> dict[str, str]:+ urls: dict[str, str] = {}+ combined = os.environ.get("DONKEY_RUNTIME_PACKAGE_MANIFEST_URLS", "")+ for pair in combined.split(","):+ if not pair or "=" not in pair:+ continue+ runtime_id, value = pair.split("=", 1)+ if runtime_id and value:+ urls[runtime_id] = value++ for runtime_id, env_name in RUNTIME_ENV_NAMES.items():+ value = os.environ.get(env_name, "")+ if value:+ urls[runtime_id] = value+ return urls+++def read_json_url(url: str) -> dict[str, Any]:+ with urllib.request.urlopen(url, timeout=30) as response:+ return json.loads(response.read().decode("utf-8"))+++def load_registry(base_dir: Path) -> dict[str, Any]:+ registry_path = registry_file(base_dir)+ if not registry_path.exists():+ return {"installations": {}}+ try:+ return json.loads(registry_path.read_text())+ except json.JSONDecodeError:+ return {"installations": {}}+++def save_registry(base_dir: Path, registry: dict[str, Any]) -> None:+ base_dir.mkdir(parents=True, exist_ok=True)+ registry_path = registry_file(base_dir)+ fd, tmp_name = tempfile.mkstemp(prefix=".runtime-installations.", suffix=".json", dir=base_dir)+ try:+ with os.fdopen(fd, "w") as output:+ json.dump(registry, output, indent=2, sort_keys=True)+ output.write("\n")+ Path(tmp_name).replace(registry_path)+ finally:+ Path(tmp_name).unlink(missing_ok=True)+++def registry_file(base_dir: Path) -> Path:+ return base_dir / "runtime-installations.json"+++def installation_is_current(+ base_dir: Path,+ installation: dict[str, Any] | None,+ manifest: dict[str, Any],+) -> bool:+ if os.environ.get("DONKEY_DEV_RUNTIME_FORCE_SETUP", "0") == "1":+ return False+ if not isinstance(installation, dict):+ return False+ executable_path = Path(str(installation.get("executablePath") or ""))+ if not executable_path.is_file() or not os.access(executable_path, os.X_OK):+ return False+ if str(installation.get("runtimeVersion") or "") != str(manifest.get("runtimeVersion") or ""):+ return False+ if str(installation.get("modelID") or "") != str(manifest.get("modelID") or ""):+ return False+ downloaded_dir = Path(str(installation.get("downloadedDirectoryPath") or ""))+ if not is_relative_to(downloaded_dir, base_dir) or not downloaded_dir.exists():+ return False+ manifest_metadata = manifest.get("metadata") if isinstance(manifest.get("metadata"), dict) else {}+ install_metadata = installation.get("metadata") if isinstance(installation.get("metadata"), dict) else {}+ for key in ["modelWeights.downloadURL", "modelWeights.sha256", "modelWeights.filename", "runtime.package"]:+ if str(install_metadata.get(key) or "") != str(manifest_metadata.get(key) or ""):+ return False+ for item in manifest.get("files", []):+ if not isinstance(item, dict):+ return False+ relative_path = str(item.get("relativePath") or "")+ expected_sha = str(item.get("sha256") or "").lower()+ if not relative_path or not expected_sha:+ return False+ installed_file = safe_join(downloaded_dir, relative_path)+ if not installed_file.exists():+ return False+ if hashlib.sha256(installed_file.read_bytes()).hexdigest() != expected_sha:+ return False+ if bool(item.get("isExecutable")) and not os.access(installed_file, os.X_OK):+ return False+ return True+++def install_runtime(base_dir: Path, manifest: dict[str, Any]) -> dict[str, Any]:+ runtime_id = str(manifest["runtimeID"])+ runtime_version = str(manifest["runtimeVersion"])+ managed_dir = base_dir / "Packages" / runtime_id / runtime_version+ if is_relative_to(managed_dir, base_dir) and managed_dir.exists():+ shutil.rmtree(managed_dir)+ managed_dir.mkdir(parents=True, exist_ok=True)++ for item in manifest.get("files", []):+ relative_path = str(item["relativePath"])+ destination = safe_join(managed_dir, relative_path)+ destination.parent.mkdir(parents=True, exist_ok=True)+ data = read_url_bytes(str(item["downloadURL"]))+ actual_sha = hashlib.sha256(data).hexdigest()+ expected_sha = str(item["sha256"]).lower()+ if actual_sha != expected_sha:+ raise RuntimeError(f"{runtime_id} {relative_path} hash mismatch: {actual_sha} != {expected_sha}")+ destination.write_bytes(data)+ if bool(item.get("isExecutable")):+ destination.chmod(0o755)++ executable_path = safe_join(managed_dir, str(manifest["executableRelativePath"]))+ if not executable_path.is_file() or not os.access(executable_path, os.X_OK):+ raise RuntimeError(f"installed executable missing or not executable: {executable_path}")++ metadata = {+ "installedBy": "donkey-dev-runtime-setup",+ "manifest.platform": str(manifest.get("platform") or ""),+ "manifest.architecture": str(manifest.get("architecture") or ""),+ "manifest.minimumDonkeyVersion": str(manifest.get("minimumDonkeyVersion") or ""),+ "manifest.signingKeyID": str(manifest.get("signingKeyID") or ""),+ "manifest.signaturePresent": str(manifest.get("signature") is not None).lower(),+ }+ manifest_metadata = manifest.get("metadata")+ if isinstance(manifest_metadata, dict):+ metadata.update({str(key): str(value) for key, value in manifest_metadata.items()})++ return {+ "runtimeID": runtime_id,+ "executablePath": str(executable_path),+ "downloadedDirectoryPath": str(managed_dir),+ "installedAt": datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"),+ "runtimeVersion": runtime_version,+ "modelID": str(manifest.get("modelID") or ""),+ "sidecarProtocolVersion": str(manifest.get("sidecarProtocolVersion") or "v1"),+ "metadata": metadata,+ }+++def read_url_bytes(url: str) -> bytes:+ with urllib.request.urlopen(url, timeout=60) as response:+ return response.read()+++def safe_join(root: Path, relative_path: str) -> Path:+ candidate = root+ for component in Path(relative_path).parts:+ if component in {"", ".", ".."}:+ raise RuntimeError(f"unsafe runtime package path: {relative_path}")+ candidate = candidate / component+ return candidate+++def prepare_and_check(base_dir: Path, installation: dict[str, Any], manifest: dict[str, Any]) -> None:+ runtime_id = str(installation["runtimeID"])+ cache_dir = model_cache_dir(base_dir, installation)+ cache_dir.mkdir(parents=True, exist_ok=True)+ request = {+ "operation": "prepareModelWeights",+ "protocolVersion": str(installation.get("sidecarProtocolVersion") or "v1"),+ "runtimeID": runtime_id,+ "runtimeVersion": str(installation.get("runtimeVersion") or ""),+ "modelID": str(installation.get("modelID") or manifest.get("modelID") or ""),+ "cacheDirectory": str(cache_dir),+ "metadata": metadata_for_sidecar(installation, manifest),+ }+ print(f"runtime {runtime_id}: preparing model weights and backend...", flush=True)+ prepare = run_sidecar(installation, request, timeout_seconds=dev_timeout("DONKEY_DEV_RUNTIME_PREPARE_TIMEOUT_SECONDS", 600))+ print_sidecar_status(runtime_id, "prepare", prepare)++ health_request = dict(request)+ health_request["operation"] = "healthCheck"+ print(f"runtime {runtime_id}: checking health...", flush=True)+ health = run_sidecar(installation, health_request, timeout_seconds=dev_timeout("DONKEY_DEV_RUNTIME_HEALTH_TIMEOUT_SECONDS", 15))+ print_sidecar_status(runtime_id, "health", health)+++def metadata_for_sidecar(installation: dict[str, Any], manifest: dict[str, Any]) -> dict[str, str]:+ values: dict[str, str] = {}+ spec_metadata = manifest.get("metadata")+ if isinstance(spec_metadata, dict):+ values.update({str(key): str(value) for key, value in spec_metadata.items()})+ install_metadata = installation.get("metadata")+ if isinstance(install_metadata, dict):+ values.update({str(key): str(value) for key, value in install_metadata.items()})+ return values+++def run_sidecar(installation: dict[str, Any], request: dict[str, Any], timeout_seconds: int) -> dict[str, Any]:+ runtime_id = str(installation["runtimeID"])+ executable_path = str(installation["executablePath"])+ environment = os.environ.copy()+ env_name = RUNTIME_EXECUTABLE_ENV_NAMES.get(runtime_id)+ if env_name:+ environment[env_name] = executable_path+ try:+ completed = subprocess.run(+ [executable_path],+ input=json.dumps(request),+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ env=environment,+ timeout=timeout_seconds,+ check=False,+ )+ except subprocess.TimeoutExpired:+ return {"status": "timeout", "metadata": {"reason": "timeout"}}++ try:+ payload = json.loads(completed.stdout or "{}")+ except json.JSONDecodeError:+ payload = {"status": "invalidOutput", "metadata": {"stdout": completed.stdout[-400:]}}+ if completed.returncode != 0:+ payload.setdefault("metadata", {})["exitCode"] = str(completed.returncode)+ if completed.stderr:+ payload.setdefault("metadata", {})["stderr"] = completed.stderr[-400:]+ return payload+++def print_sidecar_status(runtime_id: str, phase: str, payload: dict[str, Any]) -> None:+ status = str(payload.get("status") or "unknown")+ metadata = payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {}+ reason = metadata.get("reason") or metadata.get("modelWeights.status") or "-"+ output = f"runtime {runtime_id}: {phase} {status} ({reason})"+ if status == "ok":+ print(output)+ else:+ print(f"warning: {output}", file=sys.stderr)+++def model_cache_dir(base_dir: Path, installation: dict[str, Any]) -> Path:+ model_id = str(installation.get("modelID") or installation["runtimeID"]).replace("/", "-").replace(":", "-")+ return base_dir / "ModelWeights" / str(installation["runtimeID"]) / model_id+++def dev_timeout(name: str, default_value: int) -> int:+ try:+ return max(1, int(os.environ.get(name, str(default_value))))+ except ValueError:+ return default_value+++def is_relative_to(path: Path, root: Path) -> bool:+ try:+ path.resolve().relative_to(root.resolve())+ return True+ except ValueError:+ return False+++if __name__ == "__main__":+ raise SystemExit(main())