Open source CapCut alternative.
TypeScript
Make generic harness planning canonical
David Le6eff03732d7c
diff --git a/AGENTS.md b/AGENTS.mdindex 61f1237a..b43b7b2f 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -36,6 +36,7 @@ Before changing `site/` UI, routes, API handlers, or data access patterns:- Update guides in `docs/guides/` only for major features or durable supported-behavior changes. Do not update guide docs for small styling tweaks, layout adjustments, copy changes, or implementation-only refactors.- When work completes a master-plan slice, update the master plan's supported/current-boundary language and next steps in the same change.- Keep guides explanatory. They should teach what the system is, how it works, and which boundaries matter; do not turn guides into feature inventories, implementation logs, duplicated code, or long file lists.+- Optimize guides for readability: use plain language, short sections, and only the detail a maintainer needs to understand the supported boundary. Prefer trimming outdated or repetitive detail over adding more paragraphs.- Keep guide source entrypoints short and readable. Do not write exhaustive file inventories. Prefer a small maintainer map by subsystem or one to seven high-signal paths, and link to a source path only when it gives someone a clear place to start.- Build forward by default. Prefer updating callers and contracts to the new supported shape instead of preserving old compatibility paths; ask before adding or keeping backwards-compatibility shims.- This is an open source project. Stay alert for security concerns, and never commit PII, API keys, tokens, credentials, private config, or other secrets.diff --git a/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift b/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swiftindex df3ec8fa..c2d74fe1 100644--- a/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift+++ b/apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift@@ -767,7 +767,7 @@ public struct LocalGenerateTaskIntentAdapter: TaskIntentParsingAdapter {}public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {- public static let schemaID = "task_intent_v1"+ public static let schemaID = "generic_harness_planning"public var router: AIModelRouterpublic var configuration: DonkeyBackendInferenceConfiguration?@@ -840,7 +840,7 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {)}- guard let intent = try TaskIntentWireCodec.decodeIntent(+ guard let intent = try TaskIntentWireCodec.decodeHostedPlanningIntent(outputText,definitions: request.taskDefinitions,originalCommand: request.command,@@ -854,7 +854,7 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {"provider": "donkeyBackend","privacy.store": "false"]) { current, _ in current }- guard let noTaskMetadata = try? TaskIntentWireCodec.noTaskMetadata(+ guard let noTaskMetadata = try? TaskIntentWireCodec.hostedPlanningNoTaskMetadata(outputText,parserName: "hosted-responses-v1") else {@@ -929,7 +929,7 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {"type": .string("json_schema"),"name": .string(Self.schemaID),"strict": .bool(true),- "schema": Self.jsonValue(TaskIntentWireCodec.jsonSchema(taskDefinitions: adapterRequest.taskDefinitions))+ "schema": Self.jsonValue(TaskIntentWireCodec.genericHarnessPlanningJsonSchema(taskDefinitions: adapterRequest.taskDefinitions))])],metadata: [@@ -960,26 +960,31 @@ public struct HostedTaskIntentParsingAdapter: TaskIntentParsingAdapter {private static let instructions = ["Decide whether the user is asking Donkey to run one of the provided local app task definitions.",- "Return strict JSON only.",+ "Return strict JSON only using the generic harness planning schema.","First decide whether Command is an executable local-app task or a conversation turn.","Executable local-app task means all three are clear: action, destination or target app/item, and enough payload to execute safely.",- "If Command is a greeting, conversation, question, malformed request, or lacks a real executable payload, return taskType \"none\", targetAppName \"none\", empty entities and normalizedEntities, confidence 0, needsConfirmation false, actionPlan.tools empty, and metadata.responseMode \"conversation\" with metadata.assistantResponse containing a brief natural-language reply.",- "For supported actions, choose only a provided taskType and target app. Fill entities and normalizedEntities with the concrete values needed by required entity rules.",+ "Always fill structuredIntent, ambiguityRisk, contextNeeds, planSteps, verificationCriteria, fallbacks, clarificationPolicy, and metadata.",+ "If Command is a greeting, conversation, question, malformed request, or lacks a real executable payload, set structuredIntent.route conversation, taskType \"none\", targetAppName \"none\", empty entities and normalizedEntities, confidence 0, needsConfirmation false, no planSteps with toolName values, and metadata.responseMode \"conversation\" with metadata.assistantResponse containing a brief natural-language reply.",+ "For supported actions, set structuredIntent.route localAppTask, choose only a provided taskType and target app, and fill entities and normalizedEntities with the concrete values needed by required entity rules.","Use the generic local_app_interaction task type for executable local app requests that need a model-planned app workflow and do not have a more specific provided task type.",+ "Use ambiguityRisk for safe, recoverable, or dangerous ambiguity. Dangerous ambiguity and missing required details must set structuredIntent.needsConfirmation true, ambiguityRisk.shouldAskBeforeActing true, and clarificationPolicy.shouldAsk true with a specific question.",+ "Use contextNeeds for app lookup, memory lookup, screen observation, element discovery, or skill lookup needed before or during execution.",+ "Use planSteps for the generic harness plan. Each executable step must name one allowed toolName, with inputEntity/controlID/focusKey filled when that tool needs them. Non-executable reasoning steps should use an empty toolName.",+ "Use verificationCriteria for what proves success, fallbacks for safe recovery choices, and clarificationPolicy for when Donkey should stop and ask.","For play/listen media requests, treat the turn as executable when a supported play_media capability or media_playback task is available; choose Music or another supported media app, set query to the requested artist/song/album, and do not downgrade it to conversation.","For every media playback request, include metadata.mediaSelection.kind. For explicit playable requests use explicit_song, explicit_album, or explicit_playlist. For vague artist-level media requests such as 'play some <artist>', do media-selection planning before returning JSON: pick one concrete playable song or album by that artist using model knowledge, set query to '<selected title> <artist>', and include metadata.mediaSelection.kind=representative_song or representative_album, metadata.mediaSelection.seed=<artist>, metadata.mediaSelection.selectedTitle=<title>, and metadata.mediaSelection.reason. Do not use an artist-only query unless the user explicitly asks to open the artist page, play an artist radio/station, or browse the artist.","If visible search results are provided in context for a media request, choose the highest-confidence playable Song row whose artist matches the requested seed; skip Artist, Playlist, category, and different-artist rows.","When App finder catalog JSON is non-empty and you use local_app_interaction, choose the target app only from a catalog entry with supportStatus supported and a matching capability. Set metadata.appFinder.selectedAppID to the exact appID, metadata.appFinder.selectedCapabilityID to the capability id, and metadata.appFinder.controlProfile to one declared control profile. Never select candidate, unsupported, or denied entries for execution.","For local_app_interaction, select the most likely local app, set targetAppName and entities.appName to the human app name, set entities.goal, and when text must be entered set entities.query plus normalizedEntities.query.",- "For local_app_interaction, fill 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.",- "When ui.setText is present, entities.query and normalizedEntities.query must be non-empty, actionPlan.inputEntity should usually be query, and actionPlan.controlID/focusKey should describe the guarded UI strategy.",+ "For local_app_interaction, fill planSteps with allowed toolName values only: app.openOrFocus, app.observe, ui.newDocument, ui.focusSearch, ui.focusAddressBar, ui.focusTextEntry, ui.setText, ui.pressReturn, app.verifyCommand, app.verifyVisibleText.",+ "When ui.setText is present, entities.query and normalizedEntities.query must be non-empty, the step inputEntity should usually be query, and controlID/focusKey should describe the guarded UI strategy.","For media playback when media_playback is provided, use taskType=media_playback, targetAppName=Music, entities.query=<concrete playable title plus artist>, normalizedEntities.query=<concrete playable title plus artist>, and metadata.mediaSelection.* when the user gave only an artist/genre/seed.",- "For media playback through generic local_app_interaction, targetAppName=Music, entities.appName=Music, entities.goal=play media, entities.query=<concrete playable title plus artist>, actionPlan.tools=[app.openOrFocus, app.observe, ui.focusSearch, ui.setText, ui.pressReturn, app.verifyCommand] with inputEntity=query, controlID=search, focusKey=Command+F, metadata.appFinder.selectedCapabilityID=play_media when selected from the app finder catalog, and metadata.mediaSelection.* when the user gave only an artist/genre/seed.",- "For website navigation, choose Safari or the user's browser, set query to the URL, and use ui.focusAddressBar, ui.setText, ui.pressReturn, app.verifyCommand.",- "For writing in Notes, choose Notes, make query the complete text to type, and use ui.newDocument, ui.setText, app.verifyCommand.",- "For spreadsheet or table creation, choose Numbers, put compact tab-separated table content in query, and use ui.newDocument, ui.setText, app.verifyCommand.",- "For every other task type, actionPlan.tools must be empty.",- "If no supported capability fits, choose taskType \"none\" with a helpful conversational assistantResponse rather than a generic local-action failure.",+ "For media playback through generic local_app_interaction, targetAppName=Music, entities.appName=Music, entities.goal=play media, entities.query=<concrete playable title plus artist>, planSteps should use app.openOrFocus, app.observe, ui.focusSearch, ui.setText, ui.pressReturn, app.verifyCommand with inputEntity=query, controlID=search, focusKey=Command+F, metadata.appFinder.selectedCapabilityID=play_media when selected from the app finder catalog, and metadata.mediaSelection.* when the user gave only an artist/genre/seed.",+ "For website navigation, choose Safari or the user's browser, set query to the URL, and use planSteps for ui.focusAddressBar, ui.setText, ui.pressReturn, app.verifyCommand.",+ "For writing in Notes, choose Notes, make query the complete text to type, and use planSteps for ui.newDocument, ui.setText, app.verifyCommand.",+ "For spreadsheet or table creation, choose Numbers, put compact tab-separated table content in query, and use planSteps for ui.newDocument, ui.setText, app.verifyCommand.",+ "For every other task type, planSteps should not contain executable toolName values.",+ "If no supported capability fits, set structuredIntent.route conversation and taskType \"none\" with a helpful conversational assistantResponse rather than a generic local-action failure.","Do not invent task types, unsupported entities, unsupported tools, app scripts, or direct input outside the schema."].joined(separator: " ")@@ -1313,6 +1318,160 @@ private enum TaskIntentWireCodec {]}+ static func genericHarnessPlanningJsonSchema(taskDefinitions: [LocalAppTaskDefinition]) -> [String: Any] {+ let allowsDynamicTargets = taskDefinitions.contains { definition in+ definition.metadata["dynamicTarget"] == "true"+ }+ let taskTypes = (Array(Set(taskDefinitions.map(\.taskType))) + ["none"]).sorted()+ let appNames = (Array(Set(taskDefinitions.map(\.targetApp.appName))) + ["none"]).sorted()+ let targetAppNameSchema: [String: Any] = allowsDynamicTargets+ ? ["type": "string"]+ : ["type": "string", "enum": appNames]+ let toolNames = [""] + LocalAppActionPlanTool.allCases.map(\.rawValue)+ let planStepSchema: [String: Any] = [+ "type": "object",+ "additionalProperties": false,+ "required": [+ "id",+ "summary",+ "toolName",+ "inputEntity",+ "controlID",+ "focusKey",+ "expectedObservation"+ ],+ "properties": [+ "id": ["type": "string"],+ "summary": ["type": "string"],+ "toolName": ["type": "string", "enum": toolNames],+ "inputEntity": ["type": "string"],+ "controlID": ["type": "string"],+ "focusKey": ["type": "string"],+ "expectedObservation": ["type": "string"]+ ]+ ]++ return [+ "type": "object",+ "additionalProperties": false,+ "required": [+ "schemaVersion",+ "structuredIntent",+ "ambiguityRisk",+ "contextNeeds",+ "planSteps",+ "verificationCriteria",+ "fallbacks",+ "clarificationPolicy",+ "metadata"+ ],+ "properties": [+ "schemaVersion": ["type": "string", "enum": ["generic_harness_planning"]],+ "structuredIntent": [+ "type": "object",+ "additionalProperties": false,+ "required": [+ "route",+ "goal",+ "taskType",+ "targetAppName",+ "entities",+ "normalizedEntities",+ "confidence",+ "needsConfirmation"+ ],+ "properties": [+ "route": [+ "type": "string",+ "enum": ["localAppTask", "conversation", "clarification"]+ ],+ "goal": ["type": "string"],+ "taskType": ["type": "string", "enum": taskTypes],+ "targetAppName": targetAppNameSchema,+ "entities": [+ "type": "object",+ "additionalProperties": ["type": "string"]+ ],+ "normalizedEntities": [+ "type": "object",+ "additionalProperties": ["type": "string"]+ ],+ "confidence": ["type": "number", "minimum": 0, "maximum": 1],+ "needsConfirmation": ["type": "boolean"]+ ]+ ],+ "ambiguityRisk": [+ "type": "object",+ "additionalProperties": false,+ "required": [+ "ambiguityClass",+ "riskLevel",+ "missingInformation",+ "shouldAskBeforeActing"+ ],+ "properties": [+ "ambiguityClass": [+ "type": "string",+ "enum": ["safe", "recoverable", "dangerous"]+ ],+ "riskLevel": [+ "type": "string",+ "enum": ["low", "medium", "high"]+ ],+ "missingInformation": [+ "type": "array",+ "maxItems": 8,+ "items": ["type": "string"]+ ],+ "shouldAskBeforeActing": ["type": "boolean"]+ ]+ ],+ "contextNeeds": [+ "type": "array",+ "maxItems": 8,+ "items": ["type": "string"]+ ],+ "planSteps": [+ "type": "array",+ "maxItems": 12,+ "items": planStepSchema+ ],+ "verificationCriteria": [+ "type": "array",+ "maxItems": 8,+ "items": ["type": "string"]+ ],+ "fallbacks": [+ "type": "array",+ "maxItems": 8,+ "items": ["type": "string"]+ ],+ "clarificationPolicy": [+ "type": "object",+ "additionalProperties": false,+ "required": [+ "shouldAsk",+ "questions",+ "policy"+ ],+ "properties": [+ "shouldAsk": ["type": "boolean"],+ "questions": [+ "type": "array",+ "maxItems": 4,+ "items": ["type": "string"]+ ],+ "policy": ["type": "string"]+ ]+ ],+ "metadata": [+ "type": "object",+ "additionalProperties": ["type": "string"]+ ]+ ]+ ]+ }+static func decodeIntent(_ outputText: String,definitions: [LocalAppTaskDefinition],@@ -1323,6 +1482,65 @@ private enum TaskIntentWireCodec {parserSource: TaskIntentParserSource = .localModel) throws -> TaskIntent? {let wire = try decodeWire(from: outputText)+ return try decodeIntent(+ from: wire,+ definitions: definitions,+ originalCommand: originalCommand,+ appFinderCatalog: appFinderCatalog,+ sourceModelCallID: sourceModelCallID,+ parserName: parserName,+ parserSource: parserSource+ )+ }++ static func decodeHostedPlanningIntent(+ _ outputText: String,+ definitions: [LocalAppTaskDefinition],+ originalCommand: String,+ appFinderCatalog: [LocalAppFinderCatalogEntry] = [],+ sourceModelCallID: String,+ parserName: String,+ parserSource: TaskIntentParserSource+ ) throws -> TaskIntent? {+ let planningWire = try decodeHostedPlanningWire(from: outputText)+ guard planningWire.structuredIntent.route == "localAppTask",+ planningWire.structuredIntent.taskType != "none"+ else {+ return nil+ }++ let wire = TaskIntentWire(+ taskType: planningWire.structuredIntent.taskType,+ targetAppName: planningWire.structuredIntent.targetAppName,+ entities: planningWire.structuredIntent.entities,+ normalizedEntities: planningWire.structuredIntent.normalizedEntities,+ confidence: planningWire.structuredIntent.confidence,+ needsConfirmation: planningWire.structuredIntent.needsConfirmation+ || planningWire.ambiguityRisk.shouldAskBeforeActing+ || planningWire.clarificationPolicy.shouldAsk,+ actionPlan: actionPlan(from: planningWire),+ metadata: hostedPlanningMetadata(from: planningWire)+ )+ return try decodeIntent(+ from: wire,+ definitions: definitions,+ originalCommand: originalCommand,+ appFinderCatalog: appFinderCatalog,+ sourceModelCallID: sourceModelCallID,+ parserName: parserName,+ parserSource: parserSource+ )+ }++ private static func decodeIntent(+ from wire: TaskIntentWire,+ definitions: [LocalAppTaskDefinition],+ originalCommand: String,+ appFinderCatalog: [LocalAppFinderCatalogEntry],+ sourceModelCallID: String,+ parserName: String,+ parserSource: TaskIntentParserSource+ ) throws -> TaskIntent? {if wire.taskType == "none" {return nil}@@ -1448,6 +1666,28 @@ private enum TaskIntentWireCodec {)}+ static func hostedPlanningNoTaskMetadata(+ _ outputText: String,+ parserName: String+ ) throws -> [String: String]? {+ let wire = try decodeHostedPlanningWire(from: outputText)+ guard wire.structuredIntent.route != "localAppTask"+ || wire.structuredIntent.taskType == "none"+ else {+ return nil+ }++ var metadata = hostedPlanningMetadata(from: wire)+ metadata["parser"] = parserName+ metadata["reason"] = nonEmpty(metadata["reason"]) ?? "noSupportedTaskIntent"+ metadata["responseMode"] = "conversation"+ metadata["assistantResponse"] = nonEmpty(metadata["assistantResponse"])+ ?? defaultConversationAssistantResponse+ metadata["taskType"] = "none"+ metadata["targetApp"] = wire.structuredIntent.targetAppName+ return metadata+ }+static func noTaskMetadata(_ outputText: String,parserName: String@@ -1487,6 +1727,27 @@ private enum TaskIntentWireCodec {)}+ private static func decodeHostedPlanningWire(from outputText: String) throws -> GenericHarnessPlanningWire {+ var lastError: Error?+ for candidate in jsonObjectCandidates(in: outputText) {+ do {+ return try JSONDecoder().decode(GenericHarnessPlanningWire.self, from: Data(candidate.utf8))+ } catch {+ lastError = error+ }+ }++ if let lastError {+ throw lastError+ }+ throw DecodingError.dataCorrupted(+ DecodingError.Context(+ codingPath: [],+ debugDescription: "No JSON object found in generic harness planning model output"+ )+ )+ }+private static func jsonObjectCandidates(in outputText: String) -> [String] {let trimmed = outputText.trimmingCharacters(in: .whitespacesAndNewlines)var candidates: [String] = trimmed.isEmpty ? [] : [trimmed]@@ -1529,6 +1790,80 @@ private enum TaskIntentWireCodec {return candidates.filter { seen.insert($0).inserted }}+ private static func actionPlan(from wire: GenericHarnessPlanningWire) -> LocalAppActionPlan {+ let tools = wire.planSteps.compactMap { step -> LocalAppActionPlanTool? in+ let toolName = step.toolName.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !toolName.isEmpty else { return nil }+ return LocalAppActionPlanTool(rawValue: toolName)+ }+ let inputEntity = firstNonEmpty(wire.planSteps.map(\.inputEntity)) ?? ""+ let controlID = firstNonEmpty(wire.planSteps.map(\.controlID)) ?? ""+ let focusKey = firstNonEmpty(wire.planSteps.map(\.focusKey)) ?? ""+ let verification: LocalAppActionPlanVerification = wire.planSteps.contains { step in+ step.toolName == LocalAppActionPlanTool.verifyVisibleText.rawValue+ } || wire.verificationCriteria.contains { criterion in+ criterion.localizedCaseInsensitiveContains("visible")+ } ? .visibleText : .commandAttempted++ return LocalAppActionPlan(+ tools: tools,+ inputEntity: inputEntity,+ controlID: controlID,+ focusKey: focusKey,+ verification: verification+ )+ }++ private static func hostedPlanningMetadata(from wire: GenericHarnessPlanningWire) -> [String: String] {+ var metadata = wire.metadata+ metadata["genericHarness.schemaVersion"] = wire.schemaVersion+ metadata["genericHarness.intent.route"] = wire.structuredIntent.route+ metadata["genericHarness.intent.goal"] = wire.structuredIntent.goal+ metadata["genericHarness.ambiguity.class"] = wire.ambiguityRisk.ambiguityClass+ metadata["genericHarness.risk.level"] = wire.ambiguityRisk.riskLevel+ metadata["genericHarness.shouldAskBeforeActing"] = String(wire.ambiguityRisk.shouldAskBeforeActing)+ metadata["genericHarness.missingInformationJSON"] = jsonString(wire.ambiguityRisk.missingInformation)+ metadata["genericHarness.contextNeedsJSON"] = jsonString(wire.contextNeeds)+ metadata["genericHarness.planStepsJSON"] = jsonString(+ wire.planSteps.map { step in+ [+ "id": step.id,+ "summary": step.summary,+ "toolName": step.toolName,+ "inputEntity": step.inputEntity,+ "controlID": step.controlID,+ "focusKey": step.focusKey,+ "expectedObservation": step.expectedObservation+ ]+ }+ )+ metadata["genericHarness.verificationCriteriaJSON"] = jsonString(wire.verificationCriteria)+ metadata["genericHarness.fallbacksJSON"] = jsonString(wire.fallbacks)+ metadata["genericHarness.clarification.shouldAsk"] = String(wire.clarificationPolicy.shouldAsk)+ metadata["genericHarness.clarification.questionsJSON"] = jsonString(wire.clarificationPolicy.questions)+ metadata["genericHarness.clarification.policy"] = wire.clarificationPolicy.policy+ return metadata+ }++ private static func jsonString(_ value: Any) -> String {+ guard JSONSerialization.isValidJSONObject(value),+ let data = try? JSONSerialization.data(+ withJSONObject: value,+ options: [.sortedKeys]+ ),+ let text = String(data: data, encoding: .utf8)+ else {+ return "[]"+ }+ return text+ }++ private static func firstNonEmpty(_ values: [String]) -> String? {+ values.first { value in+ !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ }+ }+private static func nonEmpty(_ value: String?) -> String? {let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""return trimmed.isEmpty ? nil : trimmed@@ -1947,6 +2282,52 @@ private enum TaskIntentWireCodec {}}+private struct GenericHarnessPlanningWire: Decodable {+ var schemaVersion: String+ var structuredIntent: GenericHarnessStructuredIntentWire+ var ambiguityRisk: GenericHarnessAmbiguityRiskWire+ var contextNeeds: [String]+ var planSteps: [GenericHarnessPlanStepWire]+ var verificationCriteria: [String]+ var fallbacks: [String]+ var clarificationPolicy: GenericHarnessClarificationPolicyWire+ var metadata: [String: String]+}++private struct GenericHarnessStructuredIntentWire: Decodable {+ var route: String+ var goal: String+ var taskType: String+ var targetAppName: String+ var entities: [String: String]+ var normalizedEntities: [String: String]+ var confidence: Double+ var needsConfirmation: Bool+}++private struct GenericHarnessAmbiguityRiskWire: Decodable {+ var ambiguityClass: String+ var riskLevel: String+ var missingInformation: [String]+ var shouldAskBeforeActing: Bool+}++private struct GenericHarnessPlanStepWire: Decodable {+ var id: String+ var summary: String+ var toolName: String+ var inputEntity: String+ var controlID: String+ var focusKey: String+ var expectedObservation: String+}++private struct GenericHarnessClarificationPolicyWire: Decodable {+ var shouldAsk: Bool+ var questions: [String]+ var policy: String+}+private struct TaskIntentWire: Decodable {var taskType: Stringvar targetAppName: Stringdiff --git a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swiftindex 910704f0..2b37886d 100644--- a/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift+++ b/apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift@@ -143,9 +143,11 @@ public struct AppHarnessGenericLifecycle: Sendable {fallbackGoal: fallbackGoal)_ = await coordinator.updateIntent(taskID: taskID, intent: intent)+ let plannedStepMetadata = resolution.intent?.metadata ?? [:]+ let modelPlanSteps = Self.modelPlanningSteps(from: plannedStepMetadata)let plan = HarnessPlan(goal: intent.goal,- steps: [+ steps: modelPlanSteps + [HarnessPlanStep(id: "run-local-app-task",summary: "Run the resolved local app task through the generic harness executor.",@@ -182,14 +184,22 @@ public struct AppHarnessGenericLifecycle: Sendable {expectedObservation: "Verification records success criteria or evidence.")],- successCriteria: ["Resolved local app result is completed or handed to a user gate."],- fallbackPolicy: ["If execution needs review or missing detail, stop at the user gate."],- clarificationPolicy: ["Ask a specific follow-up question when the resolved task is incomplete."],+ successCriteria: Self.stringArrayMetadata(+ plannedStepMetadata["genericHarness.verificationCriteriaJSON"],+ fallback: ["Resolved local app result is completed or handed to a user gate."]+ ),+ fallbackPolicy: Self.stringArrayMetadata(+ plannedStepMetadata["genericHarness.fallbacksJSON"],+ fallback: ["If execution needs review or missing detail, stop at the user gate."]+ ),+ clarificationPolicy: Self.clarificationPolicy(from: plannedStepMetadata),confidence: intent.confidence,metadata: ["planner": "genericHarnessPointerPromptBridge","traceID": traceID,- "resolution.status": resolution.status.rawValue+ "resolution.status": resolution.status.rawValue,+ "modelPlan.stepCount": String(modelPlanSteps.count),+ "modelPlan.schemaVersion": plannedStepMetadata["genericHarness.schemaVersion"] ?? ""])_ = await coordinator.updatePlan(taskID: taskID, plan: plan)@@ -417,19 +427,33 @@ public struct AppHarnessGenericLifecycle: Sendable {targetApp.map { "in \($0)" }].compactMap { $0 }let goal = goalParts.isEmpty ? fallbackGoal : goalParts.joined(separator: " ")+ let metadata = resolution.intent?.metadata ?? [:]+ let modelGoal = metadata["genericHarness.intent.goal"]+ .flatMap { $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : $0 }let missingInformation: [String]if resolution.status == .needsConfirmation {- missingInformation = [resolution.metadata["reason"] ?? "more detail"]+ missingInformation = Self.stringArrayMetadata(+ metadata["genericHarness.missingInformationJSON"],+ fallback: [resolution.metadata["reason"] ?? "more detail"]+ )} else {- missingInformation = []+ missingInformation = Self.stringArrayMetadata(+ metadata["genericHarness.missingInformationJSON"],+ fallback: []+ )}return HarnessIntentAnalysis(- goal: goal,+ goal: modelGoal ?? goal,entities: resolution.intent?.normalizedEntities ?? resolution.intent?.entities ?? [:],- ambiguityClass: resolution.status == .needsConfirmation ? .recoverable : .safe,- riskLevel: .medium,+ ambiguityClass: HarnessAmbiguityClass(+ rawValue: metadata["genericHarness.ambiguity.class"] ?? ""+ ) ?? (resolution.status == .needsConfirmation ? .recoverable : .safe),+ riskLevel: HarnessRiskLevel(+ rawValue: metadata["genericHarness.risk.level"] ?? ""+ ) ?? .medium,missingInformation: missingInformation,- shouldAskBeforeActing: resolution.status == .needsConfirmation,+ shouldAskBeforeActing: metadata["genericHarness.shouldAskBeforeActing"] == "true"+ || resolution.status == .needsConfirmation,confidence: resolution.intent?.confidence ?? 0,metadata: ["resolution.status": resolution.status.rawValue,@@ -439,6 +463,64 @@ public struct AppHarnessGenericLifecycle: Sendable {].merging(resolution.metadata) { current, _ in current })}++ private static func modelPlanningSteps(from metadata: [String: String]) -> [HarnessPlanStep] {+ guard let text = metadata["genericHarness.planStepsJSON"],+ let data = text.data(using: .utf8),+ let values = try? JSONSerialization.jsonObject(with: data) as? [[String: String]]+ else {+ return []+ }++ return values.enumerated().map { index, value in+ let id = nonEmpty(value["id"]) ?? "model-plan-step-\(index + 1)"+ return HarnessPlanStep(+ id: "model-\(id)",+ summary: nonEmpty(value["summary"]) ?? "Model-planned harness step",+ toolCall: nil,+ expectedObservation: nonEmpty(value["expectedObservation"]),+ metadata: [+ "source": "hostedGenericHarnessPlanning",+ "toolName": value["toolName"] ?? "",+ "inputEntity": value["inputEntity"] ?? "",+ "controlID": value["controlID"] ?? "",+ "focusKey": value["focusKey"] ?? ""+ ]+ )+ }+ }++ private static func clarificationPolicy(from metadata: [String: String]) -> [String] {+ var policy = stringArrayMetadata(+ metadata["genericHarness.clarification.questionsJSON"],+ fallback: []+ )+ if let text = nonEmpty(metadata["genericHarness.clarification.policy"]) {+ policy.append(text)+ }+ return policy.isEmpty+ ? ["Ask a specific follow-up question when the resolved task is incomplete."]+ : policy+ }++ private static func stringArrayMetadata(+ _ text: String?,+ fallback: [String]+ ) -> [String] {+ guard let text,+ let data = text.data(using: .utf8),+ let values = try? JSONSerialization.jsonObject(with: data) as? [String]+ else {+ return fallback+ }+ let cleaned = values.compactMap(nonEmpty)+ return cleaned.isEmpty ? fallback : cleaned+ }++ private static func nonEmpty(_ value: String?) -> String? {+ let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""+ return trimmed.isEmpty ? nil : trimmed+ }}private extension HarnessThreadEventRole {diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swiftindex 23b0aa1d..89ea9488 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift@@ -503,7 +503,19 @@ struct AIHarnessAdapterTests {@Testfunc hostedTaskIntentAdapterUsesBackendResponsesProxy() async throws {let httpClient = FakeAIHTTPClient(- data: Data(#"{"output_text":"{\"taskType\":\"media_playback\",\"targetAppName\":\"Music\",\"entities\":{\"query\":\"Viva La Vida Coldplay\"},\"normalizedEntities\":{\"query\":\"Viva La Vida Coldplay\"},\"confidence\":0.91,\"needsConfirmation\":false,\"actionPlan\":{\"tools\":[],\"inputEntity\":\"\",\"controlID\":\"\",\"focusKey\":\"\",\"verification\":\"commandAttempted\"},\"metadata\":{\"source\":\"test\",\"mediaSelection.kind\":\"representative_song\",\"mediaSelection.seed\":\"Coldplay\",\"mediaSelection.selectedTitle\":\"Viva La Vida\",\"mediaSelection.reason\":\"User asked for Coldplay, so choose a concrete song.\"}}"}"#.utf8),+ data: responseData(+ outputText: hostedPlanningOutput(+ goal: "play Viva La Vida by Coldplay",+ taskType: "media_playback",+ targetAppName: "Music",+ entitiesJSON: #"{"query":"Viva La Vida Coldplay"}"#,+ normalizedEntitiesJSON: #"{"query":"Viva La Vida Coldplay"}"#,+ confidence: 0.91,+ verificationCriteriaJSON: #"["Playback command is attempted for the concrete selected song."]"#,+ fallbacksJSON: #"["Ask before playing if the selected media is ambiguous."]"#,+ metadataJSON: #"{"source":"test","mediaSelection.kind":"representative_song","mediaSelection.seed":"Coldplay","mediaSelection.selectedTitle":"Viva La Vida","mediaSelection.reason":"User asked for Coldplay, so choose a concrete song."}"#+ )+ ),statusCode: 200)let adapter = HostedTaskIntentParsingAdapter(@@ -536,6 +548,20 @@ struct AIHarnessAdapterTests {#expect(body["donkeyProvider"] == nil)let parameters = try #require(body["parameters"] as? [String: Any])let instructions = try #require(parameters["instructions"] as? String)+ let text = try #require(body["text"] as? [String: Any])+ let format = try #require(text["format"] as? [String: Any])+ #expect(format["name"] as? String == "generic_harness_planning")+ let schema = try #require(format["schema"] as? [String: Any])+ let properties = try #require(schema["properties"] as? [String: Any])+ #expect(properties["structuredIntent"] != nil)+ #expect(properties["ambiguityRisk"] != nil)+ #expect(properties["contextNeeds"] != nil)+ #expect(properties["planSteps"] != nil)+ #expect(properties["verificationCriteria"] != nil)+ #expect(properties["fallbacks"] != nil)+ #expect(properties["clarificationPolicy"] != nil)+ #expect(result.intent?.metadata["genericHarness.schemaVersion"] == "generic_harness_planning")+ #expect(result.intent?.metadata["genericHarness.intent.goal"] == "play Viva La Vida by Coldplay")#expect(instructions.contains("local_app_interaction"))#expect(instructions.contains("media playback"))#expect(instructions.contains("play/listen media requests"))@@ -548,9 +574,14 @@ struct AIHarnessAdapterTests {func hostedTaskIntentAdapterPreservesNoTaskConversationResponse() async throws {let httpClient = FakeAIHTTPClient(data: responseData(- outputText: """- {"taskType":"none","targetAppName":"none","entities":{},"normalizedEntities":{},"confidence":0,"needsConfirmation":false,"actionPlan":{"tools":[],"inputEntity":"","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{"responseMode":"conversation","assistantResponse":"Hi there! What would you like to work on?"}}- """+ outputText: hostedPlanningOutput(+ route: "conversation",+ goal: "respond to greeting",+ taskType: "none",+ targetAppName: "none",+ confidence: 0,+ metadataJSON: #"{"responseMode":"conversation","assistantResponse":"Hi there! What would you like to work on?"}"#+ )),statusCode: 200)@@ -578,6 +609,60 @@ struct AIHarnessAdapterTests {#expect(result.trace.metadata["provider"] == "donkeyBackend")}+ @Test+ func hostedTaskIntentAdapterMapsGenericPlanStepsToBridgeActionPlan() async throws {+ let httpClient = FakeAIHTTPClient(+ data: responseData(+ outputText: hostedPlanningOutput(+ goal: "open cnn.com in Safari",+ taskType: "local_app_interaction",+ targetAppName: "Safari",+ entitiesJSON: #"{"appName":"Safari","goal":"open requested website","query":"https://cnn.com"}"#,+ normalizedEntitiesJSON: #"{"appName":"Safari","goal":"open requested website","query":"https://cnn.com"}"#,+ confidence: 0.94,+ contextNeedsJSON: #"["app lookup","screen observation"]"#,+ planStepsJSON: """+ [{"id":"launch","summary":"Open or focus Safari.","toolName":"app.openOrFocus","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Safari is focused."},{"id":"focus-address","summary":"Focus the address bar.","toolName":"ui.focusAddressBar","inputEntity":"","controlID":"addressBar","focusKey":"Command+L","expectedObservation":"Address bar is ready."},{"id":"enter-url","summary":"Enter the requested URL.","toolName":"ui.setText","inputEntity":"query","controlID":"addressBar","focusKey":"","expectedObservation":"URL is entered."},{"id":"submit","summary":"Navigate to the URL.","toolName":"ui.pressReturn","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Navigation is attempted."},{"id":"verify","summary":"Verify the navigation command.","toolName":"app.verifyCommand","inputEntity":"","controlID":"","focusKey":"","expectedObservation":"Command attempt is recorded."}]+ """,+ verificationCriteriaJSON: #"["Navigation to the requested URL is attempted."]"#,+ fallbacksJSON: #"["Ask if the URL is missing or ambiguous."]"#,+ metadataJSON: #"{"source":"test"}"#+ )+ ),+ statusCode: 200+ )+ let adapter = HostedTaskIntentParsingAdapter(+ configuration: DonkeyBackendInferenceConfiguration(+ baseURL: URL(string: "https://donkey.example")!,+ clientID: "client-1"+ ),+ httpClient: httpClient+ )++ let result = await adapter.parseTaskIntent(+ TaskIntentAdapterRequest(+ command: "open cnn.com",+ taskDefinitions: LocalAppTaskDefinitionLoader.runtimeSeedDefinitions,+ sourceTraceID: "trace-hosted-plan-steps"+ )+ )++ #expect(result.intent?.taskType == "local_app_interaction")+ #expect(result.intent?.targetApp.appName == "Safari")+ #expect(result.intent?.actionPlan?.tools == [+ .openOrFocusApp,+ .focusAddressBar,+ .setText,+ .pressReturn,+ .verifyCommand+ ])+ #expect(result.intent?.actionPlan?.inputEntity == "query")+ #expect(result.intent?.actionPlan?.controlID == "addressBar")+ #expect(result.intent?.actionPlan?.focusKey == "Command+L")+ #expect(result.intent?.metadata["genericHarness.contextNeedsJSON"] == #"["app lookup","screen observation"]"#)+ #expect(result.intent?.metadata["genericHarness.fallbacksJSON"] == #"["Ask if the URL is missing or ambiguous."]"#)+ }+@Testfunc hostedFollowUpResolverLetsBackendSelectResponsesModel() async throws {let httpClient = FakeAIHTTPClient(@@ -1294,9 +1379,14 @@ struct AIHarnessAdapterTests {),httpClient: FakeAIHTTPClient(data: responseData(- outputText: """- {"taskType":"none","targetAppName":"none","entities":{},"normalizedEntities":{},"confidence":0,"needsConfirmation":false,"actionPlan":{"tools":[],"inputEntity":"","controlID":"","focusKey":"","verification":"commandAttempted"},"metadata":{"responseMode":"conversation","assistantResponse":"Hi there! What would you like to work on?"}}- """+ outputText: hostedPlanningOutput(+ route: "conversation",+ goal: "respond to greeting",+ taskType: "none",+ targetAppName: "none",+ confidence: 0,+ metadataJSON: #"{"responseMode":"conversation","assistantResponse":"Hi there! What would you like to work on?"}"#+ )),statusCode: 200)@@ -2027,6 +2117,33 @@ struct AIHarnessAdapterTests {return Data("{\"id\":\"resp-1\",\"output_text\":\"\(escaped)\"}".utf8)}+ private func hostedPlanningOutput(+ route: String = "localAppTask",+ goal: String,+ taskType: String,+ targetAppName: String,+ entitiesJSON: String = "{}",+ normalizedEntitiesJSON: String = "{}",+ confidence: Double,+ needsConfirmation: Bool = false,+ ambiguityClass: String = "safe",+ riskLevel: String = "low",+ missingInformationJSON: String = "[]",+ shouldAskBeforeActing: Bool = false,+ contextNeedsJSON: String = "[]",+ planStepsJSON: String = "[]",+ verificationCriteriaJSON: String = "[]",+ fallbacksJSON: String = "[]",+ clarificationShouldAsk: Bool = false,+ clarificationQuestionsJSON: String = "[]",+ clarificationPolicy: String = "Ask only when required information is missing.",+ metadataJSON: String = "{}"+ ) -> String {+ """+ {"schemaVersion":"generic_harness_planning","structuredIntent":{"route":"\(route)","goal":"\(goal)","taskType":"\(taskType)","targetAppName":"\(targetAppName)","entities":\(entitiesJSON),"normalizedEntities":\(normalizedEntitiesJSON),"confidence":\(confidence),"needsConfirmation":\(needsConfirmation)},"ambiguityRisk":{"ambiguityClass":"\(ambiguityClass)","riskLevel":"\(riskLevel)","missingInformation":\(missingInformationJSON),"shouldAskBeforeActing":\(shouldAskBeforeActing)},"contextNeeds":\(contextNeedsJSON),"planSteps":\(planStepsJSON),"verificationCriteria":\(verificationCriteriaJSON),"fallbacks":\(fallbacksJSON),"clarificationPolicy":{"shouldAsk":\(clarificationShouldAsk),"questions":\(clarificationQuestionsJSON),"policy":"\(clarificationPolicy)"},"metadata":\(metadataJSON)}+ """+ }+private func localGenerateResponseData(response: String) -> Data {let escaped = response.replacingOccurrences(of: "\\", with: "\\\\")diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swiftindex cbe5f137..2f55dec7 100644--- a/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/GenericHarnessTests.swift@@ -483,6 +483,69 @@ struct GenericHarnessTests {#expect(result?.toolResult?.status == .waitingForUser)}+ @Test+ func pointerPromptLifecycleUsesHostedGenericPlanningMetadata() async {+ let store = InMemoryHarnessThreadStore()+ let coordinator = HarnessTaskCoordinator()+ let lifecycle = AppHarnessGenericLifecycle(threadStore: store, coordinator: coordinator)+ let task = await coordinator.createTask(+ id: "pointer-task-hosted-plan",+ threadID: "thread-hosted-plan",+ goal: "open a site"+ )+ let intent = TaskIntent(+ intentID: "intent-hosted-plan",+ taskType: "local_app_interaction",+ targetApp: LocalAppTarget(appName: "Safari"),+ entities: ["query": "https://example.org"],+ normalizedEntities: ["query": "https://example.org"],+ confidence: 0.92,+ parserSource: .onlineModel,+ metadata: [+ "genericHarness.schemaVersion": "generic_harness_planning",+ "genericHarness.intent.goal": "open example.org in Safari",+ "genericHarness.ambiguity.class": "safe",+ "genericHarness.risk.level": "low",+ "genericHarness.shouldAskBeforeActing": "false",+ "genericHarness.missingInformationJSON": "[]",+ "genericHarness.planStepsJSON": """+ [{"controlID":"addressBar","expectedObservation":"Address bar is focused.","focusKey":"Command+L","id":"focus-address","inputEntity":"","summary":"Focus the browser address bar.","toolName":"ui.focusAddressBar"},{"controlID":"addressBar","expectedObservation":"Requested URL is entered.","focusKey":"","id":"enter-url","inputEntity":"query","summary":"Enter the requested URL.","toolName":"ui.setText"}]+ """,+ "genericHarness.verificationCriteriaJSON": #"["The requested website navigation is attempted."]"#,+ "genericHarness.fallbacksJSON": #"["Ask before navigating if the URL is ambiguous."]"#,+ "genericHarness.clarification.questionsJSON": #"["Which URL should I open?"]"#,+ "genericHarness.clarification.policy": "Ask only if the requested URL is missing."+ ]+ )+ let resolution = LocalAppTaskCatalogResolution(+ status: .resolved,+ intent: intent+ )++ _ = await lifecycle.planLocalTaskRun(+ taskID: task.id,+ resolution: resolution,+ fallbackGoal: "open a site",+ traceID: "trace-hosted-plan"+ )+ let planned = await coordinator.task(id: task.id)++ #expect(planned?.intent?.goal == "open example.org in Safari")+ #expect(planned?.intent?.riskLevel == .low)+ #expect(planned?.plan?.steps.first?.id == "model-focus-address")+ #expect(planned?.plan?.steps.first?.toolCall == nil)+ #expect(planned?.plan?.steps.first?.metadata["toolName"] == "ui.focusAddressBar")+ #expect(planned?.plan?.steps.contains { $0.id == "run-local-app-task" } == true)+ #expect(planned?.plan?.successCriteria == ["The requested website navigation is attempted."])+ #expect(planned?.plan?.fallbackPolicy == ["Ask before navigating if the URL is ambiguous."])+ #expect(planned?.plan?.clarificationPolicy == [+ "Which URL should I open?",+ "Ask only if the requested URL is missing."+ ])+ #expect(planned?.plan?.metadata["modelPlan.schemaVersion"] == "generic_harness_planning")+ #expect(planned?.plan?.metadata["modelPlan.stepCount"] == "2")+ }+@Testfunc pointerPromptLifecycleConsumesPendingContinuationOnFollowUpTurn() async {let store = InMemoryHarnessThreadStore()diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex 66f98dce..a95cfbca 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -18,11 +18,12 @@ product migrates onto the generic harness. New work should build toward thegeneric contracts and avoid expanding the older app-specific paths.Pointer-prompt local-app execution now enters the generic lifecycle before it-uses the older live-runner backend. The supported boundary is that thread-context, task state, planning, execution gates, verification, recovery,-pause/resume, and clarification continuations are owned by the generic harness.-The migration bridge still delegates concrete desktop work to the older runner;-keep new lifecycle behavior on the generic side of that bridge.+uses the older live-runner backend. The hosted planning boundary emits the+`generic_harness_planning` packet: structured intent, ambiguity/risk,+context needs, plan steps, verification criteria, fallbacks, and clarification+policy. The bridge stores that packet in generic task intent/plan state, then+delegates concrete desktop work to the older runner until generic executors+cover it. Keep new lifecycle behavior on the generic side of that bridge.## Core Modeldiff --git a/docs/guides/decision-system.md b/docs/guides/decision-system.mdindex 8d9e102e..b4071117 100644--- a/docs/guides/decision-system.md+++ b/docs/guides/decision-system.md@@ -1,127 +1,99 @@# Decision System-## What It Decides+## Purpose-Donkey treats every prompt, voice transcript, file drop, and follow-up as a task-thread turn first. The decision system chooses what the turn should do next:+Donkey treats every prompt, voice transcript, file drop, and follow-up as a+task-thread turn first. The decision system chooses whether the next step is a+conversation response, a clarification, a review flow, a guarded local-app+action, or no action for empty input.-- respond conversationally-- ask for a specific missing detail-- open a review flow-- run a guarded local-app action-- do nothing for empty or already-handled input+Action is not the default. A local action starts only after a typed model or+runtime artifact says the turn is actionable and the runtime validates the+target, plan, permissions, and available control surface.-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 local task needs a clear action, a destination or target, and enough+payload to execute safely. Questions, greetings, malformed requests, and vague+local-task requests stay conversational or ask for a specific missing detail.-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.+## Model Boundary-## Decision Flow+Pointer prompt turns are routed through bounded harness context. Semantic+decisions go through typed model boundaries; the supported hosted path uses the+authenticated Donkey backend Responses proxy with `store=false`, and the+backend chooses the concrete model.-The pointer prompt records the user-visible turn, builds a bounded context packet, and routes it through the harness. Empty input can be handled directly. Semantic decisions go through typed model boundaries. By default, task-intent and follow-up decisions use the authenticated Donkey backend Responses proxy with `store=false`; the Mac app does not send a concrete hosted model, because backend configuration chooses it. Local model adapters are not part of the supported decision path.+The hosted decision output is strict `generic_harness_planning` JSON. It carries:-For local app work, the model receives:+- structured intent+- ambiguity and risk+- context needs+- plan steps+- verification criteria+- fallbacks+- clarification policy-- the current command-- supported runtime task definitions-- an app-finder catalog of installed apps with descriptions, support status,- declared capabilities, and control profiles when available-- safety and execution expectations encoded in task metadata+The generic harness stores those fields in task state. During the migration, the+local-app bridge decodes the structured intent into a `TaskIntent` only so the+existing catalog and live runner can execute the validated task.-The model returns strict JSON, not free-form instructions. The result is decoded into a `TaskIntent`. If the intent names an existing task definition, the catalog validates that definition. If it names the generic local-app interaction capability, the model must ground the selected app in the app-finder catalog when one was supplied. The catalog then resolves the requested app from local memory and app lookup, and materializes a transient task definition from the typed `actionPlan`.+Do not infer semantic intent by matching raw user text. Deterministic code may+match only typed model output, catalog fields, resolved app/item ids, tool names,+and other non-semantic runtime fields.-For dynamic local-item capabilities, the app or item name comes from the typed model output. For dynamic local-app interactions, the app name is accepted only when it can be matched to a supplied app-finder catalog entry with `supportStatus=supported` and a selected declared capability. Catalog and memory matching happen after typed output exists, so lookup is scoped to structured fields such as `targetAppName`, `entities.appName`, `metadata.appFinder.selectedAppID`, or a resolved target id. That inference is not execution authority; the catalog still resolves and verifies the target before any action runs.+## Local App Plans-The `TaskIntent` wire format always includes an `actionPlan` object. Non-planned task types must return an empty `actionPlan.tools` array; non-empty action plans are accepted only for task definitions that explicitly opt into model-planned local-app interaction.-Conversational turns use `taskType: "none"` with an empty action plan,-`metadata.responseMode=conversation`, and `metadata.assistantResponse`; the-resolver preserves that response instead of turning it into an unsupported local-action failure.+Models may choose only supplied task definitions and declared app capabilities.+`local_app_interaction` is the generic model-planned capability for app work+that has no more specific learned task definition.-## Generic Local-App Interaction+When an app-finder catalog is supplied, executable app choices must resolve to a+`supported` catalog entry with a declared capability and control profile.+Candidate, unsupported, or denied entries are not executable targets.-`local_app_interaction` is the default model-planned app capability. It exists for requests like "play some Justin Bieber" where the user is not asking to merely open an app, and no durable app-specific task definition has been learned yet.--For this capability the model must provide:--- `targetAppName`, such as `Music`-- `entities.appName`-- `entities.goal`-- `entities.query` when text needs to be entered-- `actionPlan.tools`, a typed sequence of allowed local tools-- `actionPlan.inputEntity`, usually `query` when `ui.setText` is present-- `actionPlan.controlID`, `actionPlan.focusKey`, and `actionPlan.verification` for the guarded UI strategy--When an app-finder catalog is present, the model must also provide:--- `metadata.appFinder.selectedAppID`-- `metadata.appFinder.selectedCapabilityID`-- `metadata.appFinder.controlProfile`--The selected app id must exist in the catalog, the catalog entry must be-`supported`, and the selected capability/control profile must be declared on-that entry. Catalog entries marked `candidate`, `unsupported`, or `denied` are-not executable targets.--The supported plan tools are intentionally small:+Supported generic plan tools are:```text-app.openOrFocus-app.observe-ui.newDocument-ui.focusSearch-ui.focusAddressBar-ui.focusTextEntry-ui.setText-ui.pressReturn-app.verifyCommand-app.verifyVisibleText+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. 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`. Media playback is not just app/query parsing: vague artist or genre requests must be planned into a concrete playable selection before execution, with `metadata.mediaSelection.*` explaining the chosen song, album, or playlist. Play-media model output without a concrete media-selection kind is rejected before execution. Validated Music `play_media` requests resolve to the AppleScript-backed media playback task instead of the generic keyboard search workflow. Unsupported tool names fail model-output validation or block before execution and become clarification/review instead of input.--## Runtime Validation--The catalog resolves dynamic targets through the agent memory store, Spotlight/app lookup, and bounded filesystem lookup. A planned action only proceeds when:+Plans that type text must provide the text as structured entity data, usually+`query`. Document-writing requests must contain meaningful final text; short+unquoted labels and copied prompt placeholders are not enough to open a writing+app. Media requests that name only an artist, genre, or seed must choose a+concrete playable song, album, or playlist before execution.-- model confidence is high enough-- app-finder metadata matches a supported app/capability when a catalog was supplied-- the target app or item is available-- required entities are present-- every planned tool is in the allowlist-- the plan can be represented as guarded workflow steps+## Validation-The live runner then owns launch/focus, observation, evidence-backed action-planning, guarded execution, verification, and agent visualization evidence.-Accessibility and keyboard input run through action-engine guardrails.-Focus-control steps that name a keyboard shortcut, such as `Command+F` or-`Command+L`, may execute once the target app is focused; pointer-style focus-still requires grounded control bounds.-AppleScript may be used only when supplied by typed task metadata or validated-generated artifacts; free-form planner text is never direct input.+Before execution, Donkey validates model confidence, required entities,+app-finder metadata, target availability, allowed tools, permissions, and whether+the plan can be represented as guarded workflow steps.-Agent visualization is evidence-derived, not a separate command path for real-work. Normal local-app tasks may emit a final plan from evidence-backed action-steps, observations, and action traces after the runner has evidence; they do-not publish a pre-execution visualization from intent resolution. Cursor-playback only uses steps with grounded control bounds or action targets, so-background planning does not animate to invented points. Visual-only-demonstration requests use the same plan shape with `executionMode=visualOnly`-and no live input. In both cases, the overlay cursor is a visualization surface-only and does not move the real macOS pointer.+The live runner owns launch/focus, observation, evidence-backed planning,+guarded input, verification, and recovery. Accessibility and keyboard input run+through action-engine guardrails. AppleScript may run only from typed task+metadata or validated generated artifacts; free-form planner text is never+direct input.-## Learning Boundary+Agent visualization is evidence-derived. Normal local-app tasks may publish+cursor playback only from observed controls, action traces, or other grounded+runtime evidence; visual-only demonstrations use the same plan shape without+live input.-Successful or reviewed plans can be stored as runtime task definitions in agent memory. That lets Donkey turn a one-off generic plan into a reusable supported capability without adding app-specific Swift fixtures or keyword lists.+## Learning-Weather, Music, and document form-fill fixtures remain useful for tests and replay. The supported runtime path is generic: local app/item lookup, model-selected intent or plan, catalog validation, guarded execution, verification, and optional memory-backed learning.+Reviewed or successful plans can become reusable runtime task definitions in+agent memory. That keeps the supported path generic: typed decision, catalog+validation, guarded execution, verification, and optional memory-backed learning.-The local app finder catalog is seeded from bundled JSON and refreshed in the background from the user's installed applications. Donkey persists a daily app-catalog snapshot under Application Support, compares it with the previously seen application ids, and sends only newly discovered apps through the typed catalog-profile model route. Generated profiles are persisted as JSON, sanitized to the allowed generic control profiles, and merged with the shipped seed; bundled deny/support entries remain authoritative.+The app-finder catalog is seeded from bundled profiles and refreshed from the+user's installed applications. Generated profiles are sanitized to generic+control profiles before they can influence executable planning.## Source Entry Points-- Prompt command handling starts in `apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift`.-- Harness routing and context packet assembly live in `apps/Donkey/Sources/DonkeyRuntime/AppHarnessTurnRouter.swift`.-- Task-intent parsing, app-finder prompt context, and the hosted Responses adapter live in `apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift`.-- Catalog validation and generic local-app interaction materialization live in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift`.-- App-finder profile JSON loading and background refresh live in `apps/Donkey/Sources/DonkeyRuntime/LocalAppCatalogProfiles.swift`; hosted profile generation lives in `apps/Donkey/Sources/DonkeyAI/HostedLocalAppCatalogProfileGenerator.swift`.-- Guarded execution lives in `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskLiveRunner.swift` and the action-engine backends.+- Prompt handling: `apps/Donkey/Sources/Donkey/PointerPromptCommandHandler.swift`+- Hosted decision adapter: `apps/Donkey/Sources/DonkeyAI/LocalGenerateTaskIntentAdapter.swift`+- Catalog validation: `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift`+- Generic lifecycle bridge: `apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift`diff --git a/plans/master-plan.md b/plans/master-plan.mdindex a3af9021..1da06d8c 100644--- a/plans/master-plan.md+++ b/plans/master-plan.md@@ -21,29 +21,25 @@ even when there are no active tasks.## Current Sequence-1. Replace old task-intent model schemas as the primary planning output. Hosted- model boundaries should produce structured intent, ambiguity/risk,- context needs, plan steps, verification criteria, fallbacks, and- clarification policy for the generic harness.-2. Implement real generic tool executors. Cover memory lookup, app lookup,+1. Implement real generic tool executors. Cover memory lookup, app lookup,screen observation, element discovery, guarded element actions, text andkeyboard input, AppleScript generation/execution, verification, and lifecycleoperations behind the registry.-3. Make smart compaction central for every model and planner call. Preserve the+2. Make smart compaction central for every model and planner call. Preserve thecurrent turn, active task state, pending gates, summaries, recent usefulevents, assets, and tool traces while storing bulky screenshots, fullAccessibility trees, script source, and long outputs as artifacts.-4. Move app-specific behavior into skills. Music, Notes, Numbers, browser+3. Move app-specific behavior into skills. Music, Notes, Numbers, browserworkflows, app knowledge, and future app-specific behavior should live inskill packs, plugin/catalog data, generated artifacts, or memory instead ofcore Swift prompt branches.-5. Build the application-learning task. It should safely explore an app, capture+4. Build the application-learning task. It should safely explore an app, capturescreenshots and Accessibility trees, distill surfaces/workflows, generatescripts where useful, validate them, and save a reusable skill pack.-6. Wire interruption and permission gates into the UI. The notch/task UI should+5. Wire interruption and permission gates into the UI. The notch/task UI shouldcontrol generic harness tasks and show the exact pending approval orchanged-course state.-7. Delete old app-specific paths once the generic path covers them. Remove+6. Delete old app-specific paths once the generic path covers them. Removehardcoded Music/Notes/Numbers/media/weather-style prompt rules, catalogspecial cases, repair logic, and demo-only workflow branches.