Skip to content

Open source CapCut alternative.

TypeScript

Add local task intent and YOLO26 vision catalog

David Lef649db113b24
diff --git a/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift b/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift
index f5bfa72b..8a316d20 100644
--- a/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift
+++ b/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift
@@ -7,6 +7,7 @@ public enum AIModelProvider: String, Codable, Equatable, Sendable {
}
public enum AIModelRole: String, Codable, Equatable, Sendable {
+ case taskIntent
case plannerHint
case traceSummary
case recovery
@@ -99,6 +100,23 @@ public struct AIModelRegistry: Codable, Equatable, Sendable {
public static let defaultHybridPlanner = AIModelRegistry(
entries: [
+ AIModelRegistryEntry(
+ id: "ollama-task-intent-local",
+ role: .taskIntent,
+ provider: .ollama,
+ modelID: "qwen3:8b",
+ endpoint: URL(string: "http://127.0.0.1:11434/api/generate")!,
+ capabilities: [.textInput, .structuredOutputs],
+ timeoutMS: 4_000,
+ promptVersion: "task-intent-v1",
+ evalStatus: .candidate,
+ docsURL: URL(string: "https://docs.ollama.com/api")!,
+ rollbackID: nil,
+ metadata: [
+ "local": "true",
+ "docsSource": "official Ollama API docs"
+ ]
+ ),
AIModelRegistryEntry(
id: "ollama-planner-hint-local",
role: .plannerHint,
@@ -138,6 +156,7 @@ public struct AIModelRegistry: Codable, Equatable, Sendable {
}
public enum AIModelJobType: String, Codable, Equatable, Sendable {
+ case taskIntent
case plannerHint
case traceSummary
case recovery
@@ -236,6 +255,8 @@ public struct AIModelRouter: Sendable {
private func role(for jobType: AIModelJobType) -> AIModelRole {
switch jobType {
+ case .taskIntent:
+ return .taskIntent
case .plannerHint:
return .plannerHint
case .traceSummary:
diff --git a/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift b/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift
new file mode 100644
index 00000000..72327bb1
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift
@@ -0,0 +1,389 @@
+import DonkeyContracts
+import DonkeyRuntime
+import Foundation
+
+public struct TaskIntentAdapterRequest: Equatable, Sendable {
+ public var command: String
+ public var taskDefinitions: [LocalAppTaskDefinition]
+ public var sourceTraceID: String
+ public var routeRequest: AIModelRouteRequest
+
+ public init(
+ command: String,
+ taskDefinitions: [LocalAppTaskDefinition],
+ sourceTraceID: String,
+ routeRequest: AIModelRouteRequest = AIModelRouteRequest(
+ jobType: .taskIntent,
+ privacyMode: .privacySensitive,
+ latencyTolerance: .interactive
+ )
+ ) {
+ self.command = command
+ self.taskDefinitions = taskDefinitions
+ self.sourceTraceID = sourceTraceID
+ self.routeRequest = routeRequest
+ }
+}
+
+public struct TaskIntentAdapterResult: Equatable, Sendable {
+ public var intent: TaskIntent?
+ public var trace: AIModelCallTrace
+
+ public init(intent: TaskIntent?, trace: AIModelCallTrace) {
+ self.intent = intent
+ self.trace = trace
+ }
+}
+
+public struct OllamaTaskIntentAdapter: Sendable {
+ public static let schemaID = "task_intent_v1"
+
+ public var router: AIModelRouter
+ public var httpClient: any AIHTTPClient
+
+ public init(
+ router: AIModelRouter = AIModelRouter(registry: .defaultHybridPlanner),
+ httpClient: any AIHTTPClient = URLSessionAIHTTPClient()
+ ) {
+ self.router = router
+ self.httpClient = httpClient
+ }
+
+ public func parseTaskIntent(
+ _ request: TaskIntentAdapterRequest
+ ) async -> TaskIntentAdapterResult {
+ let entry: AIModelRegistryEntry
+ do {
+ entry = try router.route(request.routeRequest.limitingProviders([.ollama]))
+ } catch {
+ return result(
+ entry: nil,
+ request: request,
+ status: .invalidOutput,
+ validationStatus: "routingFailed",
+ latencyMS: nil,
+ metadata: ["error": String(describing: error)]
+ )
+ }
+
+ let startedAt = ProcessInfo.processInfo.systemUptime
+ 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 == 429 {
+ return result(entry: entry, request: request, status: .rateLimited, validationStatus: "notValidated", latencyMS: latencyMS)
+ }
+
+ if response.statusCode >= 500 {
+ return result(entry: entry, request: request, status: .providerOutage, validationStatus: "notValidated", latencyMS: latencyMS)
+ }
+
+ guard (200..<300).contains(response.statusCode),
+ let outputText = try Self.outputText(from: data),
+ let intent = try TaskIntentWireCodec.decodeIntent(
+ outputText,
+ definitions: request.taskDefinitions,
+ sourceModelCallID: "model-call-\(request.sourceTraceID)"
+ )
+ else {
+ return result(entry: entry, request: request, status: .invalidOutput, validationStatus: "invalid", latencyMS: latencyMS)
+ }
+
+ return TaskIntentAdapterResult(
+ intent: intent,
+ trace: trace(
+ entry: entry,
+ request: request,
+ status: .completed,
+ validationStatus: "schemaDecoded",
+ latencyMS: latencyMS,
+ metadata: [
+ "http.status": String(response.statusCode),
+ "local.provider": "ollama"
+ ]
+ )
+ )
+ } catch is CancellationError {
+ return result(entry: entry, request: request, status: .cancelled, validationStatus: "notValidated", latencyMS: nil)
+ } catch {
+ let latencyMS = (ProcessInfo.processInfo.systemUptime - startedAt) * 1_000
+ let status: AIModelCallStatus = (error as NSError).code == NSURLErrorTimedOut ? .timeout : .providerOutage
+ return result(
+ entry: entry,
+ request: request,
+ status: status,
+ validationStatus: "notValidated",
+ latencyMS: latencyMS,
+ metadata: ["error": String(describing: error)]
+ )
+ }
+ }
+
+ private func makeURLRequest(
+ entry: AIModelRegistryEntry,
+ adapterRequest: TaskIntentAdapterRequest
+ ) throws -> URLRequest {
+ var request = URLRequest(url: entry.endpoint)
+ request.httpMethod = "POST"
+ request.timeoutInterval = Double(entry.timeoutMS) / 1_000
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ request.httpBody = try JSONSerialization.data(withJSONObject: requestBody(entry: entry, adapterRequest: adapterRequest))
+ return request
+ }
+
+ private func requestBody(
+ entry: AIModelRegistryEntry,
+ adapterRequest: TaskIntentAdapterRequest
+ ) -> [String: Any] {
+ [
+ "model": entry.modelID,
+ "prompt": promptText(for: adapterRequest),
+ "stream": false,
+ "format": TaskIntentWireCodec.jsonSchema(
+ taskTypes: adapterRequest.taskDefinitions.map(\.taskType),
+ appNames: adapterRequest.taskDefinitions.map(\.targetApp.appName)
+ ),
+ "options": [
+ "num_predict": 512
+ ]
+ ]
+ }
+
+ private func promptText(for request: TaskIntentAdapterRequest) -> String {
+ let tasks = request.taskDefinitions.map { definition in
+ let entities = definition.entityRules.map { rule in
+ "\(rule.name) required=\(rule.required) markers=\(rule.markers.joined(separator: ",")) aliases=\(rule.aliases.keys.sorted().joined(separator: ","))"
+ }
+ .joined(separator: "; ")
+
+ return [
+ "task_type=\(definition.taskType)",
+ "app=\(definition.targetApp.appName)",
+ "bundle=\(definition.targetApp.bundleIdentifier ?? "unknown")",
+ "triggers=\(definition.triggerTerms.joined(separator: ","))",
+ "entities=\(entities)"
+ ]
+ .joined(separator: " | ")
+ }
+ .joined(separator: "\n")
+
+ return [
+ "Return exactly one local app task intent as strict JSON.",
+ "Use only the provided task definitions. Do not invent apps, task types, entities, or actions.",
+ "If a required entity is missing, set needsConfirmation=true and include missingEntity in metadata.",
+ "Command: \(request.command)",
+ "Task definitions:",
+ tasks
+ ]
+ .joined(separator: "\n")
+ }
+
+ private func result(
+ entry: AIModelRegistryEntry?,
+ request: TaskIntentAdapterRequest,
+ status: AIModelCallStatus,
+ validationStatus: String,
+ latencyMS: Double?,
+ metadata: [String: String] = [:]
+ ) -> TaskIntentAdapterResult {
+ TaskIntentAdapterResult(
+ intent: nil,
+ trace: trace(
+ entry: entry,
+ request: request,
+ status: status,
+ validationStatus: validationStatus,
+ latencyMS: latencyMS,
+ metadata: metadata
+ )
+ )
+ }
+
+ private func trace(
+ entry: AIModelRegistryEntry?,
+ request: TaskIntentAdapterRequest,
+ status: AIModelCallStatus,
+ validationStatus: String,
+ latencyMS: Double?,
+ metadata: [String: String] = [:]
+ ) -> AIModelCallTrace {
+ AIModelCallTrace(
+ id: "model-call-\(request.sourceTraceID)",
+ role: entry?.role ?? .taskIntent,
+ provider: entry?.provider ?? .ollama,
+ modelID: entry?.modelID ?? "unrouted",
+ promptVersion: entry?.promptVersion ?? "unrouted",
+ schemaID: Self.schemaID,
+ latencyMS: latencyMS,
+ timeoutMS: entry?.timeoutMS ?? 0,
+ status: status,
+ validationStatus: validationStatus,
+ sourceTraceID: request.sourceTraceID,
+ metadata: metadata
+ )
+ }
+}
+
+public struct LocalModelTaskIntentResolver: Sendable {
+ public var catalog: LocalAppTaskCatalog
+ public var adapter: OllamaTaskIntentAdapter
+
+ public init(
+ catalog: LocalAppTaskCatalog,
+ adapter: OllamaTaskIntentAdapter = OllamaTaskIntentAdapter()
+ ) {
+ self.catalog = catalog
+ self.adapter = adapter
+ }
+
+ public func resolve(
+ command: String,
+ sourceTraceID: String
+ ) async -> (resolution: LocalAppTaskCatalogResolution, trace: AIModelCallTrace) {
+ let result = await adapter.parseTaskIntent(
+ TaskIntentAdapterRequest(
+ command: command,
+ taskDefinitions: catalog.taskDefinitions,
+ sourceTraceID: sourceTraceID
+ )
+ )
+
+ guard let intent = result.intent else {
+ return (
+ LocalAppTaskCatalogResolution(
+ status: .unsupportedCommand,
+ metadata: [
+ "reason": "localModelIntentUnavailable",
+ "modelCallStatus": result.trace.status.rawValue
+ ]
+ ),
+ result.trace
+ )
+ }
+
+ return (catalog.resolve(intent: intent), result.trace)
+ }
+}
+
+private struct OllamaTaskIntentResponse: Decodable {
+ var response: String?
+}
+
+private enum TaskIntentWireCodec {
+ static func jsonSchema(taskTypes: [String], appNames: [String]) -> [String: Any] {
+ [
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "taskType",
+ "targetAppName",
+ "entities",
+ "normalizedEntities",
+ "confidence",
+ "needsConfirmation",
+ "metadata"
+ ],
+ "properties": [
+ "taskType": ["type": "string", "enum": Array(Set(taskTypes)).sorted()],
+ "targetAppName": ["type": "string", "enum": Array(Set(appNames)).sorted()],
+ "entities": [
+ "type": "object",
+ "additionalProperties": ["type": "string"]
+ ],
+ "normalizedEntities": [
+ "type": "object",
+ "additionalProperties": ["type": "string"]
+ ],
+ "confidence": ["type": "number", "minimum": 0, "maximum": 1],
+ "needsConfirmation": ["type": "boolean"],
+ "metadata": [
+ "type": "object",
+ "additionalProperties": ["type": "string"]
+ ]
+ ]
+ ]
+ }
+
+ static func decodeIntent(
+ _ outputText: String,
+ definitions: [LocalAppTaskDefinition],
+ sourceModelCallID: String
+ ) throws -> TaskIntent? {
+ let data = Data(outputText.utf8)
+ let wire = try JSONDecoder().decode(TaskIntentWire.self, from: data)
+ guard let definition = definitions.first(where: {
+ $0.taskType == wire.taskType && $0.targetApp.appName == wire.targetAppName
+ }) else {
+ return nil
+ }
+
+ let normalizedEntities = normalizedEntities(from: wire, definition: definition)
+ let missingRequiredEntity = definition.entityRules.first { rule in
+ rule.required && normalizedEntities[rule.name] == nil
+ }
+ var metadata = wire.metadata.merging(definition.metadata) { current, _ in current }
+ metadata["parser"] = "ollama-task-intent-v1"
+ if let missingRequiredEntity {
+ metadata["missingEntity"] = missingRequiredEntity.name
+ }
+
+ let needsConfirmation = wire.needsConfirmation || missingRequiredEntity != nil
+ let primaryEntity = definition.verificationEntityName
+ .flatMap { normalizedEntities[$0] }
+ ?? normalizedEntities.values.sorted().first
+ ?? definition.taskType
+
+ return TaskIntent(
+ intentID: needsConfirmation
+ ? "\(definition.taskType)-needs-\(missingRequiredEntity?.name ?? "confirmation")"
+ : "\(definition.taskType)-\(slug(primaryEntity))",
+ taskType: definition.taskType,
+ targetApp: definition.targetApp,
+ entities: wire.entities,
+ normalizedEntities: normalizedEntities,
+ confidence: wire.confidence,
+ parserSource: .localModel,
+ needsConfirmation: needsConfirmation,
+ sourceModelCallID: sourceModelCallID,
+ metadata: metadata
+ )
+ }
+
+ private static func normalizedEntities(
+ from wire: TaskIntentWire,
+ definition: LocalAppTaskDefinition
+ ) -> [String: String] {
+ var normalized = wire.normalizedEntities
+ for rule in definition.entityRules {
+ guard let rawValue = wire.entities[rule.name] ?? normalized[rule.name] else { continue }
+ if let alias = rule.aliases[rawValue] ?? rule.aliases[LocalAppTaskIntentParser.normalizedPhrase(rawValue)] {
+ normalized[rule.name] = alias
+ }
+ }
+ return normalized
+ }
+
+ private static func slug(_ value: String) -> String {
+ LocalAppTaskIntentParser.normalizedPhrase(value)
+ .split(separator: " ")
+ .joined(separator: "-")
+ }
+}
+
+private struct TaskIntentWire: Decodable {
+ var taskType: String
+ var targetAppName: String
+ var entities: [String: String]
+ var normalizedEntities: [String: String]
+ var confidence: Double
+ var needsConfirmation: Bool
+ var metadata: [String: String]
+}
+
+private extension OllamaTaskIntentAdapter {
+ static func outputText(from data: Data) throws -> String? {
+ try JSONDecoder().decode(OllamaTaskIntentResponse.self, from: data).response
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
index 89d1450a..101a6b8b 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift
@@ -119,6 +119,10 @@ public struct LocalAppTaskCatalog: Sendable {
)
}
+ return resolve(intent: intent)
+ }
+
+ public func resolve(intent: TaskIntent) -> LocalAppTaskCatalogResolution {
guard let definition = taskDefinitions.first(where: { supports(intent: intent, definition: $0) }) else {
return LocalAppTaskCatalogResolution(
status: .unsupportedCommand,
diff --git a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskIntentParser.swift b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskIntentParser.swift
index 1c8986f7..a5ae16ec 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskIntentParser.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskIntentParser.swift
@@ -163,7 +163,7 @@ public struct LocalAppTaskIntentParser: Sendable {
.joined(separator: "-")
}
- static func normalizedPhrase(_ value: String) -> String {
+ public static func normalizedPhrase(_ value: String) -> String {
let folded = value.folding(
options: [.diacriticInsensitive, .caseInsensitive],
locale: Locale(identifier: "en_US_POSIX")
diff --git a/apps/Donkey/Sources/DonkeyRuntime/OffTheShelfVisionPerception.swift b/apps/Donkey/Sources/DonkeyRuntime/OffTheShelfVisionPerception.swift
index ae82f823..87afd04b 100644
--- a/apps/Donkey/Sources/DonkeyRuntime/OffTheShelfVisionPerception.swift
+++ b/apps/Donkey/Sources/DonkeyRuntime/OffTheShelfVisionPerception.swift
@@ -8,6 +8,82 @@ public enum OffTheShelfVisionSignalKind: String, Codable, Equatable, Sendable {
case segmentation
}
+public enum OffTheShelfVisionInputSource: String, Codable, Equatable, Sendable {
+ case screenshot
+ case crop
+ case recorded
+}
+
+public struct OffTheShelfVisionModelCandidate: Codable, Equatable, Sendable {
+ public var id: String
+ public var family: String
+ public var modelName: String
+ public var signalKind: OffTheShelfVisionSignalKind
+ public var preferredInputSource: OffTheShelfVisionInputSource
+ public var componentID: String
+ public var docsURL: URL
+ public var lastVerifiedAt: String
+ public var metadata: [String: String]
+
+ public init(
+ id: String,
+ family: String,
+ modelName: String,
+ signalKind: OffTheShelfVisionSignalKind,
+ preferredInputSource: OffTheShelfVisionInputSource,
+ componentID: String,
+ docsURL: URL,
+ lastVerifiedAt: String,
+ metadata: [String: String] = [:]
+ ) {
+ self.id = id
+ self.family = family
+ self.modelName = modelName
+ self.signalKind = signalKind
+ self.preferredInputSource = preferredInputSource
+ self.componentID = componentID
+ self.docsURL = docsURL
+ self.lastVerifiedAt = lastVerifiedAt
+ self.metadata = metadata
+ }
+}
+
+public enum OffTheShelfVisionModelCatalog {
+ public static let yolo26NanoScreenshotSegmentation = OffTheShelfVisionModelCandidate(
+ id: "ultralytics-yolo26n-seg-screenshot",
+ family: "YOLO26",
+ modelName: "yolo26n-seg.pt",
+ signalKind: .segmentation,
+ preferredInputSource: .crop,
+ componentID: "screenshot-segmentation-yolo26",
+ docsURL: URL(string: "https://docs.ultralytics.com/models/yolo26/")!,
+ lastVerifiedAt: "2026-05-17",
+ metadata: [
+ "provider": "ultralytics",
+ "task": "instanceSegmentation",
+ "latestYOLOFamilyVerified": "YOLO26",
+ "screenshotUse": "boundedCropFirst",
+ "liveDefault": "false",
+ "requiresLocalBenchmark": "true",
+ "docsTaskURL": "https://docs.ultralytics.com/tasks/segment/"
+ ]
+ )
+
+ public static var screenshotSegmentationCandidates: [OffTheShelfVisionModelCandidate] {
+ [yolo26NanoScreenshotSegmentation]
+ }
+
+ public static func defaultCandidate(
+ signalKind: OffTheShelfVisionSignalKind,
+ inputSource: OffTheShelfVisionInputSource
+ ) -> OffTheShelfVisionModelCandidate? {
+ screenshotSegmentationCandidates.first {
+ $0.signalKind == signalKind
+ && ($0.preferredInputSource == inputSource || inputSource == .screenshot)
+ }
+ }
+}
+
public struct RecordedOffTheShelfVisionObservation: Codable, Equatable, Sendable {
public var id: String
public var label: String
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
index 8cdd3287..eb6e7d54 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
@@ -68,6 +68,121 @@ struct AIHarnessAdapterTests {
#expect(selected.provider == .ollama)
}
+ @Test
+ func privacySensitiveTaskIntentRouteSelectsLocalProvider() throws {
+ let router = AIModelRouter(registry: .defaultHybridPlanner)
+
+ let selected = try router.route(
+ AIModelRouteRequest(
+ jobType: .taskIntent,
+ privacyMode: .privacySensitive
+ )
+ )
+
+ #expect(selected.id == "ollama-task-intent-local")
+ #expect(selected.role == .taskIntent)
+ #expect(selected.provider == .ollama)
+ }
+
+ @Test
+ func ollamaTaskIntentAdapterBuildsLocalRequestAndDecodesValidatedIntent() async throws {
+ let httpClient = FakeAIHTTPClient(
+ data: ollamaResponseData(
+ response: """
+ {"taskType":"weather_lookup","targetAppName":"Weather","entities":{"city":"SF"},"normalizedEntities":{"city":"San Francisco"},"confidence":0.93,"needsConfirmation":false,"metadata":{"source":"test"}}
+ """
+ ),
+ 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: "show me the weather for SF",
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,
+ sourceTraceID: "trace-intent"
+ )
+ )
+
+ #expect(result.intent?.taskType == "weather_lookup")
+ #expect(result.intent?.targetApp.appName == "Weather")
+ #expect(result.intent?.normalizedEntities["city"] == "San Francisco")
+ #expect(result.intent?.parserSource == .localModel)
+ #expect(result.intent?.sourceModelCallID == "model-call-trace-intent")
+ #expect(result.trace.status == .completed)
+ #expect(result.trace.role == .taskIntent)
+ #expect(result.trace.provider == .ollama)
+
+ let request = try #require(httpClient.requests.first)
+ #expect(request.url?.absoluteString == "http://127.0.0.1:11434/api/generate")
+ let body = try #require(request.httpBodyJSONObject)
+ #expect(body["model"] as? String == "qwen3:8b")
+ #expect(body["stream"] as? Bool == false)
+ #expect(body["format"] as? [String: Any] != nil)
+ #expect((body["prompt"] as? String)?.contains("Use only the provided task definitions") == true)
+ }
+
+ @Test
+ func localModelTaskIntentResolverValidatesAgainstCatalogAvailability() async {
+ let httpClient = FakeAIHTTPClient(
+ data: ollamaResponseData(
+ response: """
+ {"taskType":"weather_lookup","targetAppName":"Weather","entities":{"city":"SF"},"normalizedEntities":{"city":"San Francisco"},"confidence":0.93,"needsConfirmation":false,"metadata":{}}
+ """
+ ),
+ statusCode: 200
+ )
+ let resolver = LocalModelTaskIntentResolver(
+ catalog: LocalAppTaskCatalog(
+ taskDefinitions: BuiltInLocalAppTaskDefinitions.defaults,
+ availabilityProvider: StaticLocalAppAvailabilityProvider(installedBundleIdentifiers: ["com.apple.weather"])
+ ),
+ 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: "show me the weather for SF",
+ sourceTraceID: "trace-resolve-intent"
+ )
+
+ #expect(result.resolution.status == .resolved)
+ #expect(result.resolution.intent?.parserSource == .localModel)
+ #expect(result.resolution.availability?.isInstalled == true)
+ #expect(result.trace.status == .completed)
+ }
+
@Test
func openAIAdapterBuildsResponsesRequestWithStoreFalseAndDecodesStructuredHint() async throws {
let httpClient = FakeAIHTTPClient(
@@ -248,21 +363,23 @@ struct AIHarnessAdapterTests {
private func entry(
id: String,
+ role: AIModelRole = .plannerHint,
provider: AIModelProvider = .openAI,
modelID: String,
endpoint: URL = URL(string: "https://api.openai.com/v1/responses")!,
evalStatus: AIModelEvalStatus = .candidate,
- timeoutMS: Int = 8_000
+ timeoutMS: Int = 8_000,
+ promptVersion: String = "planner-hint-v1"
) -> AIModelRegistryEntry {
AIModelRegistryEntry(
id: id,
- role: .plannerHint,
+ role: role,
provider: provider,
modelID: modelID,
endpoint: endpoint,
capabilities: [.textInput, .structuredOutputs],
timeoutMS: timeoutMS,
- promptVersion: "planner-hint-v1",
+ promptVersion: promptVersion,
evalStatus: evalStatus,
docsURL: provider == .openAI
? URL(string: "https://platform.openai.com/docs/api-reference/responses/create")!
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift
index 2e33f039..971a00c1 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/OffTheShelfVisionPerceptionTests.swift
@@ -5,6 +5,23 @@ import Testing
@Suite
struct OffTheShelfVisionPerceptionTests {
+ @Test
+ func modelCatalogIncludesLatestYOLOForScreenshotSegmentation() throws {
+ let candidate = try #require(OffTheShelfVisionModelCatalog.defaultCandidate(
+ signalKind: .segmentation,
+ inputSource: .screenshot
+ ))
+
+ #expect(candidate.family == "YOLO26")
+ #expect(candidate.modelName == "yolo26n-seg.pt")
+ #expect(candidate.signalKind == .segmentation)
+ #expect(candidate.preferredInputSource == .crop)
+ #expect(candidate.componentID == "screenshot-segmentation-yolo26")
+ #expect(candidate.metadata["latestYOLOFamilyVerified"] == "YOLO26")
+ #expect(candidate.metadata["requiresLocalBenchmark"] == "true")
+ #expect(candidate.docsURL.absoluteString == "https://docs.ultralytics.com/models/yolo26/")
+ }
+
@Test
func metadataCodecRoundTripsLocalVisionEvidence() throws {
let metadata = RecordedOffTheShelfVisionMetadataCodec.encode(signals: [
diff --git a/docs/README.md b/docs/README.md
index 639978f9..70883684 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -4,7 +4,7 @@ This folder is the product and engineering source of truth for capabilities that
Plans describe what we might build. Guides describe what Donkey currently supports and how to maintain it.
-There is an active milestone plan in `plans/master-plan.md`. It tracks the unfinished work needed before the fast local navigation and AI-harness roadmap can be considered complete: generic local-app task knowledge, installed-app/task resolution, deterministic intent parsing, local navigation, guarded input, result verification, latency reporting, and optional slow planner recovery. Weather lookup is the first benchmark definition for this generic system, not a Weather-specific architecture.
+There is an active milestone plan in `plans/master-plan.md`. It tracks the unfinished work needed before the fast local navigation and AI-harness roadmap can be considered complete: generic local-app task knowledge, installed-app/task resolution, local-model command parsing with catalog validation, local navigation, guarded input, result verification, latency reporting, and optional slow planner recovery. Weather lookup is the first benchmark definition for this generic system, not a Weather-specific architecture.
## Product Guides
diff --git a/docs/guides/minimal-run-coordinator.md b/docs/guides/minimal-run-coordinator.md
index 37c0b2ee..18d68d0e 100644
--- a/docs/guides/minimal-run-coordinator.md
+++ b/docs/guides/minimal-run-coordinator.md
@@ -26,13 +26,15 @@ Donkey also supports the first cheap perception and deterministic controller sli
Donkey also supports the first off-the-shelf local vision evidence boundary inside the dry-run reflex loop. `RecordedOffTheShelfVisionMetadataCodec` can carry recorded detector, template, OCR, or segmentation observations with crop ids, component ids, model ids, confidence, coordinate spaces, and measured preprocessing/model latency. `OffTheShelfVisionPerceptionAdapter` converts that local evidence into compact `HotLoopPerceptionSignal` values, and `OffTheShelfVisionWorldStateProjector` exposes only typed affordances to the deterministic controller. This is a local perception contract and replay path; it does not yet run a live Core ML, ONNX, OCR, or template matcher over captured pixels.
+Donkey also tracks the first screenshot segmentation model candidate for the off-the-shelf vision boundary. `OffTheShelfVisionModelCatalog` lists Ultralytics YOLO26 nano segmentation (`yolo26n-seg.pt`) as the current screenshot/crop segmentation candidate, with official docs rechecked on May 17, 2026. This is catalog metadata only; live screenshot segmentation still requires a local runner, crop pipeline, export/runtime choice, and measured latency before it can enter a guarded live loop.
+
Donkey also supports the first action-engine guardrail boundary. `ActionEngineGuardrail` accepts typed tap, swipe, key, mouse, controller, and `releaseAll` commands; checks input permission policy, focus guard status, command rate, and maximum hold duration; tracks held-input state; and records replayable command traces. Live input remains disabled by default and requires explicit configuration, an input-allowing policy, a passing focus guard, and an injected input backend. Allowed non-live commands are projected as dry-run traces, live smoke commands record backend execution evidence, denied commands include explicit denial reasons, and `releaseAll` clears held-input state.
Donkey also supports reflex latency reports and a synthetic replay benchmark. `ReflexLatencyReportBuilder` summarizes reflex traces into p50/p95/p99 latency for software-loop, capture, preprocess/crop-normalize, model inference, perception, state update, controller decision, action projection, and input stages, plus capture/perception/controller rates, dropped frames, stale actions, and worst traces. `ReflexReplayBenchmark` can generate deterministic dry-run traces for capture-only, controller-only, or end-to-end dry-run report modes. The installed debug entrypoint can print a CLI-friendly dry-run latency report with `--dry-run-latency-report`.
Donkey also supports the first fast local-navigation dry-run slice end to end through the dry-run reflex loop. `LocalNavigationMetadataFrameSource` can turn macOS window candidate metadata and optional browser-tab metadata supplied by callers into metadata-only hot-loop frames. `LocalNavigationDryRunPerceptionAdapter` and `LocalNavigationDryRunWorldStateProjector` keep the local-navigation path swappable while preserving the no-remote-model fallback. `LocalNavigationControllerPolicy` can choose traceable dry-run semantic actions such as `focusWindow`, `activateCandidate`, `switchTab`, `wait`, or `observe` from typed state. This slice is metadata-only and side-effect free by default; guarded live-action smoke requires an injected backend, and richer visual inference remains future work.
-Donkey also supports the first generic local-app task catalog, intent, and dry-run adapter boundary. `TaskIntent` can represent a parsed task, target app, normalized entities, parser source, confidence, and confirmation state. `LocalAppTaskDefinition` describes app-task knowledge as data: target app metadata, deterministic trigger terms, required entities and aliases, workflow steps, observation strategies, and verification rules. `LocalAppTaskCatalog` resolves commands against known task definitions, checks target-app availability through an injected provider, and exposes built-in benchmark definitions such as Weather lookup as data rather than source-specific adapters. `LocalAppTaskIntentParser` can parse common local commands without a model call when a task definition is available, and `LocalAppTaskAdapter` can build a target-app local-navigation metadata request, project dry-run workflow steps, emit guarded keyboard command templates for an injected action backend, and verify observed visible text against the requested entity. Default app launch/focus, default OS typing, Accessibility actions, live local-model UI understanding, and live result verification remain unsupported.
+Donkey also supports the first generic local-app task catalog, intent, and dry-run adapter boundary. `TaskIntent` can represent a parsed task, target app, normalized entities, parser source, confidence, and confirmation state. `LocalAppTaskDefinition` describes app-task knowledge as data: target app metadata, deterministic trigger terms, required entities and aliases, workflow steps, observation strategies, and verification rules. `LocalAppTaskCatalog` resolves validated intents against known task definitions, checks target-app availability through an injected provider, and exposes built-in benchmark definitions such as Weather lookup as data rather than source-specific adapters. `OllamaTaskIntentAdapter` is the supported primary command parser: it sends the user command and available task definitions to a local Ollama-compatible structured-output model, decodes a `TaskIntent`, and validates it against the catalog before execution can proceed. `LocalAppTaskIntentParser` remains a deterministic fallback and test scaffold for known commands, not the preferred command-understanding path. `LocalAppTaskAdapter` can build a target-app local-navigation metadata request, project dry-run workflow steps, emit guarded keyboard command templates for an injected action backend, and verify observed visible text against the requested entity. Default app launch/focus, default OS typing, Accessibility actions, live local-model UI understanding, and live result verification remain unsupported.
Donkey also supports a guarded live-action smoke boundary for the first local-navigation behavior. `GuardedLiveActionSmokeRunner` requires an end-to-end dry-run result, a latency report with p95 evidence, a non-fallback latest action, explicit input policy allowance, and a passing action-engine focus guard before mapping semantic local-navigation actions to typed action-engine commands. The smoke path records replayable action traces and can execute only through an injected backend; no default OS input backend is enabled.
@@ -71,7 +73,7 @@ Donkey supports a runtime-level manual target context capture service that wires
The installed executable also supports a developer-only launch-argument entrypoint for manual verification. `--list-window-candidates` prints the current candidate-list labels and durable `windowID` values. `--manual-capture` runs one manual capture, optionally with `--window-id <id>`, `--run-id <safe-id>`, and `--trace-id <safe-id>`, then prints the run folder and artifact paths. These commands are non-interactive and exit before showing the pointer prompt overlay.
-This is a coordination, in-memory reflex trace, hot-loop contract, deterministic dry-run skeleton, bounded target-window frame-source, cheap metadata perception, recorded off-the-shelf local vision evidence, deterministic controller, local-navigation dry-run, generic local-app task catalog/intent/dry-run adapter, guarded live-action smoke boundary, slow-planner sidecar, action-engine guardrail, latency-report, planner-hint contract, model-registry/router, OpenAI and Ollama-compatible planner adapters, memory, replay/eval, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not run live vision models or OCR over captured pixels, ship a default OS input backend, perform Accessibility actions, provide a manual capture UI, persist high-volume reflex traces to disk, provide continuous streaming capture, or make model calls required for reflex ticks.
+This is a coordination, in-memory reflex trace, hot-loop contract, deterministic dry-run skeleton, bounded target-window frame-source, cheap metadata perception, recorded off-the-shelf local vision evidence, screenshot segmentation model-candidate catalog, deterministic controller, local-navigation dry-run, generic local-app task catalog/intent/dry-run adapter, guarded live-action smoke boundary, slow-planner sidecar, action-engine guardrail, latency-report, planner-hint contract, model-registry/router, OpenAI and Ollama-compatible planner adapters, memory, replay/eval, target-metadata, single-screenshot artifact, read-only Accessibility snapshot, and manual capture orchestration foundation only. It does not run live vision models or OCR over captured pixels, ship a default OS input backend, perform Accessibility actions, provide a manual capture UI, persist high-volume reflex traces to disk, provide continuous streaming capture, or make model calls required for reflex ticks.
## Technical Guidelines
@@ -93,7 +95,7 @@ This is a coordination, in-memory reflex trace, hot-loop contract, deterministic
- Keep reflex frame buffers at queue depth 1. Dropped frames are expected under pressure and should be counted.
- Keep target-window reflex frames bounded by caller-provided frame count until a streaming capture loop exists.
- Keep manual screenshot artifacts and high-resolution planner snapshots separate from reflex frames. The reflex frame source should not encode PNG/JPEG or write screenshot artifacts.
-- Keep cheap perception deterministic and compact until real pixel/model adapters exist. Perception may summarize fixture metadata or recorded off-the-shelf detector/template/OCR/segmentation evidence, but controllers must only see typed signals, world state, and action affordances.
+- Keep cheap perception deterministic and compact until real pixel/model adapters exist. Perception may summarize fixture metadata, recorded off-the-shelf detector/template/OCR/segmentation evidence, or model-candidate catalog choices, but controllers must only see typed signals, world state, and action affordances.
- Keep controller fallback explicit. Low confidence, stale signals, missing affordances, and missing signals should produce traceable `wait` or `observe` actions, not silent no-ops.
- Keep every chosen controller action trace-linked with action id, state id, frame id, policy name, confidence, rationale, fallback metadata, and any compact source-evidence metadata needed to explain the rule.
- Keep action-engine commands typed and replayable. Guardrails must run before live input and record permission, focus, rate-limit, hold-duration, release, backend, issued time, backend completion time, and execution status. Live held-input tracking starts only after the backend reports execution.
@@ -101,7 +103,7 @@ This is a coordination, in-memory reflex trace, hot-loop contract, deterministic
- Use monotonic timestamps for latency math. Wall-clock timestamps are for human labels and trace correlation only.
- Use latency reports for any p50/p95/p99 claim. Reports should include dropped frames, stale actions, tick rates, and worst traces.
- Keep local-navigation decisions typed and side-effect free until the guarded live-action slice. Metadata projectors may use window, browser-tab, and Accessibility facts when available, but controllers should emit semantic actions only.
-- Keep deterministic task intents separate from planner hints. A supported local command should parse to `TaskIntent` from local app-task definitions without a model call; slow planner output may only help ambiguous parsing, app-knowledge lookup, or recovery after validation.
+- Keep local-model task intents separate from planner hints. A supported local command should first parse to a validated `TaskIntent` through the local Ollama-compatible command parser; deterministic parsing is only a fallback/validator path, and slow planner output may only help app-knowledge lookup or recovery after validation.
- Keep local-app task adapter output inspectable before live control. Dry-run steps should show the normalized entities, target app identity, observation boundary, guarded command templates, and verification status before any injected backend is allowed to type or click.
- Prefer Accessibility and metadata for app observation. When visual interpretation is needed, route bounded screenshot/crop context to a local model UI-understanding path before introducing OCR-specific plumbing; OCR remains an optional measured adapter, not the default fallback.
- Treat planner hints as validated, expiring advice. Controllers may use the latest valid hint, but planner output must never become direct input.
@@ -123,7 +125,7 @@ From `apps/Donkey/`:
swift test
```
-The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, reflex trace latency math, bounded in-memory reflex trace retention, reflex event publication, hot-loop contract Codable round trips, coordinate conversion, stale-signal marking, deterministic dry-run trace publication, queue-depth-1 dropped-frame counting, bounded target-window frame capture, target-frame safety and overlap refusal, target-frame no-artifact/no-encoding metadata, cheap perception signal projection, recorded off-the-shelf vision evidence projection, controller confidence/staleness fallback, controller p95 replay timing under 20ms, local-navigation metadata projection and action selection, local-navigation browser-tab metadata projection, loop-integrated local-navigation dry-run action selection, deterministic local-app task parsing and alias expansion, local-app catalog resolution and app availability checks, local-app navigation request construction, generic dry-run step projection, guarded keyboard command templates, observed visible-text verification, guarded local-navigation live-smoke gating and trace evidence, abort/timeout release traces, slow-planner trigger/snapshot/validated-hint publication, planner-latency isolation from reflex reports, action-engine permission/focus/rate/hold/release guardrails, latency report percentiles and replay benchmark formatting, planner hint validation/expiry/latest-selection, model registry routing, OpenAI Responses request shaping and failure handling, memory approval/storage/list/delete/context snapshots, replay/eval metric aggregation and model update checklist fields, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, candidate-list label snapshots, screenshot artifact metadata, bounded Accessibility serialization, missing Accessibility trust partial events, unsafe target refusal, overlap-sensitive capture refusal, manual capture event ordering through persisted coordinator events, and debug launch-argument parsing/formatting.
+The runtime tests should cover lifecycle ordering, abort and timeout safety, latest-session queue drops, tool permission denial, event-store ordering, context compaction, reflex trace latency math, bounded in-memory reflex trace retention, reflex event publication, hot-loop contract Codable round trips, coordinate conversion, stale-signal marking, deterministic dry-run trace publication, queue-depth-1 dropped-frame counting, bounded target-window frame capture, target-frame safety and overlap refusal, target-frame no-artifact/no-encoding metadata, cheap perception signal projection, recorded off-the-shelf vision evidence projection, screenshot segmentation model-candidate selection, controller confidence/staleness fallback, controller p95 replay timing under 20ms, local-navigation metadata projection and action selection, local-navigation browser-tab metadata projection, loop-integrated local-navigation dry-run action selection, local-model task intent request shaping and validation, deterministic local-app task parsing fallback and alias expansion, local-app catalog resolution and app availability checks, local-app navigation request construction, generic dry-run step projection, guarded keyboard command templates, observed visible-text verification, guarded local-navigation live-smoke gating and trace evidence, abort/timeout release traces, slow-planner trigger/snapshot/validated-hint publication, planner-latency isolation from reflex reports, action-engine permission/focus/rate/hold/release guardrails, latency report percentiles and replay benchmark formatting, planner hint validation/expiry/latest-selection, model registry routing, OpenAI Responses request shaping and failure handling, memory approval/storage/list/delete/context snapshots, replay/eval metric aggregation and model update checklist fields, artifact path validation, trace folder layout, JSONL event persistence, summary updates, deterministic window resolver behavior through fixture providers, candidate-list label snapshots, screenshot artifact metadata, bounded Accessibility serialization, missing Accessibility trust partial events, unsafe target refusal, overlap-sensitive capture refusal, manual capture event ordering through persisted coordinator events, and debug launch-argument parsing/formatting.
Manual smoke commands:
@@ -160,6 +162,7 @@ Remaining live verification is environment-dependent. On May 16, 2026, iPhone Mi
- Local-app task catalog resolution and built-in benchmark definitions live in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift`.
- Deterministic local-app task parsing lives in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskIntentParser.swift`.
- Generic local-app dry-run adapter and guarded keyboard command templates live in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskAdapter.swift`.
+- Ollama-compatible local task-intent parsing lives in `apps/Donkey/Sources/DonkeyAI/OllamaTaskIntentAdapter.swift`.
- Slow-planner sidecar triggers, snapshots, validated hint bus, and hint-aware controller wrapper live in `apps/Donkey/Sources/DonkeyRuntime/SlowPlannerSidecar.swift`.
- AI model registry and routing live in `apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift`.
- The OpenAI Responses planner-hint adapter lives in `apps/Donkey/Sources/DonkeyAI/OpenAIPlannerHintAdapter.swift`.
diff --git a/plans/19-ai-harness.md b/plans/19-ai-harness.md
index 5696ee12..e3dccd0d 100644
--- a/plans/19-ai-harness.md
+++ b/plans/19-ai-harness.md
@@ -347,7 +347,7 @@ Do not hardcode one model everywhere. Assign models by role.
| Role | Default Candidate | Use |
| --- | --- | --- |
-| `intent_local` | deterministic parser, then small local model if needed | common command-to-intent parsing before local app execution |
+| `intent_local` | small local structured-output model, with deterministic parser as fallback/validator | common command-to-intent parsing before local app execution |
| `planner_default` | `gpt-5.4-mini` | routine slow planning, recovery hints, target reasoning |
| `planner_strong` | `gpt-5.5` | hard recovery, unfamiliar screens, complex strategy, plan generation |
| `planner_deep_eval` | `gpt-5.5-pro` | offline trace critique or high-value evaluation only |
@@ -366,11 +366,11 @@ Current OpenAI docs list GPT-5.5 as the flagship model for complex coding/profes
Route by job type, risk, latency tolerance, and failure history.
```text
-if deterministic intent parser can resolve the command:
- skip model call
+if job is common app command parsing:
+ prefer intent_local with a strict timeout and validate output against app-task definitions
-if job is common app intent disambiguation and local model is available:
- prefer intent_local or planner_local with a strict timeout
+if intent_local is unavailable or invalid:
+ use deterministic parser only as fallback for known commands
if job is hot_path:
reject remote model call
diff --git a/plans/20-off-the-shelf-run-loop.md b/plans/20-off-the-shelf-run-loop.md
index db5d3888..8f832308 100644
--- a/plans/20-off-the-shelf-run-loop.md
+++ b/plans/20-off-the-shelf-run-loop.md
@@ -1,6 +1,6 @@
# Off-The-Shelf Run Loop
-> Active status: not complete. The current repo supports metadata-only local-navigation dry-run scaffolding, generic local-app task catalog parsing/adaptation, target-app availability checks, and guarded live-action smoke, but not a live fast-navigation agent for a concrete command such as "show me the weather for SF".
+> Active status: not complete. The current repo supports metadata-only local-navigation dry-run scaffolding, generic local-app task catalog parsing/adaptation, local-model command parsing, target-app availability checks, and guarded live-action smoke, but not a live fast-navigation agent for a concrete command such as "show me the weather for SF".
## Goal
@@ -36,7 +36,7 @@ Do not build a custom model pipeline for the first version.
The first version should prove:
-- command-to-intent parsing is reliable for common tasks
+- local-model command-to-intent parsing is reliable for common tasks and validated against known app-task definitions
- macOS app launch/focus is reliable
- Accessibility/window metadata can extract useful app state
- local visual fallback is available only when Accessibility and metadata are insufficient
@@ -51,7 +51,8 @@ The first version should prove:
Use existing, swappable components:
-- deterministic intent parser for common local commands using app-task definitions
+- local-model command parser for common local commands using app-task definitions
+- deterministic parser only as fallback, validator, and test scaffold
- installed-app and task-knowledge lookup for target app identity, workflows, controls, and verification rules
- small local model or planner hint only for ambiguous command parsing
- target/task adapters for app-specific workflows
@@ -282,7 +283,7 @@ Good jobs:
- lane markers
- minimap markers
-Use current Ultralytics YOLO-family nano/small models as candidates. The exact model should be selected by export support, license, latency, and whether the built-in labels are useful. As of current Ultralytics docs, YOLO26 is the newest line, YOLO11 is a stable modern line, and YOLOv8 remains widely supported.
+Use current Ultralytics YOLO-family nano/small models as candidates. The exact model should be selected by export support, license, latency, and whether the built-in labels are useful. As of the official Ultralytics docs checked on May 17, 2026, YOLO26 is the latest line, YOLO11 is a stable modern line, and YOLOv8 remains widely supported. The current screenshot segmentation catalog candidate is `yolo26n-seg.pt`, and it should run on bounded crops before any full-screenshot or live-control use.
### Segment Anything When Needed
@@ -451,7 +452,7 @@ Good follow-on tasks:
Suggested first stack:
```text
-Intent: deterministic parser with local-model fallback for ambiguity
+Intent: local-model parser with deterministic fallback/validation
App control: NSWorkspace/LaunchServices activation
Observation: Accessibility snapshot first, local model UI understanding over bounded screenshot/crop fallback
Rules: deterministic local-app task state machine
@@ -463,7 +464,7 @@ Runtime: native Swift coordinator and trace pipeline
## Rollout
1. Define generic `TaskIntent`, target-app, entity, workflow-step, observation, and verification contracts.
-2. Add deterministic parsing from local app-task definitions, including aliases such as `SF -> San Francisco` in benchmark data.
+2. Add local-model command parsing from local app-task definitions, including aliases such as `SF -> San Francisco` in benchmark data, with deterministic parsing kept as fallback/validation.
3. Add installed-app and app-task knowledge lookup for target app identity, workflows, controls, and verification rules.
4. Define generic task-state fields and terminal states.
5. Extend the generic local-app task adapter from dry-run semantic actions to guarded-live orchestration.
@@ -507,10 +508,11 @@ The runtime foundation now supports a product-shaped local-navigation slice of t
- p50/p95/p99 latency reports across capture, preprocess, model, perception, state update, controller decision, action projection, and input stages
- action-engine permission, focus, rate, hold-duration, release, and backend-execution guardrails
- guarded live-action smoke through an injected backend only after dry-run latency evidence, explicit input policy allowance, and focus guard success
-- generic local-app task catalog, intent contracts, built-in benchmark definition, deterministic parsing, dry-run workflow-step projection, guarded keyboard command templates, and visible-text verification
+- generic local-app task catalog, intent contracts, built-in benchmark definition, local-model command parsing, deterministic fallback parsing, dry-run workflow-step projection, guarded keyboard command templates, and visible-text verification
+- screenshot segmentation model-candidate metadata for Ultralytics YOLO26 nano segmentation (`yolo26n-seg.pt`)
- optional slow-planner sidecar that publishes only validated hints without blocking reflex latency
-This is still not the full off-the-shelf vision stack and must not be treated as completion. It can replay and trace compact local vision evidence, but it does not ship live local detector/local-model/OCR/segmentation adapters over captured pixels, continuous streaming capture, a default OS input backend, high-volume persisted replay traces, or target-specific visual calibration.
+This is still not the full off-the-shelf vision stack and must not be treated as completion. It can replay and trace compact local vision evidence and name a current YOLO segmentation candidate, but it does not ship live local detector/local-model/OCR/segmentation adapters over captured pixels, continuous streaming capture, a default OS input backend, high-volume persisted replay traces, or target-specific visual calibration.
## Required Before This Plan Is Done
@@ -518,6 +520,7 @@ This is still not the full off-the-shelf vision stack and must not be treated as
- Prove fast local navigation from parsed intent, local app observation, deterministic controller state, and guarded live input, not remote planning.
- Add a default narrow macOS app-control backend for launch/focus/type/select/verify with focus guard and emergency release.
- Add result verification through Accessibility or local model UI-understanding fallback, with OCR only if a narrow benchmark justifies it.
+- Add measured YOLO26 screenshot/crop segmentation inference for visual fallback, including export/runtime choice, crop size, mask quality, and p95 latency.
- Add continuous streaming capture once queue-depth, stale-result, and trace sinks are ready for longer sessions.
- Add durable high-volume replay trace persistence and target-specific benchmark baselines.
- Keep local model UI understanding, segmentation, and OCR optional in the live path until each has cropped, measured, target-specific evidence.
@@ -525,6 +528,8 @@ This is still not the full off-the-shelf vision stack and must not be treated as
## Where To Look
- Ultralytics supported models: https://docs.ultralytics.com/models/
+- Ultralytics YOLO26 model docs: https://docs.ultralytics.com/models/yolo26/
+- Ultralytics segmentation task docs: https://docs.ultralytics.com/tasks/segment/
- YOLO11 model card: https://huggingface.co/Ultralytics/YOLO11
- Segment Anything repository: https://github.com/facebookresearch/segment-anything
- SAM2 repository: https://github.com/facebookresearch/sam2
diff --git a/plans/master-plan.md b/plans/master-plan.md
index 3592a19e..741b03e4 100644
--- a/plans/master-plan.md
+++ b/plans/master-plan.md
@@ -56,9 +56,9 @@ The normal Weather benchmark path should work without a remote model call. A tin
## Supported Boundary
- Runtime shell: minimal run coordination, ordered events, bounded context assembly, local run artifacts, manual target context capture, in-memory reflex trace retention, and stage-split latency reports are supported.
-- Fast navigation hot path: typed frame/world-state/action contracts, deterministic dry-run loop, bounded target-window frame source, cheap metadata perception, recorded off-the-shelf detector/template/OCR/segmentation evidence projection, swappable world-state projection, deterministic controller, loop-integrated metadata-only local-navigation dry-run action selection, optional caller-supplied browser-tab metadata, dry-run action projection, generic local-app task intent contracts, data-driven task definitions, deterministic parsing with entity alias expansion, catalog command resolution, target-app availability checks, generic dry-run task adaptation, local-navigation request construction, step projection, guarded keyboard command templates, visible-text verification, and built-in Weather benchmark data are supported. This is not yet a live fast-navigation agent: there is no default app launch/focus/type backend, no Accessibility action execution, no live local-model UI-understanding fallback, and no verified live command-to-result loop.
+- Fast navigation hot path: typed frame/world-state/action contracts, deterministic dry-run loop, bounded target-window frame source, cheap metadata perception, recorded off-the-shelf detector/template/OCR/segmentation evidence projection, screenshot segmentation model-candidate catalog with Ultralytics YOLO26 nano segmentation (`yolo26n-seg.pt`), swappable world-state projection, deterministic controller, loop-integrated metadata-only local-navigation dry-run action selection, optional caller-supplied browser-tab metadata, dry-run action projection, generic local-app task intent contracts, data-driven task definitions, Ollama-compatible local-model command parsing to validated `TaskIntent`, deterministic parsing as fallback/validator, catalog command resolution, target-app availability checks, generic dry-run task adaptation, local-navigation request construction, step projection, guarded keyboard command templates, visible-text verification, and built-in Weather benchmark data are supported. This is not yet a live fast-navigation agent: there is no default app launch/focus/type backend, no Accessibility action execution, no live local-model UI-understanding fallback, no live YOLO screenshot segmentation runner, and no verified live command-to-result loop.
- Safety boundary: action-engine command contracts, permission/focus/rate/hold/release guardrails, guarded live-action smoke with an injected backend, and replayable command traces are supported before any default OS input or Accessibility-action backend exists.
-- Slow AI boundary: structured planner hints, validation/expiry/latest-valid selection, loop-adjacent slow-planner trigger/snapshot sidecar, model registry/router, OpenAI Responses and Ollama-compatible planner adapters, provider-backed local/online planner fallback, source-linked memory, and replay/eval scaffolding are supported as optional sidecar pieces. This is not yet the complete AI harness because semantic retrieval, redaction, aggregate model observability, and provider-decoded memory write proposals remain active.
+- Slow AI boundary: local-model task-intent parsing, structured planner hints, validation/expiry/latest-valid selection, loop-adjacent slow-planner trigger/snapshot sidecar, model registry/router, OpenAI Responses and Ollama-compatible planner adapters, provider-backed local/online planner fallback, source-linked memory, and replay/eval scaffolding are supported as optional sidecar pieces. This is not yet the complete AI harness because semantic retrieval, redaction, aggregate model observability, live local visual UI understanding, and provider-decoded memory write proposals remain active.
- Source of truth: detailed supported behavior lives in `docs/guides/minimal-run-coordinator.md`; active unfinished work lives in this plan and its primary/supporting plans.
## Non-Negotiable Rules
@@ -81,18 +81,19 @@ Recent commits completed these pieces:
- `0e21088`: OpenAI Responses adapter, planner hint contracts, model registry/router scaffolding.
- `9bebfbb`: slow-planner sidecar trigger/snapshot/hint bus and guarded live-action smoke boundary.
- recent slice: Ollama-compatible local planner adapter, provider-backed local/online slow planner fallback, and explicit slow-planner completion tests.
-- current slice: generic local-app task catalog, intent/parser, app availability check, and dry-run adapter boundary, with Weather lookup represented as built-in benchmark data.
+- current slice: generic local-app task catalog, local-model command parser, deterministic fallback parser, app availability check, and dry-run adapter boundary, with Weather lookup represented as built-in benchmark data.
- `d6e48c9`: archived plans, which was premature for this milestone.
-The code now includes the first generic local-app task catalog, deterministic intent/parser, app availability check, and dry-run adapter boundary. It does not yet include default app launch/focus/type execution, Accessibility action execution, live local-model UI understanding over bounded screenshots/crops, live result verification, semantic memory retrieval, remote-input redaction hooks, aggregate model observability, or provider-decoded memory write proposals.
+The code now includes the first generic local-app task catalog, Ollama-compatible local-model command parser, deterministic fallback parser, app availability check, dry-run adapter boundary, and YOLO26 screenshot segmentation model-candidate metadata. It does not yet include default app launch/focus/type execution, Accessibility action execution, live local-model UI understanding over bounded screenshots/crops, live YOLO screenshot segmentation inference, live result verification, semantic memory retrieval, remote-input redaction hooks, aggregate model observability, or provider-decoded memory write proposals.
## What Should Be Done Next
1. Extend the generic local-app task adapter from dry-run projection to guarded-live orchestration: launch/focus the target app, observe app state, find the needed control, enter normalized entities, submit/select, and verify the requested result.
2. Add the default local action backend needed for this narrow first benchmark: app launch/activation plus guarded keyboard typing/clicking or Accessibility actions, with emergency release and focus checks.
3. Add a local model UI-understanding fallback for bounded screenshot/crop context when Accessibility and metadata are insufficient. Prefer this before OCR-specific extraction; OCR can remain a measured optional adapter.
-4. Add benchmark/reporting evidence for command-to-result latency, local navigation/action latency, verification confidence, and comparison against manual/chat-style workflows.
-5. Keep the current dry-run/guarded-live safety boundary: local or online LLM output can only become validated intent, task definitions, app-knowledge updates, observation summaries, or planner hints, never direct input.
+4. Add a measured local screenshot segmentation runner for the YOLO26 candidate only after choosing export/runtime format and crop size; keep it outside live control until p95 latency and mask quality are recorded.
+5. Add benchmark/reporting evidence for command-to-result latency, local navigation/action latency, verification confidence, visual fallback latency, and comparison against manual/chat-style workflows.
+6. Keep the current dry-run/guarded-live safety boundary: local or online LLM output can only become validated intent, task definitions, app-knowledge updates, observation summaries, or planner hints, never direct input.
## Completion Gates