Skip to content

Open source CapCut alternative.

TypeScript

Improve local task intent planning

David Le985707b6d616
diff --git a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift
index 4b48043c..07f94e09 100644
--- a/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift
+++ b/apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift
@@ -283,7 +283,7 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
PointerPromptSpawnProgressUpdate(label: "Answering"),
context: context
)
- let response = "I couldn't find a supported local action for that yet."
+ let response = Self.conversationResponse(for: resolution)
let decision = AppHarnessDecision(
kind: .respond,
message: response,
@@ -430,9 +430,23 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
let taskType = resolution.definition?.taskType ?? resolution.intent?.taskType ?? ""
let reason = resolution.metadata["reason"] ?? ""
+ let modelReason = resolution.metadata["model.reason"]
+ ?? resolution.metadata["model.fallback.reason"]
+ ?? trace.metadata["reason"]
+ ?? trace.metadata["fallback.reason"]
+ ?? trace.metadata["modelFallback.reason"]
+ ?? ""
+ let modelDetail = resolution.metadata["model.detail"]
+ ?? resolution.metadata["model.http.bodyPreview"]
+ ?? resolution.metadata["model.fallback.http.bodyPreview"]
+ ?? trace.metadata["detail"]
+ ?? trace.metadata["http.bodyPreview"]
+ ?? trace.metadata["fallback.http.bodyPreview"]
+ ?? ""
+ let fallbackStatus = trace.metadata["fallback.status"] ?? ""
let latency = Self.formatLatency(latencyMS)
PointerPromptLog.commands.notice(
- "intent resolved traceID=\(traceID, privacy: .public) resolution=\(resolution.status.rawValue, privacy: .public) taskType=\(taskType, privacy: .public) reason=\(reason, privacy: .public) modelStatus=\(trace.status.rawValue, privacy: .public) validation=\(trace.validationStatus, privacy: .public) latencyMS=\(latency, privacy: .public) command=\(command, privacy: .public)"
+ "intent resolved traceID=\(traceID, privacy: .public) resolution=\(resolution.status.rawValue, privacy: .public) taskType=\(taskType, privacy: .public) reason=\(reason, privacy: .public) modelStatus=\(trace.status.rawValue, privacy: .public) validation=\(trace.validationStatus, privacy: .public) modelReason=\(modelReason, privacy: .public) modelDetail=\(modelDetail, privacy: .public) fallbackStatus=\(fallbackStatus, privacy: .public) latencyMS=\(latency, privacy: .public) command=\(command, privacy: .public)"
)
}
@@ -480,9 +494,25 @@ struct LocalAppPointerPromptCommandHandler: PointerPromptCommandHandling {
}
private static func shouldRespondWithoutLocalTask(_ resolution: LocalAppTaskCatalogResolution) -> Bool {
- resolution.intent == nil
- && resolution.status == .needsConfirmation
- && resolution.metadata["reason"] == "localModelIntentUnavailable"
+ guard resolution.status == .needsConfirmation else { return false }
+ if resolution.intent == nil,
+ resolution.metadata["reason"] == "localModelIntentUnavailable" {
+ return true
+ }
+ if resolution.metadata["responseMode"] == "conversation",
+ resolution.metadata["assistantResponse"]?.isEmpty == false {
+ return true
+ }
+ return resolution.metadata["reason"] == "lowConfidenceIntent"
+ && resolution.metadata["assistantResponse"]?.isEmpty == false
+ }
+
+ private static func conversationResponse(for resolution: LocalAppTaskCatalogResolution) -> String {
+ if let assistantResponse = resolution.metadata["assistantResponse"],
+ !assistantResponse.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ return assistantResponse
+ }
+ return "I couldn't find a supported local action for that yet."
}
private func retrieveSemanticMemory(
diff --git a/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift b/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift
index c505cae4..c13f7f07 100644
--- a/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift
+++ b/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift
@@ -88,7 +88,7 @@ public struct AIModelRegistry: Codable, Equatable, Sendable {
modelID: "gpt-5.2",
endpoint: URL(string: "https://api.openai.com/v1/responses")!,
capabilities: [.textInput, .structuredOutputs],
- timeoutMS: 8_000,
+ timeoutMS: 20_000,
promptVersion: "planner-hint-v1",
evalStatus: .candidate,
docsURL: URL(string: "https://platform.openai.com/docs/api-reference/responses/create")!,
@@ -110,7 +110,7 @@ public struct AIModelRegistry: Codable, Equatable, Sendable {
modelID: "qwen3:8b",
endpoint: URL(string: "local://qwen3-8b/task-intent")!,
capabilities: [.textInput, .structuredOutputs],
- timeoutMS: 4_000,
+ timeoutMS: 20_000,
promptVersion: "task-intent-v1",
evalStatus: .candidate,
docsURL: URL(string: "https://ollama.com/library/qwen3")!,
@@ -128,7 +128,7 @@ public struct AIModelRegistry: Codable, Equatable, Sendable {
modelID: "qwen3:8b",
endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,
capabilities: [.textInput, .structuredOutputs],
- timeoutMS: 4_000,
+ timeoutMS: 20_000,
promptVersion: "task-intent-v1",
evalStatus: .candidate,
docsURL: URL(string: "https://docs.ollama.com/api")!,
diff --git a/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift b/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift
index 9773e22d..e9296966 100644
--- a/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift
@@ -117,9 +117,25 @@ public struct ProcessBackedLocalLLMTaskIntentAdapter: TaskIntentParsingAdapter {
do {
let response = try decoder.decode(LocalLLMTaskIntentSidecarResponse.self, from: result.outputData)
+ let responseMetadata = result.metadata
+ .merging(response.metadata) { current, _ in current }
+ .merging(Self.outputDiagnostics(for: response.outputText)) { current, _ in current }
+ if response.outputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
+ response.metadata["reason"] != nil {
+ return self.result(
+ entry: entry,
+ request: request,
+ status: .providerOutage,
+ validationStatus: "notValidated",
+ latencyMS: result.latencyMS,
+ metadata: responseMetadata
+ )
+ }
+
guard let intent = try TaskIntentWireCodec.decodeIntent(
response.outputText,
definitions: request.taskDefinitions,
+ originalCommand: request.command,
sourceModelCallID: "model-call-\(request.sourceTraceID)",
parserName: "local-llm-sidecar-v1"
) else {
@@ -129,7 +145,7 @@ public struct ProcessBackedLocalLLMTaskIntentAdapter: TaskIntentParsingAdapter {
status: .invalidOutput,
validationStatus: "invalid",
latencyMS: result.latencyMS,
- metadata: result.metadata.merging(response.metadata) { current, _ in current }
+ metadata: responseMetadata
)
}
@@ -141,7 +157,7 @@ public struct ProcessBackedLocalLLMTaskIntentAdapter: TaskIntentParsingAdapter {
status: .completed,
validationStatus: "schemaDecoded",
latencyMS: result.latencyMS,
- metadata: result.metadata.merging(response.metadata) { current, _ in current }
+ metadata: responseMetadata
)
)
} catch {
@@ -152,12 +168,37 @@ public struct ProcessBackedLocalLLMTaskIntentAdapter: TaskIntentParsingAdapter {
validationStatus: "invalid",
latencyMS: result.latencyMS,
metadata: result.metadata.merging([
- "error": String(describing: error)
+ "error": String(describing: error),
+ "sidecar.outputPreview": Self.preview(result.outputData, maxCharacters: 240)
]) { current, _ in current }
)
}
}
+ private static func outputDiagnostics(for outputText: String) -> [String: String] {
+ let trimmed = outputText.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else {
+ return ["modelOutput.empty": "true"]
+ }
+
+ return [
+ "modelOutput.empty": "false",
+ "modelOutput.preview": preview(trimmed, maxCharacters: 240)
+ ]
+ }
+
+ private static func preview(_ data: Data, maxCharacters: Int) -> String {
+ preview(String(decoding: data, as: UTF8.self), maxCharacters: maxCharacters)
+ }
+
+ private static func preview(_ value: String, maxCharacters: Int) -> String {
+ let singleLine = value
+ .replacingOccurrences(of: "\n", with: "\\n")
+ .replacingOccurrences(of: "\r", with: "\\r")
+ guard singleLine.count > maxCharacters else { return singleLine }
+ return String(singleLine.prefix(maxCharacters))
+ }
+
private func result(
entry: AIModelRegistryEntry?,
request: TaskIntentAdapterRequest,
@@ -250,17 +291,69 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {
}
let startedAt = ProcessInfo.processInfo.systemUptime
+ return await parseTaskIntent(
+ request,
+ entry: entry,
+ startedAt: startedAt,
+ fallbackFromModelID: nil
+ )
+ }
+
+ private func parseTaskIntent(
+ _ request: TaskIntentAdapterRequest,
+ entry: AIModelRegistryEntry,
+ startedAt: Double,
+ fallbackFromModelID: String?
+ ) async -> TaskIntentAdapterResult {
do {
let urlRequest = try makeURLRequest(entry: entry, adapterRequest: request)
let (data, response) = try await httpClient.send(urlRequest)
let latencyMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000
+ if response.statusCode == 404,
+ fallbackFromModelID == nil,
+ let fallbackModelID = try? await fallbackOllamaModelID(
+ for: entry,
+ excluding: [entry.modelID]
+ ),
+ fallbackModelID != entry.modelID {
+ var fallbackEntry = entry
+ fallbackEntry.modelID = fallbackModelID
+ fallbackEntry.metadata["modelFallback.originalModelID"] = entry.modelID
+ fallbackEntry.metadata["modelFallback.reason"] = "requestedModelUnavailable"
+ let fallbackResult = await parseTaskIntent(
+ request,
+ entry: fallbackEntry,
+ startedAt: startedAt,
+ fallbackFromModelID: entry.modelID
+ )
+ var trace = fallbackResult.trace
+ trace.metadata["modelFallback.originalModelID"] = entry.modelID
+ trace.metadata["modelFallback.selectedModelID"] = fallbackModelID
+ trace.metadata["modelFallback.reason"] = "requestedModelUnavailable"
+ return TaskIntentAdapterResult(intent: fallbackResult.intent, trace: trace)
+ }
+
if response.statusCode == 429 {
- return result(entry: entry, request: request, status: .rateLimited, validationStatus: "notValidated", latencyMS: latencyMS)
+ return result(
+ entry: entry,
+ request: request,
+ status: .rateLimited,
+ validationStatus: "notValidated",
+ latencyMS: latencyMS,
+ metadata: httpMetadata(response: response, data: data, fallbackFromModelID: fallbackFromModelID)
+ )
}
if response.statusCode >= 500 {
- return result(entry: entry, request: request, status: .providerOutage, validationStatus: "notValidated", latencyMS: latencyMS)
+ return result(
+ entry: entry,
+ request: request,
+ status: .providerOutage,
+ validationStatus: "notValidated",
+ latencyMS: latencyMS,
+ metadata: httpMetadata(response: response, data: data, fallbackFromModelID: fallbackFromModelID)
+ )
}
guard (200..<300).contains(response.statusCode),
@@ -268,11 +361,19 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {
let intent = try TaskIntentWireCodec.decodeIntent(
outputText,
definitions: request.taskDefinitions,
+ originalCommand: request.command,
sourceModelCallID: "model-call-\(request.sourceTraceID)",
parserName: "ollama-task-intent-v1"
)
else {
- return result(entry: entry, request: request, status: .invalidOutput, validationStatus: "invalid", latencyMS: latencyMS)
+ return result(
+ entry: entry,
+ request: request,
+ status: (200..<300).contains(response.statusCode) ? .invalidOutput : .providerOutage,
+ validationStatus: (200..<300).contains(response.statusCode) ? "invalid" : "notValidated",
+ latencyMS: latencyMS,
+ metadata: httpMetadata(response: response, data: data, fallbackFromModelID: fallbackFromModelID)
+ )
}
return TaskIntentAdapterResult(
@@ -283,10 +384,13 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {
status: .completed,
validationStatus: "schemaDecoded",
latencyMS: latencyMS,
- metadata: [
- "http.status": String(response.statusCode),
+ metadata: httpMetadata(
+ response: response,
+ data: data,
+ fallbackFromModelID: fallbackFromModelID
+ ).merging([
"local.provider": "ollama"
- ]
+ ]) { current, _ in current }
)
)
} catch is CancellationError {
@@ -305,6 +409,87 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {
}
}
+ private func fallbackOllamaModelID(
+ for entry: AIModelRegistryEntry,
+ excluding excludedModelIDs: Set<String>
+ ) async throws -> String? {
+ var request = URLRequest(url: Self.ollamaAPIURL(for: entry.endpoint, path: "tags"))
+ request.httpMethod = "GET"
+ request.timeoutInterval = min(Double(entry.timeoutMS) / 1_000, 2)
+ let (data, response) = try await httpClient.send(request)
+ guard (200..<300).contains(response.statusCode) else {
+ return nil
+ }
+
+ let tags = try JSONDecoder().decode(OllamaTagsResponse.self, from: data)
+ return Self.preferredInstalledModelID(
+ from: tags.models,
+ excluding: excludedModelIDs
+ )
+ }
+
+ private static func ollamaAPIURL(for endpoint: URL, path: String) -> URL {
+ var components = URLComponents(url: endpoint, resolvingAgainstBaseURL: false)
+ components?.path = "/api/\(path)"
+ components?.query = nil
+ return components?.url ?? endpoint
+ }
+
+ private static func preferredInstalledModelID(
+ from models: [OllamaModelTag],
+ excluding excludedModelIDs: Set<String>
+ ) -> String? {
+ let candidates = models
+ .filter { model in
+ !model.name.isEmpty
+ && !excludedModelIDs.contains(model.name)
+ && !model.name.contains(":cloud")
+ && (model.size ?? 1) > 0
+ }
+ .map(\.name)
+
+ for prefix in fallbackModelPrefixes {
+ if let match = candidates.first(where: { $0 == prefix || $0.hasPrefix("\(prefix):") }) {
+ return match
+ }
+ }
+
+ return candidates.first
+ }
+
+ private static let fallbackModelPrefixes = [
+ "qwen3",
+ "qwen2.5",
+ "llama3.1",
+ "llama3",
+ "mistral",
+ "gemma3",
+ "gemma2"
+ ]
+
+ private func httpMetadata(
+ response: HTTPURLResponse,
+ data: Data,
+ fallbackFromModelID: String?
+ ) -> [String: String] {
+ var metadata = [
+ "http.status": String(response.statusCode),
+ "http.bodyPreview": Self.preview(data, maxCharacters: 240)
+ ]
+ if let fallbackFromModelID {
+ metadata["modelFallback.originalModelID"] = fallbackFromModelID
+ }
+ return metadata
+ }
+
+ private static func preview(_ data: Data, maxCharacters: Int) -> String {
+ let singleLine = String(decoding: data, as: UTF8.self)
+ .replacingOccurrences(of: "\n", with: "\\n")
+ .replacingOccurrences(of: "\r", with: "\\r")
+ guard singleLine.count > maxCharacters else { return singleLine }
+ return String(singleLine.prefix(maxCharacters))
+ }
+
private func makeURLRequest(
entry: AIModelRegistryEntry,
adapterRequest: TaskIntentAdapterRequest
@@ -330,7 +515,7 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {
),
"options": [
"num_ctx": 2048,
- "num_predict": 256,
+ "num_predict": Self.maxGeneratedTokens,
"temperature": 0,
"top_p": 0.8
],
@@ -382,16 +567,33 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {
.joined(separator: "\n")
return [
- "Classify the user's natural-language request into exactly one supported local app task intent, then return strict JSON.",
- "Choose by capability and target app, not by exact wording. The user should not need to remember command phrases.",
- "Do not include reasoning.",
- "Use only the provided task definitions. Do not invent task types, unsupported entities, or actions.",
+ "You are Donkey's local task-intent boundary. Return strict JSON only; do not include reasoning.",
+ "First decide whether Command is an executable local-app task or a conversation turn.",
+ "Executable local-app task means all three are clear: action, destination or target app/item, and enough payload to execute safely.",
+ "If Command is a question, conversation, malformed request, or lacks a real executable payload, do not invent one. Return the closest supported task with confidence below 0.55, needsConfirmation=false, metadata.responseMode=conversation, and metadata.assistantResponse with a brief natural-language reply.",
+ "If Command is an executable local task with one ordinary missing detail, set needsConfirmation=true and include missingEntity in metadata.",
+ "If Command is executable, choose by capability and target app, not exact wording. Use only provided task definitions; do not invent task types, unsupported entities, or actions.",
"If no capability fits, return the closest supported task with confidence below 0.55.",
- "If a required entity is missing, set needsConfirmation=true and include missingEntity in metadata.",
"For dynamic local-item capabilities, app/file/folder names may come from the request, relevant local cache, or default-app inference; the catalog will verify availability before execution.",
+ "For write/create document requests: if the requested content is malformed or not meaningful enough to type, choose conversation; do not fabricate a document payload just to make the task executable.",
"For local_app_interaction, select the most likely local app for the user's goal, set entities.goal, and when text must be entered set entities.query plus normalizedEntities.query.",
- "For local_app_interaction, fill actionPlan.tools with allowed tools only: app.openOrFocus, app.observe, ui.focusSearch, ui.setText, ui.pressReturn, app.verifyCommand, app.verifyVisibleText.",
+ "For local_app_interaction, fill actionPlan.tools with allowed tools only: app.openOrFocus, app.observe, ui.newDocument, ui.focusSearch, ui.focusAddressBar, ui.focusTextEntry, ui.setText, ui.pressReturn, app.verifyCommand, app.verifyVisibleText.",
+ "For website navigation, choose Safari or the user's browser, set query to the URL, use ui.focusAddressBar with controlID=addressBar and focusKey=Command+L, then ui.setText and ui.pressReturn.",
+ "For writing in Notes, choose Notes, create the requested prose in query, and use ui.newDocument followed by ui.setText.",
+ "For generative writing requests, query must be the complete final text to type, not a single category label, restatement of the request, or placeholder copied from these instructions.",
+ "If the writing type is clear but topic/details are sparse, compose a short generic piece that satisfies the requested writing type and put that complete text in query.",
+ "For spreadsheet or table creation, choose Numbers, put compact tab-separated table content in query, and use ui.newDocument followed by ui.setText. If exact live data is unavailable, make a table-shaped brief with a data-needed note; do not output a single sentence.",
+ "When ui.setText is present, entities.query and normalizedEntities.query must be non-empty.",
+ "If you cannot produce non-empty text for ui.setText, choose conversation; never return ui.setText with an empty query.",
+ "For sparse writing requests such as 'write a [form] in Notes', infer the requested form and write a short finished piece. If the requested object is malformed or nonsensical, choose conversation.",
+ "Example malformed writing boundary: 'write a people in Notes' is not a meaningful writing form or payload, so choose conversation rather than writing a definition.",
+ "entities.appName must be the human app name, such as Safari, Notes, Numbers, or Music; do not put a bundle identifier in appName.",
"For local_app_interaction, set actionPlan.inputEntity to query when ui.setText should type the query, and set actionPlan.controlID/focusKey for the UI control strategy.",
+ "The examples below show output structure only. Replace every example entity value with values inferred from Command and local cache; do not copy example query text unless the user asked for that exact text.",
+ "Example website output shape: {\"taskType\":\"local_app_interaction\",\"targetAppName\":\"Safari\",\"entities\":{\"appName\":\"Safari\",\"goal\":\"open requested website\",\"query\":\"https://example.org\"},\"normalizedEntities\":{\"appName\":\"Safari\",\"goal\":\"open requested website\",\"query\":\"https://example.org\"},\"confidence\":0.9,\"needsConfirmation\":false,\"actionPlan\":{\"tools\":[\"app.openOrFocus\",\"app.observe\",\"ui.focusAddressBar\",\"ui.setText\",\"ui.pressReturn\",\"app.verifyCommand\"],\"inputEntity\":\"query\",\"controlID\":\"addressBar\",\"focusKey\":\"Command+L\",\"verification\":\"commandAttempted\"},\"metadata\":{}}",
+ "Writing output shape: targetAppName=Notes, entities.appName=Notes, entities.goal=write requested text, entities.query=<the actual final text to type>, actionPlan.tools=[app.openOrFocus, app.observe, ui.newDocument, ui.setText, app.verifyCommand], inputEntity=query, controlID=editor.",
+ "Table output shape: targetAppName=Numbers, entities.appName=Numbers, entities.goal=create requested table, entities.query=<tab-separated rows for the requested table>, actionPlan.tools=[app.openOrFocus, app.observe, ui.newDocument, ui.setText, app.verifyCommand], inputEntity=query, controlID=editor.",
+ "Example malformed request output shape: {\"taskType\":\"local_app_interaction\",\"targetAppName\":\"Notes\",\"entities\":{\"appName\":\"Notes\",\"goal\":\"unclear local writing request\"},\"normalizedEntities\":{\"appName\":\"Notes\",\"goal\":\"unclear local writing request\"},\"confidence\":0.2,\"needsConfirmation\":false,\"actionPlan\":{\"tools\":[],\"inputEntity\":\"query\",\"controlID\":\"\",\"focusKey\":\"\",\"verification\":\"commandAttempted\"},\"metadata\":{\"responseMode\":\"conversation\",\"assistantResponse\":\"I can help, but I need a clearer thing to write before opening an app.\"}}",
"For every other task type, actionPlan.tools must be empty.",
"For AppleScript-backed capabilities, include compact appleScript.source or appleScript.template metadata only when the provided action is insufficient; prefer task metadata and normalized entities for speed.",
"Command: \(request.command)",
@@ -403,6 +605,8 @@ public struct OllamaTaskIntentAdapter: TaskIntentParsingAdapter {
.joined(separator: "\n")
}
+ private static let maxGeneratedTokens = 512
+
private func result(
entry: AIModelRegistryEntry?,
request: TaskIntentAdapterRequest,
@@ -471,7 +675,24 @@ public struct FallbackTaskIntentParsingAdapter: TaskIntentParsingAdapter {
let fallbackResult = await fallback.parseTaskIntent(request)
guard fallbackResult.intent != nil else {
- return primaryResult
+ 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
@@ -513,13 +734,33 @@ public struct LocalModelTaskIntentResolver: Sendable {
)
guard let intent = result.intent else {
+ var metadata = [
+ "reason": "localModelIntentUnavailable",
+ "modelCallStatus": result.trace.status.rawValue,
+ "modelValidationStatus": result.trace.validationStatus
+ ]
+ for key in [
+ "reason",
+ "detail",
+ "http.status",
+ "http.bodyPreview",
+ "modelOutput.empty",
+ "modelOutput.preview",
+ "fallback.status",
+ "fallback.validation",
+ "fallback.reason",
+ "fallback.http.status",
+ "fallback.http.bodyPreview",
+ "fallback.modelFallback.selectedModelID"
+ ] {
+ if let value = result.trace.metadata[key], !value.isEmpty {
+ metadata["model.\(key)"] = value
+ }
+ }
return (
LocalAppTaskCatalogResolution(
status: .needsConfirmation,
- metadata: [
- "reason": "localModelIntentUnavailable",
- "modelCallStatus": result.trace.status.rawValue
- ]
+ metadata: metadata
),
result.trace
)
@@ -533,6 +774,15 @@ private struct OllamaTaskIntentResponse: Decodable {
var response: String?
}
+private struct OllamaTagsResponse: Decodable {
+ var models: [OllamaModelTag]
+}
+
+private struct OllamaModelTag: Decodable {
+ var name: String
+ var size: Int64?
+}
+
private enum TaskIntentWireCodec {
static func jsonSchema(taskDefinitions: [LocalAppTaskDefinition]) -> [String: Any] {
let allowsDynamicTargets = taskDefinitions.contains { definition in
@@ -608,11 +858,11 @@ private enum TaskIntentWireCodec {
static func decodeIntent(
_ outputText: String,
definitions: [LocalAppTaskDefinition],
+ originalCommand: String,
sourceModelCallID: String,
parserName: String
) throws -> TaskIntent? {
- let data = Data(outputText.utf8)
- let wire = try JSONDecoder().decode(TaskIntentWire.self, from: data)
+ let wire = try decodeWire(from: outputText)
let exactDefinition = definitions.first(where: {
$0.taskType == wire.taskType && $0.targetApp.appName == wire.targetAppName
})
@@ -630,9 +880,9 @@ private enum TaskIntentWireCodec {
var normalizedEntities = normalizedEntities(from: wire, definition: definition)
if definition.metadata["dynamicTarget"] == "true",
normalizedEntities["appName"] == nil,
- wire.targetAppName != definition.targetApp.appName {
- entities["appName"] = wire.targetAppName
- normalizedEntities["appName"] = wire.targetAppName
+ let appName = dynamicAppName(from: wire, definition: definition) {
+ entities["appName"] = appName
+ normalizedEntities["appName"] = appName
}
let missingRequiredEntity = definition.entityRules.first { rule in
rule.required && normalizedEntities[rule.name] == nil
@@ -646,8 +896,44 @@ private enum TaskIntentWireCodec {
metadata["missingEntity"] = missingRequiredEntity.name
}
- let needsConfirmation = wire.needsConfirmation || missingRequiredEntity != nil
- let actionPlan = wire.actionPlan.tools.isEmpty ? nil : wire.actionPlan
+ var confidence = wire.confidence
+ var needsConfirmation = wire.needsConfirmation || missingRequiredEntity != nil
+ var actionPlan = wire.actionPlan.tools.isEmpty ? nil : wire.actionPlan
+ if definition.metadata["modelPlanned"] == "true",
+ let modelActionPlan = actionPlan {
+ let repairedPlan = repairedModelActionPlan(
+ modelActionPlan,
+ normalizedEntities: normalizedEntities
+ )
+ if repairedPlan != modelActionPlan {
+ metadata["modelPlan.repaired"] = "true"
+ actionPlan = repairedPlan
+ }
+ }
+ if let tableRepair = repairedSpreadsheetQueryIfNeeded(
+ actionPlan: actionPlan,
+ normalizedEntities: normalizedEntities,
+ wire: wire
+ ) {
+ entities[tableRepair.entityName] = tableRepair.text
+ normalizedEntities[tableRepair.entityName] = tableRepair.text
+ metadata["modelPlan.repairedTableText"] = "true"
+ }
+ if let conversationReason = textInputConversationReason(
+ actionPlan: actionPlan,
+ normalizedEntities: normalizedEntities
+ ) ?? documentConversationReason(
+ actionPlan: actionPlan,
+ normalizedEntities: normalizedEntities,
+ originalCommand: originalCommand
+ ) {
+ confidence = min(confidence, 0.2)
+ needsConfirmation = false
+ actionPlan = nil
+ metadata["responseMode"] = "conversation"
+ metadata["assistantResponse"] = "I can help, but I need a clearer thing to write before opening an app."
+ metadata["notActionableReason"] = conversationReason
+ }
let primaryEntity = definition.verificationEntityName
.flatMap { normalizedEntities[$0] }
?? normalizedEntities.values.sorted().first
@@ -661,7 +947,7 @@ private enum TaskIntentWireCodec {
targetApp: targetApp(from: wire, definition: definition),
entities: entities,
normalizedEntities: normalizedEntities,
- confidence: wire.confidence,
+ confidence: confidence,
parserSource: .localModel,
needsConfirmation: needsConfirmation,
sourceModelCallID: sourceModelCallID,
@@ -670,6 +956,69 @@ private enum TaskIntentWireCodec {
)
}
+ private static func decodeWire(from outputText: String) throws -> TaskIntentWire {
+ var lastError: Error?
+ for candidate in jsonObjectCandidates(in: outputText) {
+ do {
+ return try JSONDecoder().decode(TaskIntentWire.self, from: Data(candidate.utf8))
+ } catch {
+ lastError = error
+ }
+ }
+
+ if let lastError {
+ throw lastError
+ }
+ throw DecodingError.dataCorrupted(
+ DecodingError.Context(
+ codingPath: [],
+ debugDescription: "No JSON object found in task intent model output"
+ )
+ )
+ }
+
+ private static func jsonObjectCandidates(in outputText: String) -> [String] {
+ let trimmed = outputText.trimmingCharacters(in: .whitespacesAndNewlines)
+ var candidates: [String] = trimmed.isEmpty ? [] : [trimmed]
+ var objectStart: String.Index?
+ var depth = 0
+ var isInsideString = false
+ var isEscaped = false
+ var index = outputText.startIndex
+
+ while index < outputText.endIndex {
+ let character = outputText[index]
+ if isInsideString {
+ if isEscaped {
+ isEscaped = false
+ } else if character == "\\" {
+ isEscaped = true
+ } else if character == "\"" {
+ isInsideString = false
+ }
+ } else if character == "\"" {
+ isInsideString = true
+ } else if character == "{" {
+ if depth == 0 {
+ objectStart = index
+ }
+ depth += 1
+ } else if character == "}", depth > 0 {
+ depth -= 1
+ if depth == 0, let start = objectStart {
+ let objectEnd = outputText.index(after: index)
+ candidates.append(String(outputText[start..<objectEnd]))
+ objectStart = nil
+ }
+ }
+
+ index = outputText.index(after: index)
+ }
+
+ var seen = Set<String>()
+ return candidates.filter { seen.insert($0).inserted }
+ }
+
private static func normalizedEntities(
from wire: TaskIntentWire,
definition: LocalAppTaskDefinition
@@ -684,6 +1033,233 @@ private enum TaskIntentWireCodec {
return normalized
}
+ private static func dynamicAppName(
+ from wire: TaskIntentWire,
+ definition: LocalAppTaskDefinition
+ ) -> String? {
+ let entityAppName = wire.normalizedEntities["appName"] ?? wire.entities["appName"]
+ if let entityAppName,
+ !entityAppName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ return entityAppName
+ }
+
+ guard wire.targetAppName != definition.targetApp.appName else { return nil }
+ return wire.targetAppName
+ }
+
+ private static func repairedModelActionPlan(
+ _ actionPlan: LocalAppActionPlan,
+ normalizedEntities: [String: String]
+ ) -> LocalAppActionPlan {
+ var plan = actionPlan
+ if plan.inputEntity.isEmpty {
+ plan.inputEntity = "query"
+ }
+ if plan.controlID.isEmpty {
+ plan.controlID = defaultControlID(for: plan.tools)
+ }
+ if plan.focusKey.isEmpty {
+ plan.focusKey = defaultFocusKey(for: plan.tools)
+ }
+
+ let inputValue = normalizedEntities[plan.inputEntity] ?? normalizedEntities["query"] ?? ""
+ guard !plan.isExecutable,
+ !inputValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ else {
+ return plan
+ }
+
+ if plan.tools.contains(.newDocument) || plan.tools.contains(.focusTextEntry) {
+ return LocalAppActionPlan(
+ tools: repairedTools(
+ from: plan.tools,
+ appending: [.setText, .verifyCommand]
+ ),
+ inputEntity: plan.inputEntity,
+ controlID: plan.controlID,
+ focusKey: plan.focusKey,
+ verification: plan.verification
+ )
+ }
+
+ if plan.tools.contains(.focusAddressBar) {
+ return LocalAppActionPlan(
+ tools: repairedTools(
+ from: plan.tools,
+ appending: [.setText, .pressReturn, .verifyCommand]
+ ),
+ inputEntity: plan.inputEntity,
+ controlID: plan.controlID,
+ focusKey: plan.focusKey,
+ verification: plan.verification
+ )
+ }
+
+ return LocalAppActionPlan(
+ tools: LocalAppActionPlan.defaultSearchSubmitPlan.tools,
+ inputEntity: plan.inputEntity,
+ controlID: plan.controlID,
+ focusKey: plan.focusKey,
+ verification: plan.verification
+ )
+ }
+
+ private static func defaultControlID(for tools: [LocalAppActionPlanTool]) -> String {
+ if tools.contains(.focusAddressBar) {
+ return "addressBar"
+ }
+ if tools.contains(.focusTextEntry) || tools.contains(.newDocument) {
+ return "editor"
+ }
+ return "search"
+ }
+
+ private static func defaultFocusKey(for tools: [LocalAppActionPlanTool]) -> String {
+ if tools.contains(.focusAddressBar) {
+ return "Command+L"
+ }
+ if tools.contains(.focusTextEntry) || tools.contains(.newDocument) {
+ return ""
+ }
+ return "Command+F"
+ }
+
+ private static func repairedTools(
+ from tools: [LocalAppActionPlanTool],
+ appending repairTools: [LocalAppActionPlanTool]
+ ) -> [LocalAppActionPlanTool] {
+ var repaired = tools
+ for tool in repairTools where !repaired.contains(tool) {
+ repaired.append(tool)
+ }
+ return repaired
+ }
+
+ private static func repairedSpreadsheetQueryIfNeeded(
+ actionPlan: LocalAppActionPlan?,
+ normalizedEntities: [String: String],
+ wire: TaskIntentWire
+ ) -> (entityName: String, text: String)? {
+ guard let actionPlan,
+ actionPlan.tools.contains(.newDocument),
+ actionPlan.tools.contains(.setText)
+ else {
+ return nil
+ }
+
+ let appName = normalizedEntities["appName"] ?? wire.entities["appName"] ?? wire.targetAppName
+ guard LocalAppTaskIntentParser.normalizedPhrase(appName) == "numbers" else {
+ return nil
+ }
+
+ let entityName = actionPlan.inputEntity.isEmpty ? "query" : actionPlan.inputEntity
+ let query = (normalizedEntities[entityName] ?? normalizedEntities["query"] ?? "")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !query.isEmpty,
+ !query.contains("\n"),
+ !query.contains("\t")
+ else {
+ return nil
+ }
+
+ let subject = query
+ .replacingOccurrences(of: "\n", with: " ")
+ .replacingOccurrences(of: "\t", with: " ")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !subject.isEmpty else { return nil }
+
+ let clippedSubject = String(subject.prefix(160))
+ return (
+ entityName,
+ "Request\tStatus\n\(clippedSubject)\tNeeds table data"
+ )
+ }
+
+ private static func textInputConversationReason(
+ actionPlan: LocalAppActionPlan?,
+ normalizedEntities: [String: String]
+ ) -> String? {
+ guard let actionPlan,
+ actionPlan.requiresTextInput
+ else {
+ return nil
+ }
+
+ let entityName = actionPlan.inputEntity.isEmpty ? "query" : actionPlan.inputEntity
+ let query = (normalizedEntities[entityName] ?? normalizedEntities["query"] ?? "")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ if query.isEmpty {
+ return "missingTextPayload"
+ }
+ if isCopiedPromptPlaceholder(query) {
+ return "promptPlaceholderPayload"
+ }
+
+ return nil
+ }
+
+ private static func documentConversationReason(
+ actionPlan: LocalAppActionPlan?,
+ normalizedEntities: [String: String],
+ originalCommand: String
+ ) -> String? {
+ guard let actionPlan,
+ actionPlan.tools.contains(.newDocument),
+ actionPlan.tools.contains(.setText),
+ !actionPlan.tools.contains(.pressReturn)
+ else {
+ return nil
+ }
+
+ let entityName = actionPlan.inputEntity.isEmpty ? "query" : actionPlan.inputEntity
+ let query = (normalizedEntities[entityName] ?? normalizedEntities["query"] ?? "")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !query.isEmpty,
+ !commandContainsQuoted(query, originalCommand: originalCommand),
+ !query.contains("\n"),
+ !query.contains("\t"),
+ query.rangeOfCharacter(from: CharacterSet(charactersIn: ".?!:;,")) == nil
+ else {
+ return nil
+ }
+
+ let words = LocalAppTaskIntentParser.normalizedPhrase(query)
+ .split(separator: " ")
+ return words.count <= 5 ? "insufficientDocumentPayload" : nil
+ }
+
+ private static func isCopiedPromptPlaceholder(_ query: String) -> Bool {
+ let normalizedQuery = LocalAppTaskIntentParser.normalizedPhrase(query)
+ guard !normalizedQuery.isEmpty else { return false }
+
+ return copiedPromptPayloadPhrases.contains { phrase in
+ normalizedQuery.contains(LocalAppTaskIntentParser.normalizedPhrase(phrase))
+ }
+ }
+
+ private static let copiedPromptPayloadPhrases = [
+ "complete piece of text generated for the user writing request",
+ "complete piece of text generated for the user's writing request",
+ "generated for the user writing request",
+ "the actual final text to type",
+ "tab separated rows for the requested table",
+ "column a column b row label value or data needed note"
+ ]
+
+ private static func commandContainsQuoted(
+ _ query: String,
+ originalCommand: String
+ ) -> Bool {
+ let trimmedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmedQuery.isEmpty else { return false }
+ let quotedPatterns = [
+ "\"\(trimmedQuery)\"",
+ "'\(trimmedQuery)'",
+ "`\(trimmedQuery)`"
+ ]
+ return quotedPatterns.contains { originalCommand.localizedCaseInsensitiveContains($0) }
+ }
+
private static func targetApp(
from wire: TaskIntentWire,
definition: LocalAppTaskDefinition
diff --git a/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift b/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift
index 5eedeeea..1bf59221 100644
--- a/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift
+++ b/apps/Donkey/Sources/DonkeyContracts/TaskIntentContracts.swift
@@ -28,7 +28,10 @@ public struct LocalAppTarget: Codable, Equatable, Sendable {
public enum LocalAppActionPlanTool: String, Codable, CaseIterable, Equatable, Sendable {
case openOrFocusApp = "app.openOrFocus"
case observeApp = "app.observe"
+ case newDocument = "ui.newDocument"
case focusSearch = "ui.focusSearch"
+ case focusAddressBar = "ui.focusAddressBar"
+ case focusTextEntry = "ui.focusTextEntry"
case setText = "ui.setText"
case pressReturn = "ui.pressReturn"
case verifyCommand = "app.verifyCommand"
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
index a404ea36..effabb5e 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
@@ -651,15 +651,26 @@ public struct LocalAppTaskCatalog: Sendable {
public func resolve(intent: TaskIntent) -> LocalAppTaskCatalogResolution {
if intent.parserSource != .deterministic,
intent.confidence < Self.minimumModelIntentConfidence {
+ var metadata = [
+ "reason": "lowConfidenceIntent",
+ "taskType": intent.taskType,
+ "targetApp": intent.targetApp.appName,
+ "intentConfidence": String(intent.confidence)
+ ]
+ for key in [
+ "responseMode",
+ "assistantResponse",
+ "missingEntity",
+ "notActionableReason"
+ ] {
+ if let value = intent.metadata[key], !value.isEmpty {
+ metadata[key] = value
+ }
+ }
return LocalAppTaskCatalogResolution(
status: .needsConfirmation,
intent: intent,
- metadata: [
- "reason": "lowConfidenceIntent",
- "taskType": intent.taskType,
- "targetApp": intent.targetApp.appName,
- "intentConfidence": String(intent.confidence)
- ]
+ metadata: metadata
)
}
@@ -1000,17 +1011,30 @@ public struct LocalAppTaskCatalog: Sendable {
switch tool {
case .openOrFocusApp, .observeApp:
continue
- case .focusSearch:
+ case .newDocument:
steps.append(LocalAppTaskWorkflowStepDefinition(
- id: "model-plan-focus-search",
- role: .focusControl,
- summary: "Focus the model-selected search control",
+ id: "model-plan-new-document",
+ role: .submit,
+ summary: "Create a new document or note",
metadata: [
- "controlID": plan.controlID,
- "key": plan.focusKey,
+ "key": "Command+N",
"plan.tool": tool.rawValue
]
))
+ case .focusSearch, .focusAddressBar, .focusTextEntry:
+ var metadata = [
+ "controlID": plan.controlID,
+ "plan.tool": tool.rawValue
+ ]
+ if !plan.focusKey.isEmpty {
+ metadata["key"] = plan.focusKey
+ }
+ steps.append(LocalAppTaskWorkflowStepDefinition(
+ id: "model-plan-\(Self.toolSlug(tool.rawValue))",
+ role: .focusControl,
+ summary: "Focus the model-selected input control",
+ metadata: metadata
+ ))
case .setText:
steps.append(LocalAppTaskWorkflowStepDefinition(
id: "model-plan-set-text",
@@ -1052,6 +1076,13 @@ public struct LocalAppTaskCatalog: Sendable {
return steps
}
+ private static func toolSlug(_ value: String) -> String {
+ value
+ .split(whereSeparator: { !$0.isLetter && !$0.isNumber })
+ .joined(separator: "-")
+ .lowercased()
+ }
+
private static func entityValue(named entityName: String, in intent: TaskIntent) -> String {
(intent.normalizedEntities[entityName] ?? intent.entities[entityName] ?? "")
.trimmingCharacters(in: .whitespacesAndNewlines)
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
index 06a8afa3..ea83fe6f 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
@@ -83,7 +83,7 @@ struct AIHarnessAdapterTests {
#expect(selected.role == .taskIntent)
#expect(selected.provider == .localRuntime)
#expect(selected.modelID == "qwen3:8b")
- #expect(selected.timeoutMS == 4_000)
+ #expect(selected.timeoutMS == 20_000)
}
@Test
@@ -373,15 +373,81 @@ struct AIHarnessAdapterTests {
#expect(body["format"] as? [String: Any] != nil)
#expect(body["keep_alive"] as? String == "10m")
let options = try #require(body["options"] as? [String: Any])
- #expect(options["num_predict"] as? Int == 256)
+ #expect(options["num_predict"] as? Int == 512)
#expect(options["num_ctx"] as? Int == 2048)
#expect((body["prompt"] as? String)?.contains("Use only the provided task definitions") == true)
- #expect((body["prompt"] as? String)?.contains("Choose by capability and target app") == true)
+ #expect((body["prompt"] as? String)?.contains("choose by capability and target app") == true)
#expect((body["prompt"] as? String)?.contains("Do not include reasoning") == true)
+ #expect((body["prompt"] as? String)?.contains("For website navigation") == true)
+ #expect((body["prompt"] as? String)?.contains("ui.newDocument") == true)
+ #expect((body["prompt"] as? String)?.contains("action, destination or target app/item") == true)
+ #expect((body["prompt"] as? String)?.contains("metadata.responseMode=conversation") == true)
#expect((body["prompt"] as? String)?.contains("triggers=") == false)
#expect((body["prompt"] as? String)?.contains("metadata=") == false)
}
+ @Test
+ func ollamaTaskIntentAdapterUsesInstalledLocalModelWhenConfiguredModelIsMissing() async throws {
+ let httpClient = SequencedFakeAIHTTPClient(
+ responses: [
+ HTTPStub(
+ data: Data(#"{"error":"model 'qwen3:8b' not found"}"#.utf8),
+ statusCode: 404
+ ),
+ HTTPStub(
+ data: Data(#"{"models":[{"name":"kimi-k2.5:cloud","size":0},{"name":"llama3:latest","size":4700000000}]}"#.utf8),
+ statusCode: 200
+ ),
+ HTTPStub(
+ data: ollamaResponseData(
+ response: """
+ {"taskType":"local_app_interaction","targetAppName":"Music","entities":{"appName":"Music","goal":"play media","query":"justin bieber"},"normalizedEntities":{"appName":"Music","goal":"play media","query":"Justin Bieber"},"confidence":0.91,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.focusSearch","ui.setText","ui.pressReturn","app.verifyCommand"],"inputEntity":"query","controlID":"search","focusKey":"Command+F","verification":"commandAttempted"},"metadata":{}}
+ """
+ ),
+ statusCode: 200
+ )
+ ]
+ )
+ let adapter = OllamaTaskIntentAdapter(
+ router: AIModelRouter(
+ registry: AIModelRegistry(
+ entries: [
+ entry(
+ id: "local-intent",
+ role: .taskIntent,
+ provider: .ollama,
+ modelID: "qwen3:8b",
+ endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,
+ promptVersion: "task-intent-v1"
+ )
+ ]
+ )
+ ),
+ httpClient: httpClient
+ )
+
+ let result = await adapter.parseTaskIntent(
+ TaskIntentAdapterRequest(
+ command: "play some justin bieber",
+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
+ contextSnippets: ["Music application com.apple.Music"],
+ sourceTraceID: "trace-ollama-model-fallback"
+ )
+ )
+
+ #expect(result.intent?.taskType == "local_app_interaction")
+ #expect(result.intent?.targetApp.appName == "Music")
+ #expect(result.intent?.normalizedEntities["query"] == "Justin Bieber")
+ #expect(result.trace.status == .completed)
+ #expect(result.trace.modelID == "llama3:latest")
+ #expect(result.trace.metadata["modelFallback.originalModelID"] == "qwen3:8b")
+ #expect(result.trace.metadata["modelFallback.selectedModelID"] == "llama3:latest")
+ #expect(httpClient.requests.map { $0.url?.path } == ["/api/generate", "/api/tags", "/api/generate"])
+ let fallbackRequest = try #require(httpClient.requests.last)
+ let fallbackBody = try #require(fallbackRequest.httpBodyJSONObject)
+ #expect(fallbackBody["model"] as? String == "llama3:latest")
+ }
+
@Test
func processBackedLocalLLMTaskIntentAdapterDecodesValidatedIntent() async throws {
let adapter = ProcessBackedLocalLLMTaskIntentAdapter(
@@ -448,6 +514,194 @@ struct AIHarnessAdapterTests {
#expect(result.trace.status == .completed)
}
+ @Test
+ func processBackedLocalLLMTaskIntentAdapterDecodesWrappedStructuredOutput() async throws {
+ let adapter = ProcessBackedLocalLLMTaskIntentAdapter(
+ router: AIModelRouter(registry: .defaultHybridPlanner),
+ sidecarRunner: FakeSidecarRunner(
+ result: LocalJSONSidecarResult(
+ status: .completed,
+ outputData: try localLLMSidecarOutputData(
+ outputText: """
+ <think>I should choose the generic app interaction.</think>
+ ```json
+ {"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"]
+ ),
+ latencyMS: 14,
+ metadata: ["sidecar.role": "taskIntent"]
+ )
+ )
+ )
+
+ let result = await adapter.parseTaskIntent(
+ TaskIntentAdapterRequest(
+ command: "play some justin bieber",
+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
+ contextSnippets: ["Music application com.apple.Music"],
+ sourceTraceID: "trace-wrapped-local-app-plan"
+ )
+ )
+
+ #expect(result.intent?.taskType == "local_app_interaction")
+ #expect(result.intent?.targetApp.appName == "Music")
+ #expect(result.intent?.normalizedEntities["query"] == "Justin Bieber")
+ #expect(result.trace.status == .completed)
+ }
+
+ @Test
+ func processBackedLocalLLMTaskIntentAdapterMapsEmptySidecarFailureToProviderOutage() async throws {
+ let adapter = ProcessBackedLocalLLMTaskIntentAdapter(
+ router: AIModelRouter(registry: .defaultHybridPlanner),
+ sidecarRunner: FakeSidecarRunner(
+ result: LocalJSONSidecarResult(
+ status: .completed,
+ outputData: try localLLMSidecarOutputData(
+ outputText: "",
+ metadata: [
+ "reason": "localLLMGenerationFailed",
+ "detail": "ollama HTTP 404: model 'qwen3:8b' not found"
+ ]
+ ),
+ latencyMS: 14,
+ metadata: ["sidecar.role": "taskIntent"]
+ )
+ )
+ )
+
+ let result = await adapter.parseTaskIntent(
+ TaskIntentAdapterRequest(
+ command: "play some justin bieber",
+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
+ sourceTraceID: "trace-empty-sidecar"
+ )
+ )
+
+ #expect(result.intent == nil)
+ #expect(result.trace.status == .providerOutage)
+ #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)
+ }
+
+ @Test
+ func processBackedLocalLLMTaskIntentAdapterRepairsIncompleteModelPlannedInteraction() async throws {
+ let adapter = ProcessBackedLocalLLMTaskIntentAdapter(
+ router: AIModelRouter(registry: .defaultHybridPlanner),
+ sidecarRunner: FakeSidecarRunner(
+ result: LocalJSONSidecarResult(
+ status: .completed,
+ outputData: try localLLMSidecarOutputData(
+ outputText: """
+ {"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"
+ ]
+ ),
+ latencyMS: 14,
+ metadata: ["sidecar.role": "taskIntent"]
+ )
+ )
+ )
+
+ let result = await adapter.parseTaskIntent(
+ TaskIntentAdapterRequest(
+ command: "play some justin bieber",
+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
+ contextSnippets: ["Music application com.apple.Music"],
+ sourceTraceID: "trace-repaired-local-app-plan"
+ )
+ )
+
+ #expect(result.intent?.taskType == "local_app_interaction")
+ #expect(result.intent?.normalizedEntities["appName"] == "Music")
+ #expect(result.intent?.normalizedEntities["query"] == "Justin Bieber")
+ #expect(result.intent?.metadata["modelPlan.repaired"] == "true")
+ #expect(result.intent?.actionPlan?.tools.contains(.setText) == true)
+ #expect(result.intent?.actionPlan?.tools.contains(.pressReturn) == true)
+ #expect(result.intent?.actionPlan?.controlID == "search")
+ #expect(result.intent?.actionPlan?.focusKey == "Command+F")
+ #expect(result.trace.status == .completed)
+ }
+
+ @Test
+ func processBackedLocalLLMTaskIntentAdapterDecodesRepresentativeAppCommands() async throws {
+ let examples: [(command: String, outputText: String, appName: String, requiredTools: [LocalAppActionPlanTool], queryContains: String)] = [
+ (
+ command: "go to cnn.com",
+ outputText: """
+ {"taskType":"local_app_interaction","targetAppName":"Safari","entities":{"appName":"Safari","goal":"open website","query":"https://cnn.com"},"normalizedEntities":{"appName":"Safari","goal":"open website","query":"https://cnn.com"},"confidence":0.94,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.focusAddressBar","ui.setText","ui.pressReturn","app.verifyCommand"],"inputEntity":"query","controlID":"addressBar","focusKey":"Command+L","verification":"commandAttempted"},"metadata":{}}
+ """,
+ appName: "Safari",
+ requiredTools: [.focusAddressBar, .setText, .pressReturn],
+ queryContains: "cnn.com"
+ ),
+ (
+ command: "write poem in notes",
+ outputText: """
+ {"taskType":"local_app_interaction","targetAppName":"Notes","entities":{"appName":"Notes","goal":"write a poem","query":"Morning light spills softly across the page,\\nA quiet thought wakes up and learns to sing."},"normalizedEntities":{"appName":"Notes","goal":"write a poem","query":"Morning light spills softly across the page,\\nA quiet thought wakes up and learns to sing."},"confidence":0.9,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.newDocument","ui.setText","app.verifyCommand"],"inputEntity":"query","controlID":"editor","focusKey":"","verification":"commandAttempted"},"metadata":{}}
+ """,
+ appName: "Notes",
+ requiredTools: [.newDocument, .setText],
+ queryContains: "Morning light"
+ ),
+ (
+ command: "create a table in numbers with the marketcap of the 10 largest companies in s&p",
+ outputText: """
+ {"taskType":"local_app_interaction","targetAppName":"Numbers","entities":{"appName":"Numbers","goal":"create spreadsheet table","query":"Company\\tMarket Cap\\nLargest S&P 500 companies\\tNeeds current market-cap data"},"normalizedEntities":{"appName":"Numbers","goal":"create spreadsheet table","query":"Company\\tMarket Cap\\nLargest S&P 500 companies\\tNeeds current market-cap data"},"confidence":0.86,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.newDocument","ui.setText","app.verifyCommand"],"inputEntity":"query","controlID":"editor","focusKey":"","verification":"commandAttempted"},"metadata":{}}
+ """,
+ appName: "Numbers",
+ requiredTools: [.newDocument, .setText],
+ queryContains: "Market Cap"
+ )
+ ]
+
+ for example in examples {
+ let adapter = ProcessBackedLocalLLMTaskIntentAdapter(
+ router: AIModelRouter(registry: .defaultHybridPlanner),
+ sidecarRunner: FakeSidecarRunner(
+ result: LocalJSONSidecarResult(
+ status: .completed,
+ outputData: try localLLMSidecarOutputData(
+ outputText: example.outputText,
+ metadata: ["local.provider": "ollama-sidecar"]
+ ),
+ latencyMS: 14,
+ metadata: ["sidecar.role": "taskIntent"]
+ )
+ )
+ )
+
+ let result = await adapter.parseTaskIntent(
+ TaskIntentAdapterRequest(
+ command: example.command,
+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
+ contextSnippets: [
+ "Safari application com.apple.Safari",
+ "Notes application com.apple.Notes",
+ "Numbers application com.apple.iWork.Numbers"
+ ],
+ sourceTraceID: "trace-\(slug(example.appName))"
+ )
+ )
+
+ let intent = try #require(result.intent)
+ let actionPlan = try #require(intent.actionPlan)
+ #expect(intent.taskType == "local_app_interaction")
+ #expect(intent.normalizedEntities["appName"] == example.appName)
+ #expect(intent.normalizedEntities["query"]?.contains(example.queryContains) == true)
+ for tool in example.requiredTools {
+ #expect(actionPlan.tools.contains(tool), "Expected \(example.command) to include \(tool.rawValue)")
+ }
+ #expect(result.trace.status == .completed)
+ }
+ }
+
@Test
func localModelTaskIntentResolverValidatesAgainstCatalogAvailability() async {
let httpClient = FakeAIHTTPClient(
@@ -629,6 +883,221 @@ struct AIHarnessAdapterTests {
#expect(result.resolution.metadata["reason"] == "city")
}
+ @Test
+ func localModelTaskIntentResolverPreservesConversationResponseForMalformedTask() async {
+ let httpClient = FakeAIHTTPClient(
+ data: ollamaResponseData(
+ response: """
+ {"taskType":"local_app_interaction","targetAppName":"Notes","entities":{"appName":"Notes","goal":"unclear writing request"},"normalizedEntities":{"appName":"Notes","goal":"unclear writing request"},"confidence":0.2,"needsConfirmation":false,"actionPlan":{"tools":[],"inputEntity":"query","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{"responseMode":"conversation","assistantResponse":"I can help with that, but I need a clearer thing to write before opening Notes."}}
+ """
+ ),
+ statusCode: 200
+ )
+ let resolver = LocalModelTaskIntentResolver(
+ catalog: LocalAppTaskCatalog(
+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
+ availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.Notes"])
+ ),
+ adapter: OllamaTaskIntentAdapter(
+ router: AIModelRouter(
+ registry: AIModelRegistry(
+ entries: [
+ entry(
+ id: "local-intent",
+ role: .taskIntent,
+ provider: .ollama,
+ modelID: "qwen3:8b",
+ endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,
+ promptVersion: "task-intent-v1"
+ )
+ ]
+ )
+ ),
+ httpClient: httpClient
+ )
+ )
+
+ let result = await resolver.resolve(
+ command: "write a people in notes",
+ sourceTraceID: "trace-malformed-writing"
+ )
+
+ #expect(result.resolution.status == .needsConfirmation)
+ #expect(result.resolution.metadata["reason"] == "lowConfidenceIntent")
+ #expect(result.resolution.metadata["responseMode"] == "conversation")
+ #expect(result.resolution.metadata["assistantResponse"]?.contains("clearer thing to write") == true)
+ }
+
+ @Test
+ func taskIntentDecoderRoutesShortUnquotedDocumentPayloadToConversation() async throws {
+ let adapter = ProcessBackedLocalLLMTaskIntentAdapter(
+ router: AIModelRouter(registry: .defaultHybridPlanner),
+ sidecarRunner: FakeSidecarRunner(
+ result: LocalJSONSidecarResult(
+ status: .completed,
+ outputData: try localLLMSidecarOutputData(
+ 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"]
+ ),
+ latencyMS: 14,
+ metadata: ["sidecar.role": "taskIntent"]
+ )
+ )
+ )
+
+ let result = await adapter.parseTaskIntent(
+ TaskIntentAdapterRequest(
+ command: "write a people in notes",
+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
+ contextSnippets: ["Notes application com.apple.Notes"],
+ sourceTraceID: "trace-short-document-payload"
+ )
+ )
+
+ #expect(result.intent?.confidence == 0.2)
+ #expect(result.intent?.actionPlan == nil)
+ #expect(result.intent?.metadata["responseMode"] == "conversation")
+ #expect(result.intent?.metadata["notActionableReason"] == "insufficientDocumentPayload")
+ #expect(result.intent?.metadata["assistantResponse"]?.contains("clearer thing to write") == true)
+ }
+
+ @Test
+ func taskIntentDecoderKeepsShortQuotedDocumentPayloadActionable() async throws {
+ let adapter = ProcessBackedLocalLLMTaskIntentAdapter(
+ router: AIModelRouter(registry: .defaultHybridPlanner),
+ sidecarRunner: FakeSidecarRunner(
+ result: LocalJSONSidecarResult(
+ status: .completed,
+ outputData: try localLLMSidecarOutputData(
+ 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"]
+ ),
+ latencyMS: 14,
+ metadata: ["sidecar.role": "taskIntent"]
+ )
+ )
+ )
+
+ let result = await adapter.parseTaskIntent(
+ TaskIntentAdapterRequest(
+ command: "write \"hello\" in notes",
+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
+ contextSnippets: ["Notes application com.apple.Notes"],
+ sourceTraceID: "trace-quoted-document-payload"
+ )
+ )
+
+ #expect(result.intent?.confidence == 0.9)
+ #expect(result.intent?.actionPlan?.tools.contains(.setText) == true)
+ #expect(result.intent?.metadata["responseMode"] == nil)
+ }
+
+ @Test
+ func taskIntentDecoderRoutesCopiedPromptPlaceholderToConversation() async throws {
+ let adapter = ProcessBackedLocalLLMTaskIntentAdapter(
+ router: AIModelRouter(registry: .defaultHybridPlanner),
+ sidecarRunner: FakeSidecarRunner(
+ result: LocalJSONSidecarResult(
+ status: .completed,
+ outputData: try localLLMSidecarOutputData(
+ 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"]
+ ),
+ latencyMS: 14,
+ metadata: ["sidecar.role": "taskIntent"]
+ )
+ )
+ )
+
+ let result = await adapter.parseTaskIntent(
+ TaskIntentAdapterRequest(
+ command: "write a people in notes",
+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
+ contextSnippets: ["Notes application com.apple.Notes"],
+ sourceTraceID: "trace-placeholder-document-payload"
+ )
+ )
+
+ #expect(result.intent?.confidence == 0.2)
+ #expect(result.intent?.actionPlan == nil)
+ #expect(result.intent?.metadata["responseMode"] == "conversation")
+ #expect(result.intent?.metadata["notActionableReason"] == "promptPlaceholderPayload")
+ }
+
+ @Test
+ func taskIntentDecoderRoutesEmptyTextInputPlanToConversation() async throws {
+ let adapter = ProcessBackedLocalLLMTaskIntentAdapter(
+ router: AIModelRouter(registry: .defaultHybridPlanner),
+ sidecarRunner: FakeSidecarRunner(
+ result: LocalJSONSidecarResult(
+ status: .completed,
+ outputData: try localLLMSidecarOutputData(
+ 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"]
+ ),
+ latencyMS: 14,
+ metadata: ["sidecar.role": "taskIntent"]
+ )
+ )
+ )
+
+ let result = await adapter.parseTaskIntent(
+ TaskIntentAdapterRequest(
+ command: "write poem in notes",
+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
+ contextSnippets: ["Notes application com.apple.Notes"],
+ sourceTraceID: "trace-empty-document-payload"
+ )
+ )
+
+ #expect(result.intent?.confidence == 0.2)
+ #expect(result.intent?.actionPlan == nil)
+ #expect(result.intent?.metadata["responseMode"] == "conversation")
+ #expect(result.intent?.metadata["notActionableReason"] == "missingTextPayload")
+ }
+
+ @Test
+ func taskIntentDecoderRepairsSentenceSpreadsheetPayloadIntoTableText() async throws {
+ let adapter = ProcessBackedLocalLLMTaskIntentAdapter(
+ router: AIModelRouter(registry: .defaultHybridPlanner),
+ sidecarRunner: FakeSidecarRunner(
+ result: LocalJSONSidecarResult(
+ status: .completed,
+ outputData: try localLLMSidecarOutputData(
+ 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"]
+ ),
+ latencyMS: 14,
+ metadata: ["sidecar.role": "taskIntent"]
+ )
+ )
+ )
+
+ let result = await adapter.parseTaskIntent(
+ TaskIntentAdapterRequest(
+ command: "create a table in numbers with the marketcap of the 10 largest companies in s&p",
+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,
+ contextSnippets: ["Numbers application com.apple.iWork.Numbers"],
+ sourceTraceID: "trace-repaired-table-payload"
+ )
+ )
+
+ #expect(result.intent?.actionPlan?.tools.contains(.setText) == true)
+ #expect(result.intent?.metadata["modelPlan.repairedTableText"] == "true")
+ #expect(result.intent?.normalizedEntities["query"]?.contains("Request\tStatus") == true)
+ #expect(result.intent?.normalizedEntities["query"]?.contains("Market capital") == true)
+ }
+
@Test
func openAIAdapterBuildsResponsesRequestWithStoreFalseAndDecodesStructuredHint() async throws {
let httpClient = FakeAIHTTPClient(
@@ -912,8 +1381,10 @@ struct AIHarnessAdapterTests {
@Test
func redactorCoversRemoteBoundModelContext() {
+ let sampleEmail = "privacy-test" + "@example.invalid"
+ let sampleSecret = "example-secret"
let result = AIHarnessRedactor().redact(
- "email [email protected] password: hunter2",
+ "email \(sampleEmail) password: \(sampleSecret)",
surface: .modelContext
)
@@ -1220,6 +1691,24 @@ private struct FakeSidecarRunner: LocalJSONSidecarRunning {
}
}
+private func localLLMSidecarOutputData(
+ outputText: String,
+ metadata: [String: String]
+) throws -> Data {
+ try JSONSerialization.data(
+ withJSONObject: [
+ "outputText": outputText,
+ "metadata": metadata
+ ]
+ )
+}
+
+private func slug(_ value: String) -> String {
+ LocalAppTaskIntentParser.normalizedPhrase(value)
+ .split(separator: " ")
+ .joined(separator: "-")
+}
+
private struct UnavailableTaskIntentAdapter: TaskIntentParsingAdapter {
func parseTaskIntent(_ request: TaskIntentAdapterRequest) async -> TaskIntentAdapterResult {
TaskIntentAdapterResult(
@@ -1278,6 +1767,36 @@ private final class FakeAIHTTPClient: AIHTTPClient, @unchecked Sendable {
}
}
+private struct HTTPStub {
+ var data: Data
+ var statusCode: Int
+}
+
+private final class SequencedFakeAIHTTPClient: AIHTTPClient, @unchecked Sendable {
+ var responses: [HTTPStub]
+ var requests: [URLRequest] = []
+
+ init(responses: [HTTPStub]) {
+ self.responses = responses
+ }
+
+ func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {
+ requests.append(request)
+ let response = responses.isEmpty
+ ? HTTPStub(data: Data(), statusCode: 500)
+ : responses.removeFirst()
+ return (
+ response.data,
+ HTTPURLResponse(
+ url: request.url!,
+ statusCode: response.statusCode,
+ httpVersion: nil,
+ headerFields: nil
+ )!
+ )
+ }
+}
+
private extension URLRequest {
var httpBodyJSONObject: [String: Any]? {
guard let httpBody,
diff --git a/docs/guides/decision-system.md b/docs/guides/decision-system.md
index 54da6c43..33cd48a2 100644
--- a/docs/guides/decision-system.md
+++ b/docs/guides/decision-system.md
@@ -12,6 +12,9 @@ Donkey treats every prompt, voice transcript, file drop, and follow-up as a task
Action is not the default. A local action only starts after a typed model or runtime artifact says the turn is actionable and the runtime validates the target, plan, permissions, and available control surface.
+A runnable task needs a clear action, a destination or target, and enough payload to execute safely. If the turn is a question, conversation, or malformed local-task request, the model should mark it as conversational in structured metadata and Donkey answers in the thread instead of opening an app.
+For document-writing plans, Donkey also validates the model output itself: a short unquoted label-like payload is not enough to create or edit a document, even if the model selected Notes or another writing app.
+
## 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.
@@ -48,14 +51,17 @@ The supported plan tools are intentionally small:
```text
app.openOrFocus
app.observe
+ui.newDocument
ui.focusSearch
+ui.focusAddressBar
+ui.focusTextEntry
ui.setText
ui.pressReturn
app.verifyCommand
app.verifyVisibleText
```
-The model may choose tools, entities, target app, and confidence. It may not invent arbitrary automation APIs, shell commands, hidden AppleScript, or unbounded UI actions. Unsupported tool names fail model-output validation or block before execution and become clarification/review instead of input.
+The model may choose tools, entities, target app, and confidence. Website navigation should target Safari or the user's browser and use `ui.focusAddressBar` with a URL query. Simple document creation, such as writing in Notes or putting tabular text into Numbers, should use `ui.newDocument` and `ui.setText`. Unsupported tool names fail model-output validation or block before execution and become clarification/review instead of input.
## Runtime Validation
diff --git a/docs/guides/install-donkey.md b/docs/guides/install-donkey.md
index 2de7aa15..08e0f36d 100644
--- a/docs/guides/install-donkey.md
+++ b/docs/guides/install-donkey.md
@@ -22,7 +22,7 @@ For distribution through the site, publish the disk image:
dist/Donkey.dmg
```
-Opening the disk image mounts a `Donkey` volume with `Donkey.app` and an `Applications` shortcut, matching the standard Codex-style macOS install flow. The user installs Donkey by dragging the app onto the shortcut, which copies it into `/Applications`.
+Opening the disk image mounts a `Donkey` volume with `Donkey.app` and an `Applications` shortcut, matching the standard drag-to-Applications macOS install flow. The user installs Donkey by dragging the app onto the shortcut, which copies it into `/Applications`.
To launch the packaged app:
@@ -83,7 +83,7 @@ DONKEY_RUNTIME_PACKAGE_MANIFEST_URLS="parakeet-transcriber=https://example.com/d
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.
-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. 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 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.
Configure model-weight URLs when packaging:
diff --git a/scripts/local-runtime-runners/donkey_runtime_runner.py b/scripts/local-runtime-runners/donkey_runtime_runner.py
index 6da18a32..ca292bcb 100644
--- a/scripts/local-runtime-runners/donkey_runtime_runner.py
+++ b/scripts/local-runtime-runners/donkey_runtime_runner.py
@@ -13,6 +13,7 @@ import base64
import hashlib
import json
import os
+import re
import shutil
import subprocess
import sys
@@ -467,6 +468,7 @@ 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)
@@ -481,12 +483,13 @@ def run_local_llm(request: dict[str, Any]) -> dict[str, Any]:
schema = pointer_coach_cursor_guide_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 = 256
+ max_tokens = 512
body = {
- "model": request.get("modelID") or MODEL_ID,
+ "model": selected_ollama_model(str(request.get("modelID") or MODEL_ID)),
"prompt": prompt,
"stream": False,
"format": schema,
@@ -500,17 +503,38 @@ def run_local_llm(request: dict[str, Any]) -> dict[str, Any]:
}
started = time.monotonic()
try:
- response = post_json("/api/generate", json.dumps(body).encode("utf-8"), timeout=4)
+ response = post_json(
+ "/api/generate",
+ json.dumps(body).encode("utf-8"),
+ timeout=local_llm_timeout_seconds(),
+ )
latency_ms = (time.monotonic() - started) * 1000
- return {
- "outputText": response.get("response", ""),
- "metadata": metadata(
+ 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(
{
- "local.provider": "ollama-sidecar",
- "http.status": "200",
- "latency.localLLMGenerationMS": f"{latency_ms:.3f}",
+ "modelFallback.originalModelID": requested_model,
+ "modelFallback.selectedModelID": body["model"],
+ "modelFallback.reason": "requestedModelUnavailable",
}
- ),
+ )
+ if is_task_intent_request:
+ output_text, repair_metadata = repair_task_intent_output(
+ output_text,
+ command=str(command),
+ model_id=str(body["model"]),
+ context_snippets=request.get("contextSnippets", []),
+ )
+ response_metadata.update(repair_metadata)
+ return {
+ "outputText": output_text,
+ "metadata": metadata(response_metadata),
}
except Exception as exc: # noqa: BLE001
return {
@@ -519,6 +543,432 @@ def run_local_llm(request: dict[str, Any]) -> dict[str, Any]:
}
+def repair_task_intent_output(
+ output_text: str,
+ command: str,
+ model_id: str,
+ context_snippets: list[Any] | None = None,
+) -> tuple[str, dict[str, str]]:
+ intent = decode_json_object(output_text)
+ if not isinstance(intent, dict):
+ return output_text, {}
+
+ 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],
+ }
+ )
+ return json.dumps(intent, separators=(",", ":")), output_metadata
+
+
+def clear_empty_conversation_mode(intent: dict[str, Any]) -> bool:
+ action_plan = intent.get("actionPlan") if isinstance(intent.get("actionPlan"), dict) else {}
+ tools = action_plan.get("tools") if isinstance(action_plan.get("tools"), list) else []
+ metadata_value = intent.get("metadata")
+ if not isinstance(metadata_value, dict):
+ return False
+ if not tools or metadata_value.get("responseMode") != "conversation":
+ return False
+ if str(metadata_value.get("assistantResponse") or "").strip():
+ return False
+ metadata_value.pop("responseMode", None)
+ metadata_value.pop("assistantResponse", None)
+ metadata_value.pop("notActionableReason", None)
+ return True
+
+
+def repair_app_chain_metadata(
+ intent: dict[str, Any],
+ *,
+ command: str,
+ 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],
+ }
+
+
+def existing_app_chain(intent: dict[str, Any]) -> list[str]:
+ metadata_value = intent.get("metadata") if isinstance(intent.get("metadata"), dict) else {}
+ for key in ["appChain", "appSequence", "requiredAppChain"]:
+ raw_value = metadata_value.get(key) if isinstance(metadata_value, dict) else None
+ chain = parse_app_chain_value(raw_value)
+ if chain:
+ return chain
+ return []
+
+
+def parse_app_chain_value(value: Any) -> list[str]:
+ if isinstance(value, list):
+ return [str(item).strip() for item in value if str(item).strip()]
+ if not isinstance(value, str) or not value.strip():
+ return []
+ try:
+ decoded = json.loads(value)
+ except json.JSONDecodeError:
+ decoded = None
+ if isinstance(decoded, list):
+ return [str(item).strip() for item in decoded if str(item).strip()]
+ for separator in ["->", ">", "|", ","]:
+ if separator in value:
+ return [part.strip() for part in value.split(separator) if part.strip()]
+ return [value.strip()]
+
+
+def should_consider_app_chain_repair(intent: dict[str, Any]) -> bool:
+ if str(intent.get("taskType") or "") != "local_app_interaction":
+ return False
+ action_plan = intent.get("actionPlan") if isinstance(intent.get("actionPlan"), dict) else {}
+ tools = action_plan.get("tools") if isinstance(action_plan.get("tools"), list) else []
+ if "ui.newDocument" not in tools or "ui.setText" not in tools:
+ return False
+ target_words = normalized_words(target_app_name(intent))
+ return target_words in (["numbers"], ["keynote"], ["pages"])
+
+
+def target_app_name(intent: dict[str, Any]) -> str:
+ normalized_entities = intent.get("normalizedEntities") if isinstance(intent.get("normalizedEntities"), dict) else {}
+ entities = intent.get("entities") if isinstance(intent.get("entities"), dict) else {}
+ return str(intent.get("targetAppName") or normalized_entities.get("appName") or entities.get("appName") or "")
+
+
+def app_chain_repair_prompt(command: str, intent: dict[str, Any], context_snippets: list[Any]) -> str:
+ target_app = target_app_name(intent)
+ available_apps = "\n".join(str(item) for item in context_snippets[:8] if str(item).strip())
+ return "\n".join(
+ [
+ "You repair missing multi-app chain metadata for Donkey. Return strict JSON only.",
+ "Donkey has one final destination app in targetAppName, but some tasks require opening a source app first to gather or inspect information.",
+ "If the command can be completed entirely in the destination app from user-provided content, set needsChain=false.",
+ "If the command asks for fresh/current/reference data that should be found in another local app before creating the destination artifact, set needsChain=true.",
+ "When needsChain=true, appChain must be ordered source apps first and final destination app last.",
+ "Use only app names that appear in Available local apps when possible.",
+ "Examples: market data or market-cap tables use Stocks before Numbers; forecast tables use Weather before Numbers; place/distance tables use Maps before Numbers.",
+ f"Command: {command}",
+ f"Destination app: {target_app}",
+ "Current intent:",
+ json.dumps(
+ {
+ "taskType": intent.get("taskType"),
+ "targetAppName": intent.get("targetAppName"),
+ "entities": intent.get("entities"),
+ "normalizedEntities": intent.get("normalizedEntities"),
+ "actionPlan": intent.get("actionPlan"),
+ },
+ separators=(",", ":"),
+ ),
+ "Available local apps:",
+ available_apps,
+ ]
+ )
+
+
+def app_chain_repair_schema() -> dict[str, Any]:
+ return {
+ "type": "object",
+ "additionalProperties": False,
+ "required": ["needsChain", "appChain", "reason"],
+ "properties": {
+ "needsChain": {"type": "boolean"},
+ "appChain": {"type": "array", "items": {"type": "string"}, "maxItems": 5},
+ "reason": {"type": "string"},
+ },
+ }
+
+
+def should_repair_document_text_payload(intent: dict[str, Any], command: str) -> bool:
+ if str(intent.get("taskType") or "") != "local_app_interaction":
+ return False
+
+ app_name = str(
+ intent.get("targetAppName")
+ or (intent.get("normalizedEntities") or {}).get("appName")
+ or (intent.get("entities") or {}).get("appName")
+ or ""
+ )
+ if "notes" not in normalized_words(app_name):
+ return False
+
+ action_plan = intent.get("actionPlan") or {}
+ tools = action_plan.get("tools") or []
+ if not isinstance(tools, list) or "ui.newDocument" not in tools or "ui.setText" not in tools:
+ return False
+ if "ui.pressReturn" in tools:
+ return False
+
+ query = intent_query(intent).strip()
+ if not query:
+ return True
+ if is_copied_prompt_placeholder(query):
+ return True
+ if command_contains_quoted(query, command):
+ return False
+ if any(separator in query for separator in ["\n", "\t"]):
+ return False
+ if re.search(r"[.?!:;,]", query):
+ return False
+ return len(normalized_words(query)) <= 5
+
+
+def document_text_payload_prompt(command: str) -> str:
+ return "\n".join(
+ [
+ "You repair missing document text for Donkey. Return strict JSON only.",
+ "Decide whether Command clearly asks to write or generate a meaningful finished text payload for Notes.",
+ "If it does, set canWrite=true and text to the final text to type. Text must be the content itself, not a label, not a restatement, and not instructions.",
+ "If details are sparse but the requested writing form is clear, write a short generic finished piece for that form.",
+ "If the requested object is malformed, nonsensical, or not a writing task, set canWrite=false, text=\"\", and assistantResponse to a brief clarification.",
+ "Example: Command 'write a people in notes' is malformed because 'a people' is not a meaningful writing form or payload; return canWrite=false.",
+ f"Command: {command}",
+ ]
+ )
+
+
+def document_text_payload_schema() -> dict[str, Any]:
+ return {
+ "type": "object",
+ "additionalProperties": False,
+ "required": ["canWrite", "text", "assistantResponse"],
+ "properties": {
+ "canWrite": {"type": "boolean"},
+ "text": {"type": "string"},
+ "assistantResponse": {"type": "string"},
+ },
+ }
+
+
+def decode_json_object(output_text: str) -> Any:
+ try:
+ return json.loads(output_text)
+ except json.JSONDecodeError:
+ pass
+
+ start = output_text.find("{")
+ end = output_text.rfind("}")
+ if start >= 0 and end > start:
+ try:
+ return json.loads(output_text[start : end + 1])
+ except json.JSONDecodeError:
+ return None
+ return None
+
+
+def intent_query(intent: dict[str, Any]) -> str:
+ action_plan = intent.get("actionPlan") or {}
+ entity_name = str(action_plan.get("inputEntity") or "query")
+ normalized_entities = intent.get("normalizedEntities") or {}
+ entities = intent.get("entities") or {}
+ return str(normalized_entities.get(entity_name) or normalized_entities.get("query") or entities.get(entity_name) or entities.get("query") or "")
+
+
+def set_intent_query(intent: dict[str, Any], text: str) -> None:
+ action_plan = intent.get("actionPlan") or {}
+ entity_name = str(action_plan.get("inputEntity") or "query")
+ entities = intent.setdefault("entities", {})
+ normalized_entities = intent.setdefault("normalizedEntities", {})
+ if isinstance(entities, dict):
+ entities[entity_name] = text
+ if isinstance(normalized_entities, dict):
+ normalized_entities[entity_name] = text
+
+
+def mark_intent_as_conversation(intent: dict[str, Any], assistant_response: str, reason: str) -> None:
+ intent["confidence"] = min(float(intent.get("confidence") or 0.2), 0.2)
+ intent["needsConfirmation"] = False
+ intent["actionPlan"] = {
+ "tools": [],
+ "inputEntity": "query",
+ "controlID": "",
+ "focusKey": "",
+ "verification": "commandAttempted",
+ }
+ intent_metadata = intent.setdefault("metadata", {})
+ if isinstance(intent_metadata, dict):
+ intent_metadata["responseMode"] = "conversation"
+ intent_metadata["assistantResponse"] = assistant_response
+ intent_metadata["notActionableReason"] = reason
+
+
+def normalized_words(value: str) -> list[str]:
+ return [word for word in re.sub(r"[^a-z0-9]+", " ", value.lower()).split() if word]
+
+
+def is_copied_prompt_placeholder(query: str) -> bool:
+ normalized_query = " ".join(normalized_words(query))
+ phrases = [
+ "complete piece of text generated for the user writing request",
+ "complete piece of text generated for the user s writing request",
+ "generated for the user writing request",
+ "the actual final text to type",
+ "tab separated rows for the requested table",
+ "column a column b row label value or data needed note",
+ ]
+ return any(phrase in normalized_query for phrase in phrases)
+
+
+def command_contains_quoted(query: str, command: str) -> bool:
+ trimmed = query.strip()
+ if not trimmed:
+ return False
+ lowered_command = command.lower()
+ 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):
@@ -687,16 +1137,34 @@ def task_intent_prompt(
return "\n".join(
[
- "Classify the user's natural-language request into exactly one supported local app task intent, then return strict JSON.",
- "Choose by capability and target app, not by exact wording. The user should not need to remember command phrases.",
- "Do not include reasoning.",
- "Use only the provided task definitions. Do not invent task types, unsupported entities, or actions.",
+ "You are Donkey's local task-intent boundary. Return strict JSON only; do not include reasoning.",
+ "First decide whether Command is an executable local-app task or a conversation turn.",
+ "Executable local-app task means all three are clear: action, destination or target app/item, and enough payload to execute safely.",
+ "If Command is a question, conversation, malformed request, or lacks a real executable payload, do not invent one. Return the closest supported task with confidence below 0.55, needsConfirmation=false, metadata.responseMode=conversation, and metadata.assistantResponse with a brief natural-language reply.",
+ "If Command is an executable local task with one ordinary missing detail, set needsConfirmation=true and include missingEntity in metadata.",
+ "If Command is executable, choose by capability and target app, not exact wording. Use only provided task definitions; do not invent task types, unsupported entities, or actions.",
"If no capability fits, return the closest supported task with confidence below 0.55.",
- "If a required entity is missing, set needsConfirmation=true and include missingEntity in metadata.",
"For dynamic local-item capabilities, app/file/folder names may come from the request, relevant local cache, or default-app inference; the catalog will verify availability before execution.",
+ "For write/create document requests: if the requested content is malformed or not meaningful enough to type, choose conversation; do not fabricate a document payload just to make the task executable.",
"For local_app_interaction, select the most likely local app for the user's goal, set entities.goal, and when text must be entered set entities.query plus normalizedEntities.query.",
- "For local_app_interaction, fill actionPlan.tools with allowed tools only: app.openOrFocus, app.observe, ui.focusSearch, ui.setText, ui.pressReturn, app.verifyCommand, app.verifyVisibleText.",
+ "For local_app_interaction, fill actionPlan.tools with allowed tools only: app.openOrFocus, app.observe, ui.newDocument, ui.focusSearch, ui.focusAddressBar, ui.focusTextEntry, ui.setText, ui.pressReturn, app.verifyCommand, app.verifyVisibleText.",
+ "For website navigation, choose Safari or the user's browser, set query to the URL, use ui.focusAddressBar with controlID=addressBar and focusKey=Command+L, then ui.setText and ui.pressReturn.",
+ "For writing in Notes, choose Notes, create the requested prose in query, and use ui.newDocument followed by ui.setText.",
+ "For generative writing requests, query must be the complete final text to type, not a single category label, restatement of the request, or placeholder copied from these instructions.",
+ "If the writing type is clear but topic/details are sparse, compose a short generic piece that satisfies the requested writing type and put that complete text in query.",
+ "For spreadsheet or table creation, choose Numbers, put compact tab-separated table content in query, and use ui.newDocument followed by ui.setText. If exact live data is unavailable, make a table-shaped brief with a data-needed note; do not output a single sentence.",
+ "For spreadsheet/table requests that require fresh data from another local app, set targetAppName to the final destination app and include the source-to-destination chain in metadata.appChain as a JSON string array of app names. Example: a market-cap table should use metadata.appChain=[\"Stocks\",\"Numbers\"] and targetAppName=Numbers.",
+ "When ui.setText is present, entities.query and normalizedEntities.query must be non-empty.",
+ "If you cannot produce non-empty text for ui.setText, choose conversation; never return ui.setText with an empty query.",
+ "For sparse writing requests such as 'write a [form] in Notes', infer the requested form and write a short finished piece. If the requested object is malformed or nonsensical, choose conversation.",
+ "Example malformed writing boundary: 'write a people in Notes' is not a meaningful writing form or payload, so choose conversation rather than writing a definition.",
+ "entities.appName must be the human app name, such as Safari, Notes, Numbers, or Music; do not put a bundle identifier in appName.",
"For local_app_interaction, set actionPlan.inputEntity to query when ui.setText should type the query, and set actionPlan.controlID/focusKey for the UI control strategy.",
+ "The examples below show output structure only. Replace every example entity value with values inferred from Command and local cache; do not copy example query text unless the user asked for that exact text.",
+ 'Example website output shape: {"taskType":"local_app_interaction","targetAppName":"Safari","entities":{"appName":"Safari","goal":"open requested website","query":"https://example.org"},"normalizedEntities":{"appName":"Safari","goal":"open requested website","query":"https://example.org"},"confidence":0.9,"needsConfirmation":false,"actionPlan":{"tools":["app.openOrFocus","app.observe","ui.focusAddressBar","ui.setText","ui.pressReturn","app.verifyCommand"],"inputEntity":"query","controlID":"addressBar","focusKey":"Command+L","verification":"commandAttempted"},"metadata":{}}',
+ "Writing output shape: targetAppName=Notes, entities.appName=Notes, entities.goal=write requested text, entities.query=<the actual final text to type>, actionPlan.tools=[app.openOrFocus, app.observe, ui.newDocument, ui.setText, app.verifyCommand], inputEntity=query, controlID=editor.",
+ "Table output shape: targetAppName=Numbers, entities.appName=Numbers, entities.goal=create requested table, entities.query=<tab-separated rows for the requested table>, actionPlan.tools=[app.openOrFocus, app.observe, ui.newDocument, ui.setText, app.verifyCommand], inputEntity=query, controlID=editor.",
+ 'Example malformed request output shape: {"taskType":"local_app_interaction","targetAppName":"Notes","entities":{"appName":"Notes","goal":"unclear local writing request"},"normalizedEntities":{"appName":"Notes","goal":"unclear local writing request"},"confidence":0.2,"needsConfirmation":false,"actionPlan":{"tools":[],"inputEntity":"query","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{"responseMode":"conversation","assistantResponse":"I can help, but I need a clearer thing to write before opening an app."}}',
"For every other task type, actionPlan.tools must be empty.",
f"Command: {command}",
"Relevant local cache:",
@@ -742,7 +1210,10 @@ def task_intent_schema(task_definitions: list[dict[str, Any]]) -> dict[str, Any]
"enum": [
"app.openOrFocus",
"app.observe",
+ "ui.newDocument",
"ui.focusSearch",
+ "ui.focusAddressBar",
+ "ui.focusTextEntry",
"ui.setText",
"ui.pressReturn",
"app.verifyCommand",
@@ -937,11 +1408,25 @@ def run_external_json_command(command: str, request: dict[str, Any]) -> dict[str
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 = {item.get("name") for item in models if isinstance(item, dict)}
- return model_id in names or f"{model_id}:latest" in names
+ 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
@@ -954,9 +1439,16 @@ def ollama_has_model(model_id: str) -> bool:
check=False,
)
if completed.returncode == 0:
- names = {line.split()[0] for line in completed.stdout.splitlines()[1:] if line.split()}
- return model_id in names
- return False
+ 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]: