Open source CapCut alternative.
TypeScript
docs: rewrite all guides in the engineering doc style with verified accuracy fixes
David Le3142e7ba2af7
diff --git a/docs/guides/agent-harness.md b/docs/guides/agent-harness.mdindex bba86e28..a6073d0c 100644--- a/docs/guides/agent-harness.md+++ b/docs/guides/agent-harness.md@@ -1,330 +1,306 @@# Agent Harness+The agent harness is the runtime that turns a user request into completed work+on the Mac. It is app-agnostic: it knows how to plan, act, verify, and recover,+but it knows nothing about specific apps. Everything app-specific lives outside+the core — in task definitions, catalog data, skills, generated artifacts,+plugins, or memory.++**The one rule:** core harness code never contains phrase lists, app-name+branches, or natural-language conditionals. If you're tempted to write+`if command.contains("music")`, the logic belongs in a skill, the catalog, or a+typed model boundary instead.++## How a Turn Works++A task is not one big model completion. It's a loop of small steps, each one+checked before and after:+```text-User turn+user turn+ |+ v+1. Understand the turn (typed model boundary: goal, target app, parameters)+ |+ v+2. Compact context into task state (never raw history)+ |+ v+3. Ask the model: "what is the single next tool call?"+ | (see, act, verify, respond, clarify, or complete)+ v+4. Validate the call (registry, permissions, focus, safety class)|v-Generic harness task state (goal, world model, history) <--+- | |- v |-Model boundary -> the single next tool call |- | (see, act, verify, respond, clarify, or complete) |- v |-Tool registry -> guarded executor -> structured observation- | |- +-- update world model, then re-plan ---------------------+- (or hard-stop at a permission / clarification gate)+5. Execute it through the guarded executor+ |+ v+6. Record the structured observation into the world model+ |+ v+7. Loop back to 3 — or hard-stop at a permission / clarification gate```-The agent harness is Donkey's app-agnostic runtime boundary for turning a user-turn into durable task progress. It owns intent routing, bounded context,-planning, guarded tool execution, verification, recovery, permission gates,-clarification, pause/resume, interruption, and multi-task state.+The model decides *what* to do next; Swift decides *whether and how* it+actually happens. The model picks the tool. Swift owns task state, validation,+focus checks, permission gates, execution, and recording results.-Keep the harness generic. App-specific behavior belongs in task definitions,-catalog data, skills, generated artifacts, plugins, or memory. Core harness-code must not add phrase lists, app-name branches, or one-off natural-language-conditionals.+Planning happens per observation, not as one upfront plan. The harness looks,+acts, sees what happened, then picks the next step.-## Runtime Shape+## Task State-A user-query turn enters the generic lifecycle before any local-app executor is-selected. The harness compacts context into task state, then runs a loop: each-step it asks the model boundary for the single next tool call given the current-world model, validates and executes that one call deterministically, records the-resulting observation, and asks again. Planning happens per observation, not as-one upfront plan.+Every task carries its own durable state:-The loop is:+- goal and structured intent+- world model (what the harness currently believes about the screen and system)+- plan, tool history, and pending continuation+- granted permissions+- lifecycle status (running, paused, `waitingForUser`, `waitingForPermission`,+ interrupted, resuming, completed, failed-safe, cancelled)-```text-intake--> compact context into task state--> ask the model boundary for the next tool call--> validate against registry, permissions, and task state--> execute one guarded tool step--> record the structured observation into the world model--> re-plan, or hard-stop at a clarification / permission gate-```--Desktop work is not a single model completion. The harness observes, acts, and-records evidence one step at a time, re-planning after each observation. The-model chooses the next tool — including when to see, verify, respond, clarify,-or complete — while Swift owns task state, tool validation, focus checks,-permission gates, execution, and result recording.--## Task State+State is task-local. Pausing, clarifying, gating, interrupting, or cancelling+one task never touches another.-Each task has its own durable state: goal, structured intent, context, world-model, plan, granted permissions, tool history, pending continuation, and-lifecycle status.+Storage is split three ways so decisions stay inspectable:-Active/waiting tasks stay task-local. A pause, clarification, permission gate,-interruption, cancellation, or failed-safe state must affect only the selected-task.+- **Threads** store conversation events and active task ids.+- **Task snapshots** store execution state.+- **Compaction snapshots** record exactly what context was sent to the model+ for each decision.-Threads store conversation events and active task ids. Task snapshots store-execution state. Compaction snapshots record what bounded context was sent to a-model so decisions remain inspectable.+## Turn Understanding-## Context And Intent+Two rules govern how the harness reads a user request:-The harness never sends raw unbounded history to a model. Compaction keeps the-current turn, relevant active/waiting task state, recent useful evidence,-summaries, memory snippets, pending questions/permissions, and bounded assets.+**1. Never match raw user text.** Semantic intent always passes through an LLM+or another typed boundary first. After that, deterministic code may match+*typed fields* — tool names, app ids, schema values, permissions, file paths,+Accessibility roles — but never the raw string.-Never infer semantic intent by matching raw user text. Pass the turn through an-LLM or another typed model/runtime boundary first. After that, deterministic-code may match typed fields such as tool names, app ids, schema values,-permissions, filesystem paths, and Accessibility roles/actions.+**2. Understand once, then loop.** Before the per-step loop starts, an+understanding boundary restates the goal, names the target app (or leaves it+empty for system-tool tasks), extracts parameters and success criteria, and+flags whether clarification is needed. Every later step plans against this+stable, typed goal instead of re-reading the user's words.-A desktop turn is understood once before the per-step loop begins: a typed-understanding boundary restates the goal, names the target app, extracts the-request's parameters and success criteria, and decides whether to clarify. That-understanding selects which app the loop drives and is carried into every step so-the planner grounds against a stable goal instead of re-reading raw text each-step. Deterministic matching (e.g. clarify when the understanding flags it) keys-off those typed fields, never the raw command.+Context sent to the model is always bounded. Compaction keeps the current+turn, relevant task state, recent useful evidence, summaries, memory snippets,+pending questions/permissions, and bounded assets — never unbounded raw+history.-The app catalog is part of the model boundary. If a requested app or capability-is not supported or is still refreshing, surface conversation, clarification,-waiting, or failed-safe state rather than silently executing an unsupported-candidate.+The app catalog is part of this boundary. If a requested app or capability+isn't supported (or is still refreshing), the harness surfaces conversation,+clarification, waiting, or failed-safe state. It never silently executes an+unsupported guess.-## Model Boundary And Adapters+## Model Boundary and Adapters-The model boundary is pluggable. The harness asks an abstract boundary for the-single next tool call; a model adapter translates that request into one-provider's wire format and parses the provider's response back into a validated-registry tool call. Adapters live in `DonkeyAI/`, behind the generic registry —-task state and the planner never see provider details.+The harness asks an abstract boundary one question: "given this task state,+what is the single next tool call?" Adapters translate that question into a+specific provider's wire format and parse the answer back. Adapters live in+`DonkeyAI/`; the planner and task state never see provider details.-An adapter's job is narrow and total:+An adapter's job is narrow:```textnext-tool-call request--> render registry descriptors + schemas into the provider's tool format--> send compacted task state as the prompt (never raw history)--> provider--> parse response into one validated registry tool call, or a boundary error+-> render registry tool descriptors into the provider's tool format+-> send compacted task state as the prompt+-> parse the response into one validated registry tool call, or an error```-Provider-side failures (refusal, truncation, malformed call) map into harness-states the planner already handles, not ad hoc retries inside the adapter.+Because adapters are interchangeable, a fallback adapter — including one for+an open-weights model that emits tool calls as structured text — is a drop-in+shape: it implements the same render/parse contract against the same registry+and changes nothing in the runtime loop. Format-specific parsing stays inside+the adapter; the rest of the harness only ever sees a validated tool call.-Because adapters are interchangeable, the boundary supports a primary hosted-model plus a fallback. A fallback adapter targeting an open-weights model that-emits tool calls as structured text — for example the Hermes function-call-convention — is a supported shape: it implements the same render/parse contract,-reuses the same registry and schemas, and changes nothing in the runtime loop.-Keep format-specific parsing inside the adapter; the rest of the harness only-ever sees a validated tool call.--What stays out of adapters: task state, permission gates, verification,-planning, and computer-use guarding. An adapter formats requests and parses tool-calls; it never decides intent, executes tools, or holds task state.+Adapters never decide intent, execute tools, or hold task state. Provider+failures (refusals, truncation, malformed calls) map into harness states the+planner already handles — no ad hoc retries inside the adapter. Planner-side+failures are bounded honestly too: a malformed or empty model reply is retried+with the failure fed back, and an empty tool name never reads as completion.## Tools-Tools are registered through the generic registry. A descriptor declares the-tool name, plugin id, schemas, required permissions, safety class, required-context, verification hints, and metadata. The planner sees descriptors and-schemas, not Swift implementation details.--Tool results return structured observations that update the task world model.-Waiting states are hard stops:--- missing permission moves the task to `waitingForPermission`-- missing required user detail moves the task to `waitingForUser`-- dangerous ambiguity asks before acting-- on verification failure the planner re-plans to recover, clarify, or fail safe--Core tool families cover conversation, clarification, permission requests,-memory, skills, app lookup, observation, UI element actions, text/keyboard-input, pointer input (scroll, drag, click variants), waiting, shell commands,-AppleScript/script generation and execution, verification, learning, and-lifecycle control.--Completion is evidence-gated by the runtime, not just prompt guidance: a-`run.complete` whose most recent succeeded state-changing step has no later-succeeded evidence step (a read-only observation, or a tool whose descriptor-declares its result is itself evidence — like a shell command's output and exit-code) is rejected with a failed result, and the planner re-plans to verify-first. Planner-side failures are bounded honestly too: a malformed or empty-model reply is retried once with the failure fed back, and an empty tool name-never reads as completion.--## System Tools First--Donkey operates the Mac the way an expert terminal user would. The planner's-first choice is `shell_exec` — a single-line shell command — for anything a-power user solves without the GUI: finding files (`mdfind`, `find`, `ls -t`),-launching or quitting apps (`open`, `osascript`), reading state (`pmset -g`,-`system_profiler`, `defaults read`), and changing settings (`defaults write`,-`networksetup`). Driving an app's GUI is the fallback, used only when the task-truly needs it (canvas, Electron, or proprietary interfaces with no system-tool-equivalent). This preference lives in the planner doctrine and a built-in-`system-tools` skill; the understanding boundary leaves the target app empty for-system-tool tasks so they are not pinned to a GUI app.--Shell commands are not refused by a denylist. Each command is classified by its-argv tokens into a risk tier, and nothing changes state without consent:--- **read** (e.g. `mdfind`, `defaults read`, `pmset -g`) runs immediately.-- **reversibleWrite** (e.g. `defaults write`, `open`, `networksetup -set…`)- stops at a consent gate offering allow-once or always-allow. An always-allow- rule is keyed on the command signature (e.g. `defaults write`) and persists.-- **highRisk** (privileged, destructive, network-egress, or security/privacy- settings — `sudo`, `rm`, `dd`, `curl | sh`, `com.apple.TCC`) asks every time- and can never be remembered.--Consent is surfaced in the pointer/notch overlay with Allow Once / Always Allow,-reusing the `waitingForPermission` gate. The tier classifier matches typed argv-fields only — never natural-language intent. A capability probe records which-command-line tools are installed on the machine (and versions) so the planner-reaches only for what exists.--## Computer Use--Computer use is a tool family inside the harness, and seeing and acting are each-plain tools the planner chooses per step — not a fixed pipeline. The harness-re-plans after every observation, so the model looks, sees the result, then picks-the next tool.--To **see**, it can read the Accessibility tree (fast, structured, best for native-apps) or capture and analyze a screenshot with vision (works for any pixels, e.g.-canvas or Electron content). Either returns elements into the world model.-Accessibility is preferred when it's sufficient; vision is the fallback when it-isn't. Screenshots never go to hosted model providers: the planner reads the-AX/vision annotations as text, so the prompt renders each element with its-geometry, value, and click eligibility, in reading order, and ranks clickable-controls first when the list is capped.--To **act**, it can click an element the AX tree or vision returned (left, right,-double, or triple click), type or press keys — including modifier chords like-Cmd+C — scroll, drag one observed element onto another, wait briefly for the app-to settle, or generate and run an AppleScript — whichever fits. Clicking an-Accessibility control prefers a native Accessibility press (`AXPress`) and falls-back to a guarded coordinate click on the control's frame; vision elements click-by coordinate; right- and multi-clicks always take the coordinate path. Either-way this is not a shortcut around the focus and permission checks below. The-planner can also answer conversationally or ask the user to clarify instead of-acting — responding and clarifying are themselves tools.--A non-LLM monitor watches the frontmost window's screenshot fingerprint and-re-parses on large changes, keeping the vision parse cache warm so a capture is-usually reused instantly rather than paid for inline.--Input must be guarded by target focus, permission policy, element eligibility,-allowed action type, safety class, and verification criteria. Coordinate input-is a fallback path, not a shortcut around those checks. When the target window-lost focus between observe and act, the guard attempts one recovery activation-of the target app (never any other app) before denying; a denial names whatever-is in front so the planner can react to the blocking window instead of failing-opaquely.--Verification must be evidence-backed. A command is not complete merely because-the target app is focused. The harness needs post-action evidence such as a-guarded command trace, visible text, selected state, app-reported result, or-screenshot-backed observation.--Pointer playback is separate from input. It may rotate, travel, hold, and label-the path the agent planned or observed, while AX, AppleScript, keyboard input,-or guarded coordinate fallback perform the real work. The overlay narrates every-step, not just clicks: steps that move the pointer animate the cursor to the-target, and steps that don't (observe, shell, wait, verify) hold the cursor in-place and update its label, so a user always sees what the run is doing.--## AppleScript And Scripts--AppleScript is a tool path, not a hardcoded helper path. Generation creates a-script artifact; it does not execute the script. Execution may run only a-validated, generated, or user-reviewed artifact through the guarded backend,-with target app, permissions, action metadata, and verification evidence.--Dynamic AppleScript follows the same artifact boundary and should stay small:+Every tool is registered through the generic registry with a descriptor: name,+plugin id, schemas, required permissions, safety class, required context,+verification hints, and metadata. The planner sees descriptors and schemas,+never Swift implementations.++Tool results come back as structured observations that update the world model.+Four situations are hard stops, not things to push through:++| Situation | Result |+|---|---|+| Missing permission | task → `waitingForPermission` |+| Missing user detail | task → `waitingForUser` |+| Dangerous ambiguity | ask before acting |+| Verification failure | re-plan: recover, clarify, or fail safe |++Core tool families: conversation, clarification, permission requests, memory,+skills, app lookup, observation, UI element actions, text/keyboard input,+pointer input (scroll, drag, click variants), waiting, shell commands,+AppleScript generation and execution, verification, learning, and lifecycle+control.++## Shell First, GUI Second++Donkey works like an expert terminal user. The planner's first choice is+`shell_exec` for anything a power user solves without the GUI:++- finding things: `mdfind`, `find`, `ls -t`+- launching/quitting apps: `open`, `osascript`+- reading state: `pmset -g`, `system_profiler`, `defaults read`+- changing settings: `defaults write`, `networksetup`++Driving a GUI is the fallback, used only when the task truly needs it (canvas,+Electron, or proprietary interfaces with no command-line equivalent). This+preference lives in the planner doctrine and a built-in `system-tools` skill.+For system-tool tasks the understanding boundary leaves the target app empty,+so they're never pinned to a GUI app.++Shell safety is consent-based, not denylist-based. Each command is classified+by its argv tokens (typed fields, never natural language) into a risk tier:++| Tier | Examples | Behavior |+|---|---|---|+| **read** | `mdfind`, `defaults read`, `pmset -g` | runs immediately |+| **reversibleWrite** | `defaults write`, `open`, `networksetup -set…` | consent gate: Allow Once / Always Allow (rule keyed on command signature, persists) |+| **highRisk** | `sudo`, `rm`, `dd`, `curl \| sh`, anything touching `com.apple.TCC` | asks every time, can never be remembered |++Consent surfaces in the pointer/notch overlay and reuses the standard+`waitingForPermission` gate. A capability probe records which command-line+tools (and versions) exist on the machine, so the planner only reaches for+what's installed.++## Observation and Action (Computer Use)++Seeing and acting are plain tools the planner picks per step — not a fixed+pipeline. The harness re-plans after every observation: look, see the result,+pick the next tool.++**To see**, the planner picks one of two paths. Accessibility tree reads are+fast, structured, and preferred for native apps. Screenshot + vision works on+any pixels (canvas, Electron) and is the fallback when Accessibility isn't+enough. Both return elements into the world model. Screenshots never go to+hosted model providers: the planner reads AX and vision annotations rendered+as text — each element with its geometry, value, and click eligibility, in+reading order. A non-LLM monitor watches the frontmost window's screenshot+fingerprint and re-parses on large changes, keeping the vision cache warm so+captures are usually free at decision time.++**To act**, the planner can click an element, type or press keys (including+modifier chords), scroll, drag one observed element onto another, wait for the+app to settle, or generate and run an AppleScript. Clicking an Accessibility+control prefers a native `AXPress` and falls back to a guarded coordinate+click on the control's frame; vision elements click by coordinate. Responding+conversationally and asking for clarification are also tools — sometimes the+right "action" is a question.++Two invariants:++1. **Every input is guarded.** Target focus, permission policy, element+ eligibility, allowed action type, safety class, and verification criteria+ all apply. Coordinate input is a fallback path, never a shortcut around+ these checks. If the target window lost focus between observe and act, the+ guard attempts one recovery activation of the target app (never any other+ app) before denying — and a denial names whatever is in front, so the+ planner can react to the blocking window instead of failing opaquely.+2. **Done means evidence.** A task isn't complete because the right app is+ focused. The harness needs post-action proof: a guarded command trace,+ visible text, selected state, an app-reported result, or a+ screenshot-backed observation. The runtime enforces this — a completion+ whose last state-changing step has no later succeeded evidence step is+ rejected, and the planner re-plans to verify first.++Pointer playback (the animated cursor the user sees — rotating, traveling,+labeling its path) is cosmetic and separate from input. AX, AppleScript,+keyboard input, or guarded coordinate fallback do the real work. The overlay+narrates every step, not just clicks: steps that move the pointer animate the+cursor, and steps that don't (observe, shell, wait, verify) hold it in place+and update its label, so a silent step never looks like a hang.++## AppleScript++AppleScript is a tool path with a strict artifact boundary — never a hardcoded+helper:```text-automation.applescript.generate+automation.applescript.generate (creates a script artifact — does NOT run it)-> automation.applescript.validate--> automation.applescript.execute+-> automation.applescript.execute (guarded backend only)-> observe-> verify```-The generation step receives structured target-app, goal, entity,-allowed-action, and verification inputs for one bounded target-app operation or-a very small sequence. It must not try to build a full automation pipeline;-observation, clicking, recovery, and verification stay as separate harness-steps. If the requested operation is not doable as a small scoped AppleScript,-generation should fail cleanly and the plan should use observation,-Accessibility, screenshot, or UI tools instead.--Planner output must not contain raw script source for dynamic AppleScript. A-child generation boundary creates the artifact source, and the plan reuses the-same `scriptArtifactID` across generation, validation, and execution.--App-specific AppleScript belongs in skill-local scripts, generated artifacts,-plugins, catalog entries, or user-reviewed definitions. Do not add app-named-Swift helpers such as `musicPlaybackScript`.--### Dictionary Grounding And The Compile Gate--Generated AppleScript is grounded in the target app's real scripting+Rules:++- Generation receives structured inputs (target app, goal, entity, allowed+ actions, verification criteria) and produces *one bounded operation* or a+ very small sequence. It must not build a whole automation pipeline —+ observation, clicking, recovery, and verification stay as separate harness+ steps.+- If the operation can't be done as a small scoped script, generation fails+ cleanly and the plan falls back to observation, Accessibility, or UI tools.+- Planner output never contains raw script source. A child generation boundary+ creates the source, and the plan reuses the same `scriptArtifactID` across+ generate, validate, and execute.+- App-specific scripts live in skills, generated artifacts, plugins, catalog+ entries, or user-reviewed definitions. No app-named Swift helpers like+ `musicPlaybackScript`.++### Grounded in the App's Real Dictionary++Generated AppleScript is grounded in the target app's actual scriptingdictionary, not the model's memory of AppleScript. The runtime parses an app's-`.sdef` into a typed model (`AppScriptingDictionaryService`, cached per app-version), and that vocabulary flows through the pipeline in three places:--- The `app_commands` command gives the planner an app's declared commands,- parameters, classes, and enumerations as a bounded digest, with a per-suite- drill-down. Non-scriptable apps answer deterministically with a redirect to- the accessibility/vision path.-- Generation receives the digest and must use only declared terminology, bind- every required parameter, and report the commands it used; if the goal does- not fit the dictionary, it declines instead of inventing syntax.-- Validation is deterministic, not advisory: beyond the static safety checks,- it rejects unresolved template tokens, rejects reported commands the- dictionary does not declare, and compiles the script against the target app's- dictionary (`NSAppleScriptCompileGate`, no execution, never launches the- app). A compile failure carries the real compiler message back to the- planner for regeneration.--A generated script that compiles, validates, and executes successfully is-promoted into a learned skill pack (parameterized when a generation-reported-binding can be turned back into an input slot), so the next run of the same-task goes `app_skill` → `skill_run` with no model-generated script at all.--## Skills And Learning--Skills are reusable harness extensions. Skill lookup gives the planner bounded-instructions, descriptors, and validated scripts without putting app-specific-branches into core runtime code.--Learning an application is a skill-producing harness task. It gathers bounded-screenshot and Accessibility evidence, explores only safe/reversible states-unless the user approves more, distills an app profile and workflow recipes,-and saves a reusable skill pack with any validated scripts.--Learned packs compound across sessions: a saved pack (under the app-support-learned-skills directory) declares its app in `apps:` frontmatter and is-re-discovered alongside the bundled packs, so a later run driving that app-preloads its learned playbook exactly like a built-in. Bundled packs win when-both name the same app.+`.sdef` into a typed model, cached per app version, and that vocabulary flows+through the pipeline in three places:++- An `app_commands` tool gives the planner the app's declared commands,+ parameters, classes, and enumerations as a bounded digest, with per-suite+ drill-down. Non-scriptable apps get a deterministic redirect to the+ Accessibility/vision path.+- Generation receives the digest, must use only declared terminology, binds+ every required parameter, and reports the commands it used. If the goal+ doesn't fit the dictionary, it declines instead of inventing syntax.+- Validation is deterministic, not advisory: it rejects unresolved template+ tokens, rejects reported commands the dictionary doesn't declare, and+ compiles the script against the app's dictionary (compile only — no+ execution, never launches the app). A compile failure carries the real+ compiler message back to the planner for regeneration.++A script that compiles, validates, and executes successfully is promoted into+a learned skill pack — parameterized when a generation-reported binding can+become an input slot — so the next run of the same task goes straight through+skill lookup and `skill_run` with no model-generated script at all.++## Skills and Learning++Skills are reusable harness extensions: bounded instructions, descriptors, and+validated scripts the planner can look up — the sanctioned home for+app-specific knowledge that must never enter core runtime code.++Learning an app is itself a harness task that produces a skill. It gathers+bounded screenshot and Accessibility evidence, explores only safe/reversible+states unless the user approves more, distills an app profile and workflow+recipes, and saves a reusable skill pack with any validated scripts.++Learned packs compound across sessions: a saved pack declares its app in+`apps:` frontmatter and is rediscovered alongside the bundled packs, so a+later run driving that app preloads its learned playbook exactly like a+built-in. Bundled packs win when both name the same app.## Source Map-Start here:--- `apps/Donkey/Sources/DonkeyHarness/` for task state, registry, tools, skills,- thread storage, and generic runtime execution.-- `apps/Donkey/Sources/DonkeyContracts/` for shared contracts across modules.-- `apps/Donkey/Sources/DonkeyRuntime/` for guarded local-app execution,- Accessibility, screenshots, app/window observation, and input backends.-- `apps/Donkey/Sources/DonkeyAI/` for hosted and fallback model routing and- adapters. Agent prompt doctrine is consolidated in `DonkeyPrompts.swift`- (the Live session instruction, request understanding, and step planning);- narrow adapter prompts stay with their adapters.-- `apps/Donkey/Sources/Donkey/` for user-query integration.--Tests live in `apps/Donkey/Tests/DonkeyRuntimeTests/`. Use focused `swift test`-runs from `apps/Donkey/` when changing harness behavior.+| Module | Owns |+|---|---|+| `apps/Donkey/Sources/DonkeyHarness/` | task state, registry, tools, skills, thread storage, generic runtime |+| `apps/Donkey/Sources/DonkeyContracts/` | shared contracts across modules |+| `apps/Donkey/Sources/DonkeyRuntime/` | guarded execution, Accessibility, screenshots, app/window observation, input backends |+| `apps/Donkey/Sources/DonkeyAI/` | hosted model routing and adapters; prompt doctrine in `DonkeyPrompts.swift` |+| `apps/Donkey/Sources/Donkey/` | user-query integration |++Tests live in `apps/Donkey/Tests/DonkeyRuntimeTests/`. Run focused+`swift test` from `apps/Donkey/` when changing harness behavior.diff --git a/docs/guides/authoring-skills.md b/docs/guides/authoring-skills.mdindex 772d6972..7753b424 100644--- a/docs/guides/authoring-skills.md+++ b/docs/guides/authoring-skills.md@@ -1,25 +1,32 @@# Authoring Skills-A skill is a folder with a `SKILL.md` that teaches the agent how to do something-the way an expert would. The model reads the body; deterministic code reads the-frontmatter. App-specific operating knowledge belongs here, never in prompts.+A skill is a folder with a `SKILL.md` that teaches the agent how to do+something the way an expert would. The model reads the body; deterministic code+reads the frontmatter.++**The one rule:** app-specific operating knowledge lives in skills, never in+prompts or core runtime code. If you're tempted to teach the harness about+Notes inside `DonkeyPrompts.swift`, write+`BuiltInSkills/notes/SKILL.md` instead.++## Skill Kinds++| Kind | Identified by | Surfaces when |+|---|---|---|+| App skill | `apps:` line listing display names + bundle ids | a turn targets that app — matched on the typed app identity, never the user's words |+| Other skill | no `apps:` line; `tags`/`keywords` | lexical search finds it for a workflow need |++Name an app skill after its app (`notes`, `mail`). Name an other skill after+its capability (`system-tools` for the shell, `browser` for any browser,+`weather`).++## LocationsBuilt-in skills live in`apps/Donkey/Sources/DonkeyRuntime/Resources/BuiltInSkills/<id>/SKILL.md`.Learned skills are written to the app-support learned directory and discoveredthe same way. The folder name is the skill id; keep it the clean app or-capability name (`notes`, `mail`, `system-tools`), not a description.--## Two kinds of skill--**App skills** operate one Mac app. They carry an `apps:` line listing the app's-display names and bundle ids. That line is how the runtime auto-matches and-preloads the skill when a turn targets that app — match is on the typed app-identity, never on the user's words. Name the skill after the app.--**Other skills** are capabilities not tied to a single app (`system-tools` for-the shell, `browser` for any browser, `weather`). They omit `apps:` and surface-through search on their `tags`/`keywords` when a workflow needs them.+capability name, not a description.## Frontmatter@@ -38,18 +45,18 @@ tools: shell_exec, app_skill <- tools the skill expects to use## BodyWrite the operating playbook as an expert would brief a teammate: the reliable-way to do the common tasks, the exact commands or AppleScript, the pitfalls, and-how to verify. Prefer `shell_exec` with `osascript` over driving the GUI; reach-for vision only when scripting can't. Keep commands single-line and+way to do the common tasks, the exact commands or AppleScript, the pitfalls,+and how to verify. Prefer `shell_exec` with `osascript` over driving the GUI;+reach for vision only when scripting can't. Keep commands single-line andparenthesis-free where possible (see `system-tools`). State boundaries — whatmust ask the user first (sending, deleting, purchases).## ScriptsA skill may ship validated scripts in a `scripts/` subfolder — discovery picks-them up from there automatically (no frontmatter line needed). The agent runs-them with `skill_run` instead of reinventing the steps, so name and reference-them in the body. Scripts must be bounded and deterministic.+them up automatically, with no frontmatter line. The agent runs them with+`skill_run` instead of reinventing the steps, so name and reference them in+the body. Scripts must be bounded and deterministic.-See existing packs under `BuiltInSkills/` for the shape — `notes` and `mail` for-app skills, `system-tools` for an other-skill.+See existing packs under `BuiltInSkills/` for the shape — `notes` and `mail`+for app skills, `system-tools` for an other-skill.diff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.mdindex 6710049d..5694bcf0 100644--- a/docs/guides/backend-apis.md+++ b/docs/guides/backend-apis.md@@ -1,43 +1,56 @@# Backend API Guide-Backend APIs live in `site/src/app/api/**/route.ts`.+Backend APIs live in `site/src/app/api/**/route.ts`. They serve the Mac app+(session cookie), the site's own client views, and third-party Vision API+developers (API keys).-## Rules+**The one rule:** every route handler is wrapped in `withDonkeyAuth` from+`@/lib/donkey-api-auth`. A public endpoint is a deliberate exception with an+explicit product reason — today only Better Auth's own routes and the+signature-verified Stripe webhook — never a default.-- APIs are authenticated by default.-- Always wrap route handlers with `withDonkeyAuth` from `@/lib/donkey-api-auth`.-- Routes accept a Donkey session cookie by default. Third-party API keys are- opt-in per route: pass `withDonkeyAuth(handler, { allowApiKey: true })`. This- typed allowlist is the only way a key reaches a handler — never match on the- request path. `request.donkey.method` tells the handler how the caller+## Authentication++- `withDonkeyAuth` accepts a Donkey session cookie by default. Third-party API+ keys are opt-in per route: `withDonkeyAuth(handler, { allowApiKey: true })`.+ This typed allowlist is the only way a key reaches a handler — never match on+ the request path. `request.donkey.method` tells the handler how the callerauthenticated (`session-cookie`, `api-key`, or `dev-bypass`).-- Treat public endpoints as exceptions that need an explicit product reason.-- Better Auth is mounted as the public auth exception at `site/src/app/api/auth/[...all]/route.ts`; configure it through `@/lib/auth`.-- The supported interactive login provider is Google OAuth only. Keep `emailAndPassword.enabled` false unless the product explicitly adds another login method.-- Configure Google OAuth with `${BETTER_AUTH_URL}/api/auth/callback/google` as the redirect URI.-- Keep the Mac app callback origin (`donkey://` by default) in Better Auth- trusted origins so `/mac-auth` can return successful Google sign-in to the- app.+- Better Auth is mounted at `site/src/app/api/auth/[...all]/route.ts` and+ configured through `@/lib/auth`. The supported interactive login provider is+ Google OAuth only; keep `emailAndPassword.enabled` false unless the product+ explicitly adds another login method. Configure Google OAuth with+ `${BETTER_AUTH_URL}/api/auth/callback/google` as the redirect URI.- Mac app sign-in uses Better Auth's one-time-token plugin. `/mac-auth/callback`mints a short-lived code from the browser session, renders a browser handoffpage that opens `donkey://auth/callback`, then the app exchanges the code at`/api/auth/one-time-token/verify` so `URLSession` stores the resulting Better- Auth cookie in the app-owned cookie jar. The code should remain short-lived- while still allowing a manual "Open Donkey" fallback click.+ Auth cookie in the app-owned cookie jar. Keep the code short-lived while+ still allowing a manual "Open Donkey" fallback click, and keep the Mac app+ callback origin (`donkey://` by default) in Better Auth trusted origins.- In Vercel, configure `BETTER_AUTH_URL`, `BETTER_AUTH_SECRET`,`GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, and`DONKEY_MAC_AUTH_REDIRECT_ORIGINS`. Do not commit real OAuth credentials.-- Validate request bodies, search params, and route params with Zod before using them.++## Handler Rules++- Validate request bodies, search params, and route params with Zod before+ using them.- Verify resource ownership before reading or mutating scoped data.-- Return explicit `NextResponse.json(...)` responses with the intended status code.+- Return explicit `NextResponse.json(...)` responses with the intended status+ code.- For access-control failures (missing session, missing/inactive subscription),- return a plain 401 via `unauthorizedResponse` from `@/lib/donkey-api-auth`; for- a missing resource, return a plain 404 via `notFoundResponse`. Do not write- per-case descriptive auth/not-found errors. Reserve distinct status codes for- genuinely different operational outcomes (e.g. 402 over quota, 429 rate limit).+ return a plain 401 via `unauthorizedResponse`; for a missing resource, a+ plain 404 via `notFoundResponse` (both from `@/lib/donkey-api-auth`). Do not+ write per-case descriptive auth/not-found errors. Reserve distinct status+ codes for genuinely different operational outcomes (e.g. 402 over quota, 429+ rate limit).- Do not wrap route handlers in `try/catch` unless the handler can recover andreturn a different intentional response. Let unexpected errors surface to theframework's logging path.++## Database+- Keep Prisma access server-only through `@/lib/prisma`.- Keep Prisma table/model definitions in logically grouped sibling `.prisma`files under `site/prisma/`. Never put table/model definitions in@@ -54,8 +67,9 @@ Backend APIs live in `site/src/app/api/**/route.ts`.The inference gateway lives under `site/src/app/api/inference/**`. It is aMac-app-facing backend boundary for remote model and asset generation. Routes,-shared schemas, stateless provider calls, and Swift contracts must stay provider-neutral;-provider names are configuration/data inside private adapters only.+shared schemas, stateless provider calls, and Swift contracts stay+provider-neutral; provider names are configuration/data inside private adapters+only.- Require `x-donkey-client-id` on inference routes.- Keep remote asset generation state on the Mac side. The backend can create or@@ -64,7 +78,7 @@ provider names are configuration/data inside private adapters only.generation records, provider output references, or generated assets inPostgres.- Keep provider-specific request mapping behind the inference provider registry.- Route handlers should import the registry and neutral schemas, not individual+ Route handlers import the registry and neutral schemas, not individualadapters.- Computer-use provider tools are registered as request tools and mapped byadapters. Browser interaction uses Gemini through@@ -77,22 +91,21 @@ provider names are configuration/data inside private adapters only.- Screenshot parsing is available at `POST /api/inference/screenshots/parse/`.It accepts scoped app/window or system-navigation screenshots only, neverwhole-desktop captures, and returns read-only UI evidence in the Mac app's- local UI understanding shape. The default provider is Gemini Flash through- a dedicated screenshot-parsing module configured with hosted Google- credentials or `GEMINI_API_KEY`.+ local UI understanding shape. The default provider is Gemini Flash through a+ dedicated screenshot-parsing module configured with hosted Google credentials+ or `GEMINI_API_KEY`.- The Gemini adapter uses the official `@google/genai` Node/TypeScript SDK forgeneral non-streaming chat, structured Responses calls, and browsercomputer-use calls. It uses Vertex AI's global endpoint only when- `GOOGLE_APPLICATION_CREDENTIALS_JSON` includes a `project_id`. If the project- is missing, the provider is unavailable. The adapter's defaults should route- fast structured task-intent and follow-up decisions to `gemini-3.1-flash-lite`,- keep `gemini-3.5-flash` available for general chat and non-decision Responses- calls, and use `gemini-3-flash-preview` for browser Computer Use tool calls.- Keep model selection in code rather than environment overrides. Structured+ `GOOGLE_APPLICATION_CREDENTIALS_JSON` includes a `project_id`; if the project+ is missing, the provider is unavailable. The adapter's defaults route fast+ structured task-intent and follow-up decisions to `gemini-3.1-flash-lite`,+ keep `gemini-3.5-flash` for general chat and non-decision Responses calls,+ and use `gemini-3-flash-preview` for browser Computer Use tool calls. Keep+ model selection in code rather than environment overrides. Structureddecision requests normalize JSON schemas for Gemini and retry withoutprovider-enforced schema when Vertex rejects schema parameters; Mac-side- runtime validation still owns whether the returned JSON is executable. For- Google Cloud credits, set+ runtime validation still owns whether the returned JSON is executable. Set`GOOGLE_APPLICATION_CREDENTIALS_JSON` as a hosted-deploy sensitive env varrather than storing Google provider credentials in the Mac app.- The OpenAI hosted Responses adapter uses `OPENAI_API_KEY` only for macOS@@ -103,7 +116,7 @@ provider names are configuration/data inside private adapters only.## Hosted Model CreditsHosted inference usage is metered per authenticated user in the backend. The-Mac app still sends provider-neutral inference requests; the backend owns credit+Mac app sends provider-neutral inference requests; the backend owns creditchecks, provider/model rates, debits, and audit rows.- Keep one visible balance per user, with auditable grants, expirations, usage@@ -134,13 +147,14 @@ checks, provider/model rates, debits, and audit rows.## Third-Party Vision API-`POST /api/vision` is also a self-serve product for outside-developers, sold separately from the Mac app. It serves two audiences through-the same handler, branching on `request.donkey.method`:+`POST /api/vision` is also a self-serve product for outside developers, sold+separately from the Mac app. It serves two audiences through the same handler,+branching on `request.donkey.method`:-- **Mac app** (`session-cookie`): gated by the hosted credit balance, as above.-- **Third-party** (`api-key`): gated by an active subscription and a monthly- call quota — it never touches the money-credit balance.+| Caller | `request.donkey.method` | Gate |+|---|---|---|+| Mac app | `session-cookie` | hosted credit balance, as above |+| Third-party developer | `api-key` | active subscription + monthly call quota — never touches the money-credit balance |How the third-party path works:@@ -149,8 +163,9 @@ How the third-party path works:`VisionApiSubscription` (`site/prisma/Billing.prisma`). The included callcount comes from the Stripe price metadata (`monthlyCallQuota`).- Keys are issued by the Better Auth API-key plugin (`@better-auth/api-key`),- managed from the dashboard via `/api/api-keys`. Only a hash is stored; the- secret is shown once. Key creation requires an active subscription.+ managed from the account settings UI via `/api/api-keys`. Only a hash is+ stored; the secret is shown once. Key creation requires an active+ subscription.- The vision route opts in with `allowApiKey: true`, enforces a per-key burstlimit, and counts succeeded vision usage events in the current period againstthe quota. Covered calls are recorded with `billingMode: "included"` (zero@@ -159,8 +174,9 @@ How the third-party path works:is signature-verified and therefore a deliberate public exception to the`withDonkeyAuth` rule; it syncs subscription lifecycle and the call quota.Checkout, portal, subscription, and usage live under `/api/billing/**`.-- The dashboard (`/dashboard`) is client-rendered; all data access goes through- the audited TanStack Query hooks in `site/src/queries/`.+- The per-user account views (`/app/settings`, including API keys and usage)+ are client-rendered; all data access goes through the audited TanStack Query+ hooks in `site/src/queries/`.## Patterndiff --git a/docs/guides/code-review.md b/docs/guides/code-review.mdindex 8b919770..19a75054 100644--- a/docs/guides/code-review.md+++ b/docs/guides/code-review.md@@ -1,21 +1,20 @@# Code Review Guide-## Purpose+We review code so the next person can read it. A change is good when a+teammate can open the file, follow the logic top to bottom, and understand why+it is correct without chasing it across the codebase. This guide is what we+look for, in Swift (`apps/Donkey`) and TypeScript (`site`) alike.-We review code so the next person can read it. A change is good when a teammate-can open the file, follow the logic top to bottom, and understand why it is-correct without chasing it across the codebase. This guide is what we look for.-It applies to Swift (`apps/Donkey`) and TypeScript (`site`) alike.--The goal of every change is to reduce the total complexity a reader has to hold+**The one rule:** every change must reduce the total complexity a reader holdsin their head. Adding code that does this is progress. Adding code that hidescomplexity behind more moving parts is not, even when each piece looks small.-## Prefer Deep Functions, Not Shallow Ones+## Function Depth-A function earns its name by hiding real work behind a simple interface. A deep-function takes a small, obvious input and saves the caller from a lot of detail.-A shallow function adds a name and a call frame but hides almost nothing.+A function earns its name by hiding real work behind a simple interface. A+deep function takes a small, obvious input and saves the caller from a lot of+detail. A shallow function adds a name and a call frame but hides almost+nothing.- Do not wrap a single call or a one-line expression in a new function just togive it a name. Inline it; the reader can see what it does.@@ -28,68 +27,64 @@ A shallow function adds a name and a call frame but hides almost nothing.When you are tempted to extract, ask: does the caller become simpler to read,or does it just gain another name to follow? Extract only for the former.-## Keep Indirection to a Minimum+## IndirectionEvery layer the reader must step through to find the real behavior is a tax.Pay it only when it buys something.-- Prefer a direct call to a small ladder of pass-through wrappers, adapters, and+- Prefer a direct call to a ladder of pass-through wrappers, adapters, andre-exports that only forward arguments.- Do not add an interface, protocol, or injection seam for a singleimplementation that has no second caller and no test that needs to fake it.- Avoid barrel/`index.ts` re-exports and broad protocol indirection that existonly to look layered. Import the concrete thing directly.-- A reader should reach the code that does the work in one or two hops, not five.+- A reader should reach the code that does the work in one or two hops, not+ five.Indirection that maps to a real boundary is good: the Swift MVC split(`docs/guides/swift-mvc.md`) and the typed harness/model boundaries-(`docs/guides/agent-harness.md`) exist for reasons. The tax is forwarding layers-that exist for their own sake.+(`docs/guides/agent-harness.md`) exist for reasons. The tax is forwarding+layers that exist for their own sake.-## Simplify the Design+## Design Simplicity- Solve the problem in front of you. Do not add configuration, generality, orextension points for a future that has not arrived.-- Remove derivable or duplicated state. If a value can be computed from another,- compute it; do not store and sync two copies.+- Remove derivable or duplicated state. If a value can be computed from+ another, compute it; do not store and sync two copies.- Collapse special cases into the shared mechanism instead of bolting another- branch onto it. A growing pile of special cases usually means the underlying- design needs to change, not that it needs one more `if`.+ branch onto it. A growing pile of special cases means the underlying design+ needs to change, not that it needs one more `if`.- Build forward. Update callers to the new shape rather than keepingcompatibility shims and dead branches. Ask before keeping a shim.- Delete code the change makes unreachable. Do not leave it commented out.-## Write For Human Readers+## Readability-- Names should carry the meaning. A reader who knows only the name should guess- the behavior. Rename before you comment around a confusing name.-- Comments explain *why* — the constraint, the edge case, the reason this is not- the obvious approach. Do not narrate *what* the code already says.+- Names carry the meaning. A reader who knows only the name should guess the+ behavior. Rename before you comment around a confusing name.+- Comments explain *why* — the constraint, the edge case, the reason this is+ not the obvious approach. Do not narrate *what* the code already says.- Keep nesting shallow. Return early, handle the error case first, and let themain path run down the left margin.- Keep the happy path obvious and the rare path out of its way.-- Match the surrounding code's idiom, naming, and comment density. A change that- reads like the file around it is easier to trust.+- Match the surrounding code's idiom, naming, and comment density. A change+ that reads like the file around it is easier to trust.## Repo-Specific Rules-- Never infer user intent by matching raw input text. No phrase lists, prefixes,- regexes, or app-name checks to decide what the user wants. Route the turn- through an LLM or a typed model boundary, then match on structured output- only. See `docs/guides/agent-harness.md`.-- Keep the Swift MVC boundaries intact: views render and emit intents, models- own state, controllers own AppKit. See `docs/guides/swift-mvc.md`.-- For `site`, follow `docs/guides/frontend-nextjs-guidelines.md`: server- components by default, no `fetch` from components, no `any`.-- Never commit secrets, keys, tokens, or PII. This repo is open source.--## Review Checklist--- Does each new function hide enough to justify its interface, or is it shallow?-- Can the reader reach the real work in one or two hops?-- Is there state that could be derived instead of stored and kept in sync?-- Is a new special case hiding a design that should be generalized instead?-- Does a name need a comment to be understood? Rename it.-- Is there a compatibility shim or dead branch that should be removed instead?-- Does any code decide semantic intent by matching raw user text?-- Does the change read like the code around it?+1. **Never match raw user text for intent.** No phrase lists, prefixes,+ suffixes, regexes, app-name checks, or greeting/help classifiers. Route the+ turn through an LLM or a typed model boundary, then match on structured+ output only. See `docs/guides/agent-harness.md`.+2. **Keep the Swift MVC boundaries intact.** Views render and emit intents,+ models own state, controllers own AppKit. See `docs/guides/swift-mvc.md`.+3. **Follow the site guides.** For `site` UI,+ `docs/guides/frontend-nextjs-guidelines.md`: server components by default,+ no `fetch` from components, no `any`. For database work,+ `docs/guides/backend-apis.md`: no hand-written SQL migrations, no+ `prisma migrate` or `prisma db push`, and Prisma models in grouped sibling+ `.prisma` files, never in `schema.prisma`.+4. **Confirm the required checks ran.** `npm run lint` and `npm run build` for+ `site` changes; focused `swift test` runs for harness changes.+5. **Never commit secrets, keys, tokens, or PII.** This repo is open source.diff --git a/docs/guides/decision-system.md b/docs/guides/decision-system.mdindex cfecdd44..37e4651e 100644--- a/docs/guides/decision-system.md+++ b/docs/guides/decision-system.md@@ -1,92 +1,81 @@# Decision System-## Purpose--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.--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.--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.--## Model Boundary--User-query 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 hosted decision output is strict `generic_harness_planning` JSON. It carries:--- structured intent-- ambiguity and risk-- context needs-- plan steps-- verification criteria-- fallbacks-- clarification policy--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.--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.--## Local App Plans--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.--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.--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.+How Donkey decides what a user turn becomes: a conversational answer, a+clarifying question, a permission request, guarded action on the Mac, or+nothing at all. Every prompt, voice transcript, file drop, and follow-up is a+task-thread turn first, and the mechanics of running an actionable turn live in+`docs/guides/agent-harness.md` — this guide covers only how the decision is+made and what each outcome means.++**The one rule:** action is never the default. A local action starts only+after a typed model boundary says the turn is actionable and the runtime+validates the tool call, permissions, focus, and safety class. If you're+tempted to decide actionability by matching the user's words —+`if command.contains("open")` — stop: semantic decisions belong to the model+boundaries below, and deterministic code matches only their typed output.++## How a Turn Is Decided++Two hosted model boundaries make every semantic decision. Both call the+authenticated Donkey backend with `store=false`; the backend owns provider and+concrete model selection.++```text+user turn+ |+ v+1. Request understanding (once per turn)+ HostedHarnessRequestUnderstanding -> restated goal, target app (or none),+ parameters, success criteria, needsClarification + clarifying question+ |+ v+2. Per-step planning (loop)+ HostedHarnessStepPlanner -> one tool call per step: { tool, input, reason }+ Responding conversationally, asking for clarification, and requesting a+ permission are tools the planner picks like any other.+```++The model decides *what* the turn means and which tool comes next; Swift+decides *whether and how* the call runs. If understanding fails or times out,+the loop degrades to planning against the raw goal — it never blocks the turn.++## Outcomes++| Turn | Outcome |+|---|---|+| Empty or whitespace input | no-op decision; the prepared task completes immediately, no action runs |+| Question, greeting, chat | planner picks the respond tool; conversational answer, no action state |+| Actionable with a clear target | guarded harness loop runs to completion with evidence |+| Actionable but missing a required detail | clarify tool → task `waitingForUser` with one specific question |+| Action needs an ungranted permission | permission request → task `waitingForPermission` |+| Cannot proceed safely | failed-safe with an honest report, never a silent guess |++A runnable local task needs a clear action, a resolvable target, and enough+payload to execute safely. Vague requests ask for the one missing detail+instead of guessing.## Validation-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. Verification can combine-input evidence and observed result evidence when a capability requires it.--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.--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.--## Learning+Every planned tool call is validated before execution: the tool must exist in+the registry, its permissions must be granted, the target window must hold+focus, and its safety class must allow the action. AppleScript runs only as+validated generated artifacts — free-form planner text is never executed+directly. Completion requires evidence: the runtime rejects a completion whose+last state-changing step has no later succeeded verification step.-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.+## Visualization Is Evidence-Derived-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.+The cursor playback users see is built only from grounded runtime evidence —+observed control bounds and succeeded action traces with screen coordinates —+never from planner text or invented positions. Harness path playback flows+through the `agent.path.visualize` tool, which returns a plan only after every+waypoint is grounded.## Source Entry Points-- Prompt handling: `apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift`-- Hosted decision adapter: `apps/Donkey/Sources/DonkeyAI/HostedTaskIntentParsingAdapter.swift`-- Catalog validation: `apps/Donkey/Sources/DonkeyRuntime/LocalAppTaskCatalog.swift`-- Generic lifecycle bridge: `apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift`+| Module | Owns |+|---|---|+| `apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift` | turn entry, outcome handling, visualization |+| `apps/Donkey/Sources/DonkeyAI/HostedHarnessRequestUnderstanding.swift` | one-shot request understanding |+| `apps/Donkey/Sources/DonkeyAI/HostedHarnessStepPlanner.swift` | per-step tool decisions |+| `apps/Donkey/Sources/DonkeyRuntime/AppHarnessGenericLifecycle.swift` | thread/task lifecycle and context compaction |diff --git a/docs/guides/donkey-vision.md b/docs/guides/donkey-vision.mdindex 530eebd5..3066dc61 100644--- a/docs/guides/donkey-vision.md+++ b/docs/guides/donkey-vision.md@@ -1,103 +1,89 @@# Donkey Vision-## What It Is--Donkey Vision is the observation layer that helps Donkey understand what is on a-user's computer screen well enough to reason about it. It is not a single model-or a single provider. It is a fusion system: local Mac evidence gives Donkey-grounded geometry, and AI helps interpret what those grounded regions mean.--The practical goal is simple: when Donkey needs to navigate around a user's-computer, it should know where UI elements are, what they probably are, and how-confident it should be. The answer should be useful without pretending that a-vision model's bounding boxes are perfect.--## Why Fusion Exists--No single source is enough.--Accessibility is the best source when an app exposes good native controls. It-can give precise bounds, roles, labels, and supported actions. But many modern-desktop apps are web or Electron shells, and their Accessibility trees can be-sparse, grouped, stale, or missing important icon controls.--Screenshots see what the user sees. Native visual detection can find shapes,-rows, panels, input surfaces, and icon-like regions from pixels. It is useful for-geometry, especially when Accessibility is thin, but it does not always know the-semantic name of a control.--AI can read the scene and recognize likely UI concepts across apps. It can say-"this looks like a search field", "this row is a project", or "this icon is a-voice button." But AI bounding boxes are approximate. They can be off by a few-pixels, too large, shifted to adjacent text, or attached to the wrong nearby-region. AI boxes are evidence, not authority.--Donkey Vision combines these strengths:--- Accessibility provides trusted local structure when available.-- AI provides semantic enrichment and fills gaps.-- Fusion decides which evidence should render or feed downstream reasoning.--## Geometry Rule--Local geometry wins.--If Donkey has a grounded local box from Accessibility or window chrome-geometry, that box should be preferred over an overlapping AI box. AI may enrich-the label or explain what the region probably means, but it should not replace-precise local geometry with a model-estimated rectangle. Native screenshot CV is-not part of the live Donkey Vision overlay pipeline.+Donkey Vision is the observation layer that turns the user's windows into+structured UI understanding the agent can reason about. It is not one model or+one provider — it is a fusion system: local Mac evidence gives grounded+geometry, and hosted AI enrichment interprets what those grounded regions+mean. The engine runs always-on and headless in production; the developer+overlay is just a window into it.++**The one rule:** local geometry wins. If a grounded local box exists from+Accessibility or window-chrome geometry, an overlapping AI box may enrich its+label but never replaces its rectangle. If an AI box is visibly off, do not+"fix" it with coordinate offsets — improve local geometry, fusion, or the+screenshot scope instead.++## How It Works++```text+frontmost-window monitor (screenshot fingerprint, re-parses on large change)+ |+ v+UIUnderstandingCoordinator captures the changed window+ |- Accessibility read: roles, labels, precise bounds, supported actions+ |- native visual detection: shapes, rows, panels, icon regions from pixels+ |- hosted vision parse (POST /api/vision) only when that window's pixels+ | changed since the last successful parse; unchanged windows reuse their+ | carried-forward boxes+ v+fusion: local geometry wins; AI enriches labels and fills uncovered gaps+ |+ v+WindowUIUnderstandingStore (per-window cache)+ |+ v+the agent's captureAndAnalyze reads the store first; the debug overlay+renders the same evidence when enabled+```-This is especially important for:+Local evidence decides *where* things are; AI decides *what* they probably+mean. Fusion decides which evidence renders or feeds downstream reasoning.-- macOS traffic-light controls and titlebar buttons-- sidebars and navigation rows-- search fields and command inputs-- bottom composers and submit controls-- small icon-only toolbar buttons-- repeated list rows where nearby text can confuse model localization+Each source covers the others' blind spots. Accessibility is precise when an+app exposes native controls, but web and Electron shells leave it sparse or+stale. Native visual detection finds geometry in any pixels but not semantic+names. Hosted AI recognizes UI concepts across apps ("this is a search field",+"this icon is a voice button") but its bounding boxes are approximate — off by+pixels, too large, or attached to nearby text. AI boxes are evidence, not+authority.-AI-only boxes are still useful when no local evidence covers that part of the-screen. They should be marked as AI/read-only evidence so maintainers can see-that the position came from the model.+An older streaming screenshot-parse path is kept compiled behind the+coordinator's `remoteAIEngine` switch, which is currently hardcoded to the+vision path.## Safety Boundary-Donkey Vision is observation first, and it can now supply a secondary live-input-target when Accessibility cannot provide a better element.--Vision evidence can help Donkey plan, explain, debug, decide where to look next,-and choose a coordinate click target. Live input still has to pass through the-guarded action boundary: target validation, focus checks, permission policy,-action eligibility, and runtime verification.+Donkey Vision is observation first; it can also supply a secondary live-input+target when Accessibility cannot provide a better element. Live input always+passes through the guarded action boundary: target validation, focus checks,+permission policy, action eligibility, and runtime verification. Input tries+Accessibility first, then AI visual targets, then guarded coordinate click+fallback.-AI-derived evidence is especially constrained:+AI-derived evidence is specially constrained:-- AI boxes may be interactable when they come from a scoped app/window or+- AI boxes may be interactable only when they come from a scoped app/window orsystem-navigation screenshot and are marked `guardedAction`.-- AI output may provide a coordinate click target after the Accessibility path- fails or is unavailable. The executor clicks the guarded target center, not an- unbounded desktop coordinate.+- AI output may provide a coordinate click target only after the Accessibility+ path fails or is unavailable; the executor clicks the guarded target center,+ never an unbounded desktop coordinate.- Screenshots sent to hosted AI must be scoped to an app/window or asystem-navigation surface, never the full desktop.- Screenshots are not persisted or logged as general product data.## Developer Overlay-The developer overlay is a way to see Donkey Vision while debugging. It should-render multiple evidence sources at the same time, with visible source badges:+The overlay renders the live fusion result for debugging, with a visible+source badge on every box:-- `AX` for Accessibility-backed boxes-- `AI` for hosted AI boxes+| Badge | Source | If a box is off |+|---|---|---|+| `AX` | Accessibility | local coordinate mapping bug — fix the Mac geometry path |+| `CV` | native visual detection | local detector issue — fix detection, not offsets |+| `AI` | hosted vision parse | expected model localization error — never add coordinate offsets |-The distinction matters. If an `AI` box is visibly off, that is expected model-localization error and should not be fixed by adding arbitrary coordinate-offsets. Prefer improving local geometry, fusion, or the screenshot scope. If an-`AX` box is off, that is a local coordinate mapping bug and should be fixed in-the Mac geometry path. Live input tries Accessibility first, then AI visual-targets, then guarded coordinate click fallback.--The debug config uses Donkey Vision as the mode:+The overlay is enabled through `dev-overlay.json` (see+`docs/guides/user-query-overlay.md` for where the config lives):```json{@@ -110,39 +96,31 @@ The debug config uses Donkey Vision as the mode:}```-Do not add a provider field to this config. Donkey Vision is always local AX-evidence plus hosted AI enrichment; the config controls cadence, scope, and-filters, not which evidence source runs.--## AI Source--The hosted AI evidence comes from the vision endpoint-(`POST /api/vision`, RunPod OmniParser V2). The overlay coordinator-hashes each window screenshot and only calls the endpoint when that window's-pixels changed since the last successful parse; unchanged windows reuse their-carried-forward boxes. The older streaming screenshot-parse path is kept compiled-but disabled behind `remoteAIEngine` in the coordinator so it can be switched back-while we iterate on vision.+Optional `targetBundleIdentifiers` / `targetAppNames` fields narrow the+overlay to specific apps. Do not add a provider field to this config. Donkey+Vision is always local evidence plus hosted AI enrichment; the config controls+cadence, scope, and filters, not which evidence source runs.## Source Map-High-signal entry points:--- `apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionCoordinator.swift`-- `apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionOverlayController.swift`-- `apps/Donkey/Sources/DonkeyAI/DebugUIInspectionFrameFusion.swift`-- `apps/Donkey/Sources/DonkeyAI/VisionParseDebugUIOverlayMapper.swift` (active AI source)-- `apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swift` (retained, disabled)-- `apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementDetectionService.swift`-- `site/src/lib/inference/vision/` and `site/src/lib/inference/screenshot-parsing/`+| Path | Owns |+|---|---|+| `apps/Donkey/Sources/Donkey/LocalUIElementDetection/UIUnderstandingCoordinator.swift` | always-on engine: capture, change detection, parse scheduling |+| `apps/Donkey/Sources/Donkey/LocalUIElementDetection/DebugUIInspectionOverlayController.swift` | debug overlay rendering and badges |+| `apps/Donkey/Sources/DonkeyAI/DebugUIInspectionFrameFusion.swift` | fusion of local and AI evidence |+| `apps/Donkey/Sources/DonkeyAI/VisionParseDebugUIOverlayMapper.swift` | active AI source mapping |+| `apps/Donkey/Sources/DonkeyAI/ScreenshotParseDebugUIOverlayMapper.swift` | retained, disabled streaming path |+| `apps/Donkey/Sources/DonkeyRuntime/LocalUIElementDetection/LocalUIElementDetectionService.swift` | native visual detection |+| `site/src/lib/inference/vision/`, `site/src/lib/inference/screenshot-parsing/` | backend vision parsing |## Maintainer Rules-- Do not treat model boxes as pixel-perfect.-- Do not add global coordinate offsets to compensate for AI localization.-- Do not send full-desktop screenshots to hosted AI.-- Do not make provider selection the UI or config model for Donkey Vision.-- Prefer app/window-scoped screenshots and local geometry.-- Keep AI evidence marked and visually distinct.-- Allow AI visual targets to drive guarded coordinate clicks only after focus,- permission, target-window, and action-eligibility checks pass.+1. **Model boxes are never pixel-perfect.** Do not add global coordinate+ offsets to compensate for AI localization.+2. **Scoped captures only.** Never send full-desktop screenshots to hosted AI.+3. **No provider switch.** Provider selection is not the UI or config model+ for Donkey Vision.+4. **AI evidence stays marked.** Keep AI boxes visually distinct and tagged so+ maintainers can see the position came from a model.+5. **Guarded input only.** AI visual targets drive coordinate clicks only+ after focus, permission, target-window, and action-eligibility checks pass.diff --git a/docs/guides/frontend-nextjs-guidelines.md b/docs/guides/frontend-nextjs-guidelines.mdindex 8f80ad0a..037f5db5 100644--- a/docs/guides/frontend-nextjs-guidelines.md+++ b/docs/guides/frontend-nextjs-guidelines.md@@ -1,72 +1,97 @@# Frontend and Next.js Guidelines-This guide explains how to work in the `site` app. Keep changes aligned with the existing route structure, Tailwind styling, and server/client boundaries.+How to work in the `site` Next.js app: route structure, server/client+boundaries, Tailwind styling, and data access.++**The one rule:** React components never call `fetch(...)` directly.+Client-side data access goes through TanStack Query hooks in `src/queries/`;+server-side data access stays in server code. If you're tempted to fetch+inline, the call belongs in a hook.## Project Shape-- Keep routes, layouts, pages, loading states, and route handlers in `src/app`.-- Keep shared UI primitives in `src/components`.-- Keep route-specific UI near the route, such as `src/app/_components/landing` for the home page.+- Routes, layouts, pages, loading states, and route handlers live in+ `src/app`.+- Shared UI primitives live in `src/components`; route-specific UI stays near+ the route, such as `src/app/_components/landing` for the home page.+- Server-only helpers live in `src/lib`.- Split large route experiences into focused component files.-- Keep server-only helpers in `src/lib`.-- Use absolute imports through the `@/*` alias.-- Avoid barrel `index.ts` files unless a package-level public API truly needs one.+- Use absolute imports through the `@/*` alias; avoid barrel `index.ts` files+ unless a package-level public API truly needs one.## Components-- Treat components as Server Components by default.-- Add `"use client"` only for state, effects, refs, event handlers, browser APIs, or client-only hooks.+- Components are Server Components by default. Add `"use client"` only for+ state, effects, refs, event handlers, browser APIs, or client-only hooks.- Keep client boundaries small and close to the interactive control.- Keep secrets and direct database access out of Client Components.- Pass plain serializable props from Server Components into Client Components.## Navigation-- Use the `next/link` `<Link>` component for internal routes (anything starting with `/`) so navigation stays client-side and prefetches.-- Use a plain `<a>` only for external URLs, `mailto:`, and other non-route links.-- When a shared control accepts an arbitrary `href` (such as the landing `PillButton`), let the control pick `<Link>` vs `<a>` from the href instead of duplicating that choice at every call site.+- Use the `next/link` `<Link>` component for internal routes (anything+ starting with `/`) so navigation stays client-side and prefetches. Use a+ plain `<a>` only for external URLs, `mailto:`, and other non-route links.+- When a shared control accepts an arbitrary `href` (such as the landing+ `PillButton`), let the control pick `<Link>` vs `<a>` from the href instead+ of duplicating that choice at every call site.## Styling-- Tailwind utility classes are the default for all UI, with no exceptions by area. This includes the landing components under `src/app/_components/landing`, which were historically inline-styled and are now Tailwind-first. Do not reintroduce React inline `style` objects for layout, spacing, typography, colors, borders, or responsive behavior.-- Tailwind is configured via CSS (`@theme` in `src/app/globals.css`), not a `tailwind.config.*` file; its absence is not a reason to use inline styles.-- Use the brand tokens defined in `globals.css` rather than repeating raw hex: `text-ink`/`bg-ink`/`border-ink` (near-black), `bg-coral`/`text-coral`, `bg-cream`, `bg-background` (page sand), and `font-system`/`font-code`. Reach for a Tailwind arbitrary value (`text-[#454545]`, `text-[clamp(45px,9.6vw,134px)]`) only for genuinely one-off values not worth a token.-- Use Tailwind responsive variants for breakpoints (`md:*`, and arbitrary variants like `min-[900px]:*` when a design uses a non-standard breakpoint). Do not add client-only media-query hooks to choose styling; express responsive styling in classes and, when an element only differs by visibility, toggle it with `hidden`/`md:block` rather than conditional rendering.-- Reserve inline `style` strictly for genuinely runtime values, such as a dimension computed from props or state, CSS custom properties derived from data, or a third-party style API.+- Tailwind utility classes are the default for all UI, with no exceptions by+ area. Do not write React inline `style` objects for layout, spacing,+ typography, colors, borders, or responsive behavior. Reserve inline `style`+ strictly for genuinely runtime values: a dimension computed from props or+ state, CSS custom properties derived from data, or a third-party style API.+- Tailwind is configured via CSS (`@theme` in `src/app/globals.css`), not a+ `tailwind.config.*` file; its absence is not a reason to use inline styles.+- Use the brand tokens defined in `globals.css` rather than repeating raw hex:+ `text-ink`/`bg-ink`/`border-ink` (near-black), `bg-coral`/`text-coral`,+ `bg-cream`, `bg-background` (page sand), and `font-system`/`font-code`.+ Reach for a Tailwind arbitrary value (`text-[#454545]`,+ `text-[clamp(45px,9.6vw,134px)]`) only for genuinely one-off values not+ worth a token.+- Use Tailwind responsive variants for breakpoints (`md:*`, and arbitrary+ variants like `min-[900px]:*` for a non-standard breakpoint). Do not add+ client-only media-query hooks to choose styling. When an element only+ differs by visibility, toggle it with `hidden`/`md:block` rather than+ conditional rendering.- Compose conditional classes with the `cn` helper from `@/lib/utils`.-- Prefer existing icon components for buttons and compact actions when an icon fits the control.-- Keep controls at stable dimensions so hover states, icons, labels, and loading states do not shift layout.-- Keep cards for repeated items, modals, and genuinely framed content. Avoid nesting cards inside cards.+- Prefer existing icon components for buttons and compact actions when an icon+ fits the control.+- Keep controls at stable dimensions so hover states, icons, labels, and+ loading states do not shift layout.+- Keep cards for repeated items, modals, and genuinely framed content. Avoid+ nesting cards inside cards.## Data and APIs-- Put Route Handlers in `src/app/api/**/route.ts`.-- Protect Donkey APIs unless an endpoint is intentionally public.-- Validate request bodies, search params, and route params before using them.-- Keep API responses explicit and consistently shaped.-- Do not call `fetch(...)` directly from React components. Client-side data- access goes through TanStack Query hooks, and every query/mutation hook lives- in `src/queries/` so the cache surface is auditable in one place. Components- import the hooks; they do not fetch inline. The shared fetch wrapper and error- type are `src/queries/apiClient.ts`. Define each query's key as a constant- alongside its hook in the same module (export it if another module needs to- invalidate it). Mount `QueryProvider` once at the root layout.-- Dashboard-style, per-user data views are client-rendered and read their data- through these hooks. The route handlers still enforce auth server-side, so a- client guard is for UX, not security.-- Use database clients only from server-side code.-- Do not run database migrations or schema pushes casually; choose the migration workflow deliberately for the target database.+- Route Handlers live in `src/app/api/**/route.ts` and follow+ `docs/guides/backend-apis.md` — authenticated by default, Zod-validated,+ explicit responses.+- Every query/mutation hook lives in `src/queries/` so the cache surface is+ auditable in one place. Components import the hooks; they do not fetch+ inline. The shared fetch wrapper and error type are+ `src/queries/apiClient.ts`. Define each query's key as a constant alongside+ its hook in the same module (export it if another module needs to invalidate+ it). Mount `QueryProvider` once at the root layout.+- Per-user account views (`/app/settings`, including API keys and usage) are+ client-rendered and read their data through these hooks. The route handlers+ still enforce auth server-side, so a client guard is for UX, not security.+- Use database clients only from server-side code, and never run migrations or+ schema pushes casually; choose the migration workflow deliberately for the+ target database.## TypeScript-- Use `type` for props and local data shapes.-- Prefer a short `Props` name when there is only one props type in the file.+- Use `type` for props and local data shapes; prefer a short `Props` name when+ there is only one props type in the file.- Do not use `any`; define the narrowest useful type or stop and clarify.-- Prefer optional chaining (`a?.b`) over `a && a.b` or `!a || !a.b` when reading- a possibly-absent member.+- Prefer optional chaining (`a?.b`) over `a && a.b` or `!a || !a.b` when+ reading a possibly-absent member.- Keep imports direct and explicit.-- Include real dependencies in hooks.-- Store callbacks in refs when they should not trigger re-renders.+- Include real dependencies in hooks; store callbacks in refs when they should+ not trigger re-renders.## Checksdiff --git a/docs/guides/install-donkey.md b/docs/guides/install-donkey.mdindex 9bc0ce36..53339492 100644--- a/docs/guides/install-donkey.md+++ b/docs/guides/install-donkey.md@@ -1,6 +1,10 @@# Install Donkey Locally-Donkey can be packaged into a local macOS app bundle and drag-to-Applications disk image for manual testing or site distribution.+Donkey packages into a local macOS app bundle and a drag-to-Applications disk+image for manual testing or site distribution. Production releases run the+same packaging through GitHub Actions — see `docs/guides/releasing-donkey.md`.++## PackagingFrom the repo root:@@ -8,12 +12,15 @@ From the repo root:./scripts/package-donkey-app.sh```-The drag-to-Applications background is rendered from SVG, so local packaging-requires ImageMagick's `magick` command.--The script builds the release executable, creates `dist/Donkey.app`, copies bundled resources and embedded frameworks, ensures the executable can load those frameworks from the app bundle, applies an ad-hoc signature when `codesign` is available, and creates `dist/Donkey.dmg`.+The script builds the release executable, creates `dist/Donkey.app`, copies+bundled resources and embedded frameworks, ensures the executable can load+those frameworks from the app bundle, applies an ad-hoc signature when+`codesign` is available, and creates `dist/Donkey.dmg`. The drag-to-Applications+background is rendered from SVG, so local packaging requires ImageMagick's+`magick` command.-The app bundle version defaults to `0.1.0` build `1`. Override it for local release testing:+The app bundle version defaults to `0.1.0` build `1`. Override it for local+release testing:```bashDONKEY_APP_VERSION="0.1.1" \@@ -23,54 +30,40 @@ DONKEY_APP_BUILD="2" \The app bundle registers the `donkey://auth/callback` sign-in callback andopens the site `/mac-auth` handoff for Google OAuth before the overlay starts.-Packaged apps point auth and hosted inference at the same base URL:-`https://donkeyuse.com` by default.--Override the single base URL for local or staging testing:+Packaged apps point auth and hosted inference at the same base URL —+`https://donkeyuse.com` by default. Override it for local or staging testing:```bashDONKEY_WEB_BASE_URL="http://localhost:3000" ./scripts/package-donkey-app.sh```-For local distribution testing, publish the disk image:--```text-dist/Donkey.dmg-```--Opening the disk image mounts a `Donkey` volume with a custom Finder installer-window: `Donkey.app` sits on the left, the `Applications` shortcut sits on the-right, and the background arrow points users through the drag-to-Applications-flow. The installer artwork lives in `scripts/assets/donkey-dmg-background.svg`;-the package script renders that SVG into the Finder background and writes the-Finder layout into the compressed disk image so users see the install screen-immediately after opening `Donkey.dmg`.-The user installs Donkey by dragging the app onto the shortcut, which copies it-into `/Applications`.--To launch the packaged app:+Launch the packaged app with `open dist/Donkey.app`; test the installer flow+with `open dist/Donkey.dmg`.-```bash-open dist/Donkey.app-```+## The Disk Image-To test the installer flow:+Opening `dist/Donkey.dmg` mounts a `Donkey` volume with a custom Finder+installer window: `Donkey.app` on the left, the `Applications` shortcut on the+right, and a background arrow pointing users through the drag-to-Applications+flow. The user installs Donkey by dragging the app onto the shortcut, which+copies it into `/Applications`.-```bash-open dist/Donkey.dmg-```+The installer artwork lives in `scripts/assets/donkey-dmg-background.svg`. The+package script renders that SVG into the Finder background and writes the+Finder layout into the compressed disk image, so users see the install screen+immediately after opening `Donkey.dmg`.## Sparkle Updates-Donkey uses Sparkle for app updates. Do not add a Donkey-specific update installer or custom replacement flow; Sparkle owns appcast parsing, update validation, download, install, relaunch, and user-facing update UI.--Production releases are distributed from GitHub Releases. See-`docs/guides/releasing-donkey.md` for the release runbook. Do not use the-Supabase Storage `/release` bucket for release binaries or appcast hosting.+Donkey uses Sparkle for app updates. Do not add a Donkey-specific update+installer or custom replacement flow; Sparkle owns appcast parsing, update+validation, download, install, relaunch, and user-facing update UI.-The public Sparkle feed lives in `site/public/appcast.xml`, which the site-serves as `https://donkeyuse.com/appcast.xml`. Appcast enclosure URLs point to-the numeric GitHub Release asset URL, not a moving `latest` or `-latest` URL.+The public Sparkle feed lives in `site/public/appcast.xml`, served as+`https://donkeyuse.com/appcast.xml`. Appcast enclosure URLs point to the+numeric GitHub Release asset URL, not a moving `latest` or `-latest` URL. Do+not use the Supabase Storage `/release` bucket for release binaries or appcast+hosting.Configure Sparkle when packaging:@@ -85,61 +78,56 @@ DONKEY_SPARKLE_PUBLIC_ED_KEY="..." \For local update testing, use Sparkle's standard local appcast workflow:1. Package the older app and install it in `/Applications`.-2. Package the newer app with a higher `DONKEY_APP_VERSION` / `DONKEY_APP_BUILD`.-3. Use Sparkle's `generate_appcast` tooling over the folder containing the newer update archive.-4. Package or launch the older app with `DONKEY_SPARKLE_FEED_URL` pointing to the local `file://` appcast and `DONKEY_SPARKLE_PUBLIC_ED_KEY` set to the matching public EdDSA key.--Example feed URL shape:--```bash-DONKEY_SPARKLE_FEED_URL="file:///Users/me/donkey-updates/appcast.xml"-```--When Sparkle finds a valid signed update, the expanded notch task panel shows an update button in its header. Clicking it invokes Sparkle's standard update UI.+2. Package the newer app with a higher `DONKEY_APP_VERSION` /+ `DONKEY_APP_BUILD`.+3. Run Sparkle's `generate_appcast` tooling over the folder containing the+ newer update archive.+4. Package or launch the older app with `DONKEY_SPARKLE_FEED_URL` pointing to+ the local `file://` appcast (e.g.+ `file:///Users/me/donkey-updates/appcast.xml`) and+ `DONKEY_SPARKLE_PUBLIC_ED_KEY` set to the matching public EdDSA key.++When Sparkle finds a valid signed update, the expanded notch task panel shows+an update button in its header. Clicking it invokes Sparkle's standard update+UI.## Hosted ModelsThe packaged Mac app does not bundle, download, install, or configure local-model weights. Model-backed behavior is routed through the authenticated Donkey-backend, which owns provider credentials, provider selection, and concrete model-selection. The Mac client sends typed requests to the backend and does not need-OpenAI, Gemini, or other provider API keys.--First launch setup is therefore an account and permission setup flow, not a-local model installer. After sign-in, Donkey asks for Accessibility,-Screenshots, and Microphone with user-visible reasons before starting the-overlay. Protected folders such as Desktop, Documents, and Downloads remain-lazy and are requested only when a user-requested local-item lookup needs them.-There are no supported release manifest URLs, model weight override URLs, local-LLM packages, or local model repair steps in the hosted-model install path.+model weights. Model-backed behavior routes through the authenticated Donkey+backend, which owns provider credentials, provider selection, and concrete+model selection. The Mac client sends typed requests to the backend and needs+no OpenAI, Gemini, or other provider API keys.++First launch is therefore an account and permission setup flow, not a local+model installer. After sign-in, Donkey asks for Accessibility, Screenshots,+and Microphone with user-visible reasons before starting the overlay.+Protected folders such as Desktop, Documents, and Downloads remain lazy and+are requested only when a user-requested local-item lookup needs them. There+are no supported release manifest URLs, model weight override URLs, local LLM+packages, or local model repair steps in the hosted-model install path.## Local Development-For local development, `scripts/run-donkey-dev.sh` starts the local site when-`DONKEY_WEB_BASE_URL` points at localhost, builds Donkey, wraps the debug-executable in `apps/Donkey/.build/debug/Donkey Dev.app`, registers that app-bundle for `donkey://auth/callback`, and launches it. The debug wrapper uses the-`Donkey Dev` display name and `ai.donkey.Donkey.dev` bundle identifier by-default so macOS privacy settings do not collide with packaged `Donkey.app`-builds.-```bash./scripts/run-donkey-dev.sh```-Use `DONKEY_START_SITE=0` to skip starting the site, `DONKEY_LAUNCH_APP=0` to-build and register the debug app without opening it, or `DONKEY_WEB_BASE_URL` /-`DONKEY_AUTH_CALLBACK_SCHEME` to test a different auth handoff. Set-`DONKEY_CODESIGN_IDENTITY` to a local code-signing identity when you want macOS-privacy grants to use that identity; without one, the script falls back to-ad-hoc signing with a stable dev designated requirement. When the dev script-exits or receives `SIGINT`, `SIGTERM`, or hangup, it stops running `Donkey`,-`Donkey Dev`, and bundled Donkey sidecar processes unless-`DONKEY_KEEP_APP_ON_EXIT=1` is set. Before rebuilding the dev app bundle, it-also stops running Donkey app processes by default; set-`DONKEY_STOP_APPS_BEFORE_BUILD=0` only when intentionally inspecting a running-build.--Development builds use the same hosted-model boundary as packaged builds. If a-developer needs to test provider behavior, configure the site/backend-environment and keep provider credentials out of the Mac app.+The dev script starts the local site when `DONKEY_WEB_BASE_URL` points at+localhost, builds Donkey, wraps the debug executable in+`apps/Donkey/.build/debug/Donkey Dev.app`, registers that bundle for+`donkey://auth/callback`, and launches it. The debug wrapper uses the+`Donkey Dev` display name and `ai.donkey.Donkey.dev` bundle identifier by+default so macOS privacy settings do not collide with packaged `Donkey.app`+builds. Development builds use the same hosted-model boundary as packaged+builds; to test provider behavior, configure the site/backend environment and+keep provider credentials out of the Mac app.++| Variable | Effect |+|---|---|+| `DONKEY_START_SITE=0` | skip starting the site |+| `DONKEY_LAUNCH_APP=0` | build and register the debug app without opening it |+| `DONKEY_WEB_BASE_URL` / `DONKEY_AUTH_CALLBACK_SCHEME` | test a different auth handoff |+| `DONKEY_CODESIGN_IDENTITY` | sign with a local identity so macOS privacy grants stick to it; otherwise ad-hoc signing with a stable dev designated requirement |+| `DONKEY_KEEP_APP_ON_EXIT=1` | don't stop running `Donkey`, `Donkey Dev`, and sidecar processes when the script exits or receives `SIGINT`/`SIGTERM`/hangup |+| `DONKEY_STOP_APPS_BEFORE_BUILD=0` | don't stop running Donkey app processes before rebuilding (only when intentionally inspecting a running build) |diff --git a/docs/guides/releasing-donkey.md b/docs/guides/releasing-donkey.mdindex 62a97fa2..4d342bc4 100644--- a/docs/guides/releasing-donkey.md+++ b/docs/guides/releasing-donkey.md@@ -1,32 +1,47 @@# Releasing Donkey-Donkey production releases are distributed through GitHub Releases. The-Supabase Storage `/release` bucket is not part of the release path.--The release entrypoint is the `Release Donkey` GitHub Actions workflow. A-maintainer chooses whether to bump the major, minor, or patch version in the-GitHub UI, and the workflow builds the latest default-branch code into the-release artifact.--Nightly prereleases use a separate `Nightly Donkey Build` GitHub Actions-workflow. It builds changed default-branch code on a schedule and publishes the-result to the moving `nightly` prerelease.--## Release Boundaries--- Release tags use numeric SemVer in `vMAJOR.MINOR.PATCH` form, such as- `v0.1.1`.-- The GitHub Release asset is `Donkey.dmg`.-- The workflow also uploads `Donkey.dmg.sha256`.-- The website download URL points to the promoted numeric release asset, not a- moving `latest` or `-latest` URL.-- The production release workflow keeps the latest 10 numeric GitHub Releases- and deletes older numeric release records after promotion. It does not delete- Git tags, aliases, or the nightly prerelease.-- The public Sparkle appcast is committed at `site/public/appcast.xml` and- served as `https://donkeyuse.com/appcast.xml`.-- Sparkle signs and validates update archives; do not add a Donkey-specific- updater or replacement installer.+Donkey production releases are distributed through GitHub Releases, built by+the `Release Donkey` GitHub Actions workflow from the latest default-branch+code. A separate `Nightly Donkey Build` workflow publishes a smoke-test+prerelease on a schedule. The Supabase Storage `/release` bucket is not part+of the release path.++**The one rule:** user-facing links use the immutable numeric tag. The website+download URL and the appcast enclosure URL point at+`/releases/download/vMAJOR.MINOR.PATCH/Donkey.dmg`, never a moving `latest` or+`-latest` URL. Alias tags exist only for maintainer convenience.++## Workflows++| | `Release Donkey` | `Nightly Donkey Build` |+|---|---|---|+| Trigger | manual: choose `patch`, `minor`, or `major` | nightly at 09:00 UTC, plus manual |+| Tag | numeric SemVer `vMAJOR.MINOR.PATCH` (starts at `0.1.0`) | moving `nightly` tag |+| Release | numeric GitHub Release, marked GitHub's latest | `Donkey Nightly Build` prerelease |+| Assets | `Donkey.dmg` + `Donkey.dmg.sha256` | `Donkey.dmg` + `Donkey.dmg.sha256` |+| Appcast / website | updates `site/public/appcast.xml` and the website download constant, commits both | untouched |+| Alias tags | moves `vMAJOR`, `vMAJOR.MINOR`, `latest` | untouched |+| Retention | keeps the latest 10 numeric releases; deletes older release records (never tags or the nightly prerelease) | n/a |+| Skip condition | none | skips when the `nightly` tag already points at the default-branch commit |++Use nightly builds to smoke-test the latest default-branch app package. Use+`Release Donkey` to publish a user-facing release.++## Release Runbook++1. Open GitHub Actions for the repository.+2. Select `Release Donkey`.+3. Click `Run workflow`.+4. Choose `patch`, `minor`, or `major`.+5. Run the workflow.++The workflow checks out the latest default branch, derives the next version+from existing numeric release tags and the selected bump, builds and packages+`dist/Donkey.dmg`, signs the DMG with the Sparkle private key, creates or+updates the numeric GitHub Release with the DMG and checksum, updates+`site/public/appcast.xml` and the website download constant and commits those+changes, marks the release as GitHub's latest, moves the alias tags, and+prunes releases beyond the latest 10.## One-Time Sparkle Setup@@ -36,13 +51,8 @@ Generate one Sparkle EdDSA signing keypair on a trusted Mac:apps/Donkey/.build/artifacts/sparkle/Sparkle/bin/generate_keys --account donkey```-Copy the printed `SUPublicEDKey` value into the GitHub repository secret:--```text-DONKEY_SPARKLE_PUBLIC_ED_KEY-```--Export the matching private key:+Copy the printed `SUPublicEDKey` value into the GitHub repository secret+`DONKEY_SPARKLE_PUBLIC_ED_KEY`. Then export the matching private key:```bashapps/Donkey/.build/artifacts/sparkle/Sparkle/bin/generate_keys \@@ -50,13 +60,8 @@ apps/Donkey/.build/artifacts/sparkle/Sparkle/bin/generate_keys \-x /tmp/donkey-sparkle-private-key.txt```-Copy the file contents into this GitHub repository secret:--```text-DONKEY_SPARKLE_PRIVATE_ED_KEY-```--Delete the exported private key file after adding the secret:+Copy the file contents into the GitHub repository secret+`DONKEY_SPARKLE_PRIVATE_ED_KEY`, then delete the exported file:```bashrm -f /tmp/donkey-sparkle-private-key.txt@@ -64,56 +69,8 @@ rm -f /tmp/donkey-sparkle-private-key.txtKeep this keypair stable. Already-installed apps trust the public key embeddedat packaging time and reject future updates signed by a different private key.--## Publishing A Release--1. Open GitHub Actions for the repository.-2. Select `Release Donkey`.-3. Click `Run workflow`.-4. Choose `patch`, `minor`, or `major`.-5. Run the workflow.--The workflow checks out the latest default branch, fetches existing numeric-release tags, derives the next version from the selected bump, builds the macOS-app, packages `dist/Donkey.dmg`, signs the DMG with the Sparkle private key,-creates or updates the numeric GitHub Release, uploads the DMG and checksum,-updates `site/public/appcast.xml`, updates the website download constant,-commits those site/appcast changes, marks the numeric release as GitHub's latest-release, and moves the alias tags. When no numeric release tag exists yet, the-workflow starts at `0.1.0`. After promotion, it deletes older production-GitHub Release records so only the latest 10 numeric releases remain.--## Alias Tags--The workflow moves these alias tags to the released commit:--- `vMAJOR`-- `vMAJOR.MINOR`-- `latest`--These aliases are for maintainer convenience. User-facing website and appcast-links must keep using the immutable numeric tag.--## Nightly Builds--The `Nightly Donkey Build` workflow runs nightly at 09:00 UTC and can also be-started manually from GitHub Actions. It compares the default-branch commit to-the current `nightly` tag before installing packaging dependencies. If the tag-already points at the default-branch commit, the workflow skips packaging and-publishing. When the default branch has changed, it packages `dist/Donkey.dmg`,-generates `dist/Donkey.dmg.sha256`, moves the `nightly` tag to that commit, and-creates or updates the `Donkey Nightly Build` prerelease.--Nightly builds are intentionally separate from production releases:--- They do not use numeric SemVer tags.-- They do not update `site/public/appcast.xml`.-- They do not update the website download version.-- They do not move production alias tags.-- They are not marked as GitHub's latest release.--Use nightly builds for smoke testing the latest default-branch app package.-Use the `Release Donkey` workflow when publishing a user-facing release.+Sparkle signs and validates update archives; do not add a Donkey-specific+updater or replacement installer.## Verification@@ -122,12 +79,12 @@ After the workflow finishes:- The GitHub Release for `vMAJOR.MINOR.PATCH` contains `Donkey.dmg` and`Donkey.dmg.sha256`.- The website source has `DONKEY_LATEST_VERSION` set to the numeric version.-- `site/public/appcast.xml` contains one item for that version and an enclosure- URL under `/releases/download/vMAJOR.MINOR.PATCH/Donkey.dmg`.+- `site/public/appcast.xml` contains one item for that version and an+ enclosure URL under `/releases/download/vMAJOR.MINOR.PATCH/Donkey.dmg`.- The GitHub Releases page keeps no more than 10 numeric production releases,plus the separate nightly prerelease when present.- `https://donkeyuse.com/appcast.xml` updates after the site deploy completes.-If Sparkle cannot validate an update, first check that the app was packaged with-the same `DONKEY_SPARKLE_PUBLIC_ED_KEY` that matches the private key stored in+If Sparkle cannot validate an update, first check that the app was packaged+with the `DONKEY_SPARKLE_PUBLIC_ED_KEY` that matches the private key stored inGitHub Actions.diff --git a/docs/guides/swift-mvc.md b/docs/guides/swift-mvc.mdindex 4bad7ed6..b3b1c023 100644--- a/docs/guides/swift-mvc.md+++ b/docs/guides/swift-mvc.md@@ -1,8 +1,14 @@# Swift MVC Guide-## Purpose+Donkey Swift code keeps product state, UI rendering, and AppKit orchestration+separate, so the pointer UI stays easy to change without coupling it to runtime+or AI harness work. Views render and emit typed intents; models own state;+controllers own AppKit.-Donkey Swift code should keep product state, UI rendering, and AppKit orchestration separate. This keeps the pointer UI easy to change without coupling it to future real-time runtime or AI harness work.+**The one rule:** `DonkeyUI` never imports `DonkeyRuntime` or `DonkeyAI`.+Runtime and LLM work crosses through `DonkeyContracts`, never through view+internals. If a view needs runtime data, the data becomes a contract type the+model passes in.## Pattern@@ -13,28 +19,39 @@ Donkey Swift code should keep product state, UI rendering, and AppKit orchestrat## Technical Guidelines-- Keep SwiftUI views value-like: pass state in, pass typed intent sinks out, and avoid timers, global mouse reads, model providers, or window management inside views.-- Keep models on `@MainActor` when they publish UI state. Models may depend on narrow provider protocols, but not on AppKit windows or timers.-- Keep controllers on `@MainActor` when they touch AppKit. Controllers may read screen and event geometry, monitor double-Command activation, own `NSPanel`, and translate geometry into model state.-- Keep app entry files small. They should define `@main`, delegate adaptation, and little else.-- Prefer target-level separation for reusable contracts and UI: `DonkeyContracts`, `DonkeyUI`, `DonkeyRuntime`, and `DonkeyAI`.-- Keep shared UI state types in `DonkeyContracts`, not in `DonkeyUI`, when models and views both need them.-- Do not let `DonkeyUI` import runtime or AI modules. Future runtime and LLM work must cross through contracts, not view internals.-- Name files after their MVC role when a feature grows past one screen: `FeatureModel.swift`, `FeatureRootView.swift`, `FeatureController.swift`.+- Keep SwiftUI views value-like: pass state in, pass typed intent sinks out,+ and avoid timers, global mouse reads, model providers, or window management+ inside views.+- Keep models on `@MainActor` when they publish UI state. Models may depend on+ narrow provider protocols, but not on AppKit windows or timers.+- Keep controllers on `@MainActor` when they touch AppKit. Controllers may read+ screen and event geometry, monitor double-Command activation, own `NSPanel`,+ and translate geometry into model state.+- Keep app entry files small: `@main`, delegate adaptation, and little else.+- Prefer target-level separation for reusable contracts and UI:+ `DonkeyContracts`, `DonkeyUI`, `DonkeyRuntime`, and `DonkeyAI`.+- Keep shared UI state types in `DonkeyContracts`, not in `DonkeyUI`, when+ models and views both need them.+- Name files after their MVC role when a feature grows past one screen:+ `FeatureModel.swift`, `FeatureRootView.swift`, `FeatureController.swift`.## Current Donkey Shape-The pointer overlay follows this split:--- model state covers prompt text, typed input, placement, theme, and typed intents-- views render the notch status and composer from model state-- the controller owns AppKit-only work such as the notch and prompt panels, double-Command activation, screen positioning, and movement timing-- app entry bootstraps the feature and avoids owning product behavior+The pointer overlay follows this split: model state covers prompt text, typed+input, placement, theme, and typed intents; views render the notch status and+composer from model state; the controller owns AppKit-only work such as the+notch and prompt panels, double-Command activation, screen positioning, and+movement timing; app entry bootstraps the feature without owning product+behavior. See `docs/guides/user-query-overlay.md` for the overlay's full+division of labor.## Review Checklist-- A SwiftUI view should not call `NSEvent.mouseLocation`, create an `NSPanel`, start a `Timer`, or import `DonkeyAI`/`DonkeyRuntime`.-- A model should not import `DonkeyUI`; shared display state belongs in `DonkeyContracts`.-- A model should not know about frames, screens, windows, or animation timing.-- A controller should not store business text or decide model-provider behavior beyond presenting existing model state.-- New product behavior should add or extend a guide in `docs/guides/`.+- A SwiftUI view does not call `NSEvent.mouseLocation`, create an `NSPanel`,+ start a `Timer`, or import `DonkeyAI`/`DonkeyRuntime`.+- A model does not import `DonkeyUI`; shared display state belongs in+ `DonkeyContracts`.+- A model does not know about frames, screens, windows, or animation timing.+- A controller does not store business text or decide model-provider behavior+ beyond presenting existing model state.+- New product behavior adds or extends a guide in `docs/guides/`.diff --git a/docs/guides/user-query-overlay.md b/docs/guides/user-query-overlay.mdindex 39738d5d..af07121d 100644--- a/docs/guides/user-query-overlay.md+++ b/docs/guides/user-query-overlay.md@@ -1,111 +1,194 @@# User Query Overlay-## Supported Behavior--Donkey supports a floating macOS overlay for conversational task threads and-quick local-app actions:--- On first launch, Donkey shows a native welcome screen, then a Google-only Mac- sign-in screen, then a native permission setup screen for Accessibility,- Screenshots, and Microphone before starting the overlay. Until the browser- returns through the `donkey://auth/callback` handoff, the app exchanges the- returned code for a Better Auth cookie, and the core permission setup is- complete, the notch surface is not shown and double-Command activation is not- registered.-- Double-tap Command and release to open a centered prompt with keyboard focus.-- Double-tap Command and hold the second press to open the prompt in voice mode.-- Show a top-center notch status surface for task progress, recent tasks, follow-up input, file drops, updates, and per-task pause/resume.-- When a typed prompt or notch follow-up is submitted, show a task spawn cue: the notch arrow rotates toward the exit direction, moves out of the notch, and a Donkey cursor overlay travels onto the desktop.-- Spawned cursors travel to a known safe visible target window when one is available. Otherwise they hold about 250 px below the notch near screen center as a loading/thinking state, then retarget if the destination becomes visible.-- Multiple spawned cursors can be present at the same time. The newest spawned cursor is selected by default, and clicking a cursor or its label selects it as the current agent.-- A stationary spawned cursor shows the submitted turn while Donkey is waiting on routing, model, or runtime work; it uses the cursor tail animation as the waiting state instead of replacing the label with interim text. When a response, clarification, review wait, failure, or other attention state is available, that result text replaces the label and stays visible so the user can read it and follow up; completed action-only cursors may fade out. Labels render complete words and wrap to their measured size instead of revealing partial typewriter text or clipping at the panel edge. Spawn labels expand wider on hover when that reduces wrapping, and select the cursor on click. Clicking a tasked label turns the same agent-colored surface into an inline editor with the agent message above and a lighter color-matched user input area below; Return submits the typed follow-up to that spawn's task, Shift-Return inserts a newline, Escape returns to the label, and clicking outside the editor closes it.-- Double-Command always opens the centered prompt, even when spawned cursors are visible. If a spawned cursor is selected, centered typed or voice input attaches to that task behind the scenes; otherwise Donkey uses the latest interactable spawned cursor before falling back to follow-up resolution.-- Keep prompt submissions, voice transcripts, and follow-ups on the same agent-harness path: task-thread routing, context assembly, conversational response, clarification, review, catalog-backed action parsing, task validation, and guarded local-app execution when a turn is actionable.-- Resolve model-classified local-item requests against local apps, files, and folders by querying the current Mac with the SQLite-backed agent memory store, Spotlight/`mdfind`, and bounded filesystem fallback. If the requested local item cannot be found, keep the task safe and report that it was not found instead of falling back to a vague clarification.-- Handle scriptable app tasks as guarded AppleScript automation when possible. Commands may use task metadata, generated source, or compact templates; completion is verified through generic task verification policy instead of requiring visible result text for every app.-- Visualize agent work with the spawned task cursor when a submitted turn already has one. Normal local-app tasks keep planning in the background and may create an `AgentVisualizationPlan` from the harness `agent.path.visualize` tool or from runtime evidence such as evidence-backed action steps, observations, and action traces. Cursor playback uses only grounded control bounds or action targets, so it does not animate to invented coordinates. Visual-only demonstration turns use the same plan shape without live input. Local-app visualizations use observed Accessibility or action-trace control bounds when available, convert target-window-normalized element centers into the active overlay screen's pixel coordinates, and only then move the overlay cursor. Before each travel segment, the pointer rotates toward the direction of travel; it then moves along a curved path and shows compact labels while keeping the real mouse untouched. A separate visualization-only cursor is only a fallback when no spawned cursor is available to attach to.-- Maintain a background agent memory store in Application Support. The store records resolved and missing local-item lookups, prewarms apps, stores runtime task definitions, keeps metadata such as kind/path/bundle ID/source/task/action, indexes records with SQLite FTS5 plus local vectors, and passes a bounded set of matching hints into the agent harness memory section for classifier and model consideration. Protected file folders such as Desktop, Documents, and Downloads stay lazy and are searched only when a user-requested local-item lookup needs them. See `docs/guides/decision-system.md` for how those hints feed typed model decisions and guarded local-app plans.-- Persist task threads as searchable Core Data conversations with event history, task assets, and per-run runtime coordination for any action work attached to the thread.-- Keep the overlay non-invasive. Permission setup requests Accessibility, screenshot, and microphone access with user-visible reasons, but the overlay itself does not capture the screen or synthesize input directly. Bounded screenshots and Accessibility reads are used only by guarded local-app workflows.-- A developer-only Donkey Vision overlay can be enabled by editing the- repo-tracked `apps/Donkey/dev-overlay.json` during debug runs, or by creating- `~/Library/Application Support/Donkey/dev-overlay.json`. Production builds do- not bundle the repo config and only honor the Application Support path. When- no config exists, the config is invalid, or `"enabled": false`, the debug- overlay is fully disabled. When enabled, Donkey Vision fuses Accessibility and- hosted AI screenshot parsing. Local geometry wins; AI boxes can be- interactable through guarded coordinate fallback and are visually marked as- `AI`. The overlay never sends a full- desktop screenshot to hosted AI: it captures safe app/window or- system-navigation surfaces only. See- `docs/guides/donkey-vision.md`.--```json-{- "enabled": true,- "mode": "donkeyVision",- "cadenceSeconds": 1.0,- "screenScope": "main",- "minConfidence": 0.25-}-```--## Technical Guidelines--- `UserQueryOverlayController` owns AppKit surfaces, placement, hover tracking, focus, keyboard shortcut recognition, dismissal, file-drop routing, and microphone level capture.-- `DonkeyAuthCoordinator` and `DonkeyLoginWindowController` own the Mac sign-in- gate. `MacPermissionSetupWindowController` owns the post-auth core permission- gate. App startup should create the overlay controller only after a stored- Google session exists or a pending sign-in callback validates its state token- and stores a Better Auth cookie in the app cookie jar, and the permission- setup has completed.-- SwiftUI rendering lives in `DonkeyUI` and consumes state/contracts from `DonkeyContracts`. It should not perform command parsing, model calls, input execution, screen capture, or microphone capture.-- `UserQueryOverlayModel` owns product state. Durable task data is persisted through Core Data in Application Support.-- Spawn display state is typed state. The model emits progress, target hints, and current selection; the overlay controller resolves hints against safe visible windows and keeps voice capture on the centered prompt; SwiftUI renders the notch cue, cursors, labels, label-to-editor transition, and selection state.-- Notch geometry comes from the active `NSScreen`, preferring safe-area and auxiliary-top metrics over hardcoded notch sizes. Content must stay out of the physical notch void; displays without a physical notch should use the same top-center composition without reserving unavailable space.-- `UserQueryNotchLayout` is the shared source for notch surface frames, content frames, corner radii, and notch-safe offsets. `canRenderTextInTopRow` describes whether text can draw in the top row, not whether that row exists.-- The prompt is a compact black composer: single-line text is pill-shaped, multiline text becomes a bounded rounded rectangle, Return submits, Shift-Return inserts a newline, Escape and outside clicks dismiss, and non-input capsule areas can drag the modal.-- The centered composer keeps text and voice modes on the same input surface. Double-Command release opens focused text input without initializing microphone capture, double-Command hold opens the same input with voice active, and typed text promotes the send button while the microphone affordance becomes secondary. Voice capture starts only from explicit voice activation such as holding the second Command tap or pressing the microphone affordance.-- Voice capture and transcription remain separate. The controller records bounded local audio and publishes levels; transcription is model-backed through the hosted agent-harness boundary before transcript text enters the turn path.-- Local item prewarming must run off the main actor and must not eagerly scan protected user folders. Agent memory is stored in SQLite under Application Support and uses FTS5 plus deterministic local embeddings for retrieval; JSONL is only an explicit export/debug format. Cached local-item hits must still point to an existing path or bundle before they are used as an execution target. Runtime task definitions are the generic open/local-app interaction seeds plus generated or user-reviewed definitions loaded from memory.-- For scriptable apps, prefer app-native AppleScript task commands before falling back to Accessibility, AI visual targets, or keyboard input. Submit steps with an explicit structured `controlID` may execute as an Accessibility `AXPress` against button-like controls, or as a guarded coordinate click against an AI visual target when Accessibility is unavailable. Control bounds are carried into action traces.-- Agent visualization overlays are non-interactive, non-activating panels. They may point, explain, and replay what the agent is doing or would do, but they do not synthesize mouse movement. Live keyboard or Accessibility actions remain separate guarded runtime actions. When a local-app action plan is based on an observation, preserve target-window geometry and control bounds on the evidence-backed steps so cursor replay can use pixel-grounded element positions instead of invented coordinates. Harness path playback should flow through `agent.path.visualize`, which returns a visual plan only after every waypoint is grounded.-- The developer UI inspection overlay is separate from agent visualization. It- is a transparent, non-activating, click-through, keyboard-pass-through AppKit- panel at a lower window level than Donkey's interactive UI. It renders- CALayer rectangles and labels from local Accessibility or hover-probe detector- output only. Provider action calls such as click, type, scroll, drag,- navigation, `computer_call`, or `function_call` are rejected by the overlay- itself. Live input is executed only by the guarded local-app runtime.- Hover-only detections are visualization/read-only evidence and must not- become live input authority.-- Task actions in the notch, including follow-up submission and pause/resume, must cross the model/controller command boundary with the selected task ID.-- User-query command handling should emit actionable `com.donkey.app` route/result logs for submitted commands, routing decisions, intent resolution, local action traces, unsupported requests, unavailable apps, and final task status. Action trace logs should state the backend, input mode, whether an element click happened, the control or bounds target, and that the overlay pointer is visual-only.+The user query overlay is Donkey's floating macOS surface: a top-center notch+status area, a centered prompt composer, and spawned agent cursors that show+what each task is doing. It is how every typed, voice, and follow-up turn+enters the agent harness.++**The one rule:** the overlay narrates; it never acts. Overlay panels are+non-interactive, non-activating visualization — cursor playback animates only+to grounded evidence coordinates and never synthesizes real mouse movement.+Live keyboard, Accessibility, and AppleScript actions run only through the+guarded runtime (`docs/guides/agent-harness.md`).++## Startup Gate++First launch shows a native welcome screen, then a Google-only Mac sign-in,+then a permission setup screen for Accessibility, Screenshots, and Microphone+with user-visible reasons. Until the browser returns through+`donkey://auth/callback`, the app exchanges the code for a Better Auth cookie,+and core permission setup completes, the notch is not shown and double-Command+activation is not registered. `DonkeyAuthCoordinator` and+`DonkeyLoginWindowController` own the sign-in gate;+`MacPermissionSetupWindowController` owns the permission gate. Protected+folders (Desktop, Documents, Downloads) stay lazy and are requested only when+a user-requested local-item lookup needs them.++## Activation and the Prompt++- Double-tap Command and release: centered prompt with keyboard focus, no+ microphone capture.+- Double-tap Command and hold the second press: the same prompt with voice+ active.+- Voice capture starts only from explicit activation — the hold, or pressing+ the microphone affordance. The controller records bounded local audio and+ publishes levels; transcription is model-backed through the hosted harness+ boundary before transcript text enters the turn path.+- The composer is a compact black surface: single-line text is pill-shaped,+ multiline text becomes a bounded rounded rectangle. Return submits,+ Shift-Return inserts a newline, Escape and outside clicks dismiss, and+ non-input capsule areas drag the modal. Typed text promotes the send button+ and makes the microphone affordance secondary.++Double-Command always opens the centered prompt, even when spawned cursors are+visible. If a cursor is selected, centered typed or voice input attaches to+that task; otherwise Donkey uses the latest interactable cursor before falling+back to follow-up resolution.++## Notch Surface++The notch shows task progress, recent tasks, follow-up input, file drops,+update availability, and per-task pause/resume. File drops attach to the+active or most recent task. Task actions — follow-up submission, pause/resume —+cross the model/controller boundary with the selected task ID.++Geometry comes from the active `NSScreen`, preferring safe-area and+auxiliary-top metrics over hardcoded notch sizes. Content stays out of the+physical notch void; displays without a notch use the same top-center+composition without reserving unavailable space. `UserQueryNotchLayout` is the+shared source for surface frames, content frames, corner radii, and notch-safe+offsets; `canRenderTextInTopRow` describes whether text can draw in the top+row, not whether that row exists.++## Spawned Cursors++Submitting a typed prompt or notch follow-up shows a spawn cue: the notch+arrow rotates toward the exit direction, leaves the notch, and a Donkey cursor+travels onto the desktop.++- Cursors travel to a known safe visible target window when one exists;+ otherwise they hold about 250 px below the notch near screen center as a+ thinking state and retarget when the destination becomes visible.+- A stationary cursor shows the submitted turn while Donkey works, using the+ cursor tail animation as the waiting state instead of interim label text.+ When a response, clarification, review wait, or failure arrives, that text+ replaces the label and stays visible; completed action-only cursors may fade+ out.+- Labels render complete words and wrap to their measured size — no partial+ typewriter text, no clipping at the panel edge. They expand wider on hover+ when that reduces wrapping, and select the cursor on click.+- Clicking a tasked label turns the same agent-colored surface into an inline+ editor: the agent message above, a lighter color-matched input below. Return+ submits the follow-up to that spawn's task, Shift-Return inserts a newline,+ Escape returns to the label, and clicking outside closes the editor.+- Multiple cursors can be present at once. The newest is selected by default;+ clicking a cursor or its label selects it as the current agent.++## Turn Path++Prompt submissions, voice transcripts, and follow-ups all take the same+agent-harness path: task-thread routing, context assembly, one-shot request+understanding, then the per-step harness loop that responds, clarifies, or+executes guarded action. See `docs/guides/decision-system.md` for how the+decision is made.++- Local-item requests resolve against installed apps, files, and folders using+ the SQLite agent memory store, Spotlight/`mdfind`, and bounded filesystem+ fallback. A missing item stays safe and reports not-found instead of falling+ back to a vague clarification.+- Scriptable app tasks prefer guarded AppleScript before Accessibility, AI+ visual targets, or keyboard input. Completion is verified through the+ generic verification policy, not visible result text for every app.+- Thread contents persist as markdown under Application Support+ (`Threads/<id>/thread.md`); Core Data stores durable task metadata, events,+ and assets for per-run runtime coordination.+- Command handling emits actionable `com.donkey.app` route/result logs:+ submitted commands, routing decisions, action traces (backend, input mode,+ whether an element click happened, the control or bounds target, and that+ the overlay pointer is visual-only), unsupported requests, unavailable apps,+ and final task status.++## Agent Memory Store++A background store in Application Support records resolved and missing+local-item lookups, prewarms apps, and stores runtime task definitions with+metadata such as kind, path, bundle ID, source, task, and action. It is SQLite+with FTS5 plus deterministic local embeddings; JSONL is an explicit+export/debug format only. A bounded set of matching hints feeds the harness+memory section for model consideration. Prewarming runs off the main actor and+never eagerly scans protected folders. Cached local-item hits must still point+to an existing path or bundle before they are used as an execution target.++## Visualization++Cursor playback uses only grounded evidence: observed Accessibility or+action-trace control bounds, converted from target-window-normalized centers+into the active overlay screen's pixel coordinates. Before each travel segment+the pointer rotates toward the direction of travel, then moves along a curved+path with compact labels while the real mouse stays untouched. Harness+playback flows through `agent.path.visualize`, which returns a plan only after+every waypoint is grounded; ungrounded steps are omitted. Visual-only+demonstration turns use the same plan shape without live input, and a+visualization-only cursor is used only when no spawned cursor is available to+attach to.++The developer UI inspection overlay is separate from agent visualization: a+transparent, non-activating, click-through, keyboard-pass-through panel at a+lower window level than Donkey's interactive UI. It renders local detector+output only and itself rejects provider action calls (click, type, scroll,+drag, `computer_call`, `function_call`). Enable it by editing the repo-tracked+`apps/Donkey/dev-overlay.json` during debug runs or by creating+`~/Library/Application Support/Donkey/dev-overlay.json`; production builds do+not bundle the repo config and honor only the Application Support path. No+config, an invalid config, or `"enabled": false` fully disables it. See+`docs/guides/donkey-vision.md` for the config shape and fusion behavior.++## Division of Labor++| Component | Owns |+|---|---|+| `UserQueryOverlayModel` | product state and typed intents |+| `UserQueryOverlayController` | AppKit surfaces, placement, hover tracking, focus, shortcut recognition, dismissal, file-drop routing, microphone level capture |+| `DonkeyUI` (SwiftUI) | rendering from `DonkeyContracts` state — no parsing, model calls, input execution, or screen/microphone capture |+| `UserQueryCommandHandler` | turn routing, outcome handling, route/result logging |++Spawn display state is typed state: the model emits progress, target hints,+and current selection; the controller resolves hints against safe visible+windows; SwiftUI renders the cue, cursors, labels, label-to-editor transition,+and selection.## Verification-Manually verify:--- The notch renders at the top center, respects physical notch safe areas, expands only from visible notch hover, and accepts expanded controls/clicks.-- First launch shows the permission setup after sign-in, explains Accessibility, Screenshots, and Microphone before requesting them, enables Continue only when all three are ready, and does not trigger Desktop/Documents/Downloads prompts during startup.-- Double-Command release opens a centered focused text prompt without starting microphone capture; double-Command hold opens the same prompt with voice active; pressing the microphone affordance starts voice capture; typed text shows a primary send button and a secondary microphone affordance; unrelated Command use does not activate the overlay.-- Typed, voice, and follow-up submissions create or update durable task threads, answer non-actionable conversation without showing action failure, show action status in the notch when work runs, and preserve per-task pause/resume behavior.-- Typed prompt and notch follow-up submissions show the spawn sequence: notch cue, desktop cursor emergence, direct travel to a known target or fallback holding point, typed submitted-turn label with tail-wag waiting animation, final response/result label, retargeting when the target becomes visible, persistent labels for conversational or attention states, and fade-out only for completed action-only turns.-- Stationary spawn labels render complete text without typewriter clipping, wrap to fit available width, select the cursor on click, and transition in place into a same-styled inline editor for tasked follow-ups without clipping the carried-over label.-- With multiple spawned cursors visible, clicking a cursor selects it; double-Command still opens the centered prompt, and the submitted typed or voice turn routes to the selected/latest cursor's task without opening the inline label editor.-- Open requests for installed apps, files, and folders launch or open the local item; missing local items show a not-found result and log the lookup provider/reason.-- LLM-classified visual-only prompts complete as visualization turns and show the animated cursor with typed labels without moving the real pointer.-- Normal local-app tasks can produce final visualization steps for observed, navigated, acted, and verified runtime work. Planning stays in the background. Cursor playback should target observed control centers from Accessibility or action traces when those bounds exist, omit ungrounded steps, and must not claim completion unless the runtime verification state supports it.-- The prompt supports wrapping, Shift-Return newline insertion, Return submission, Escape dismissal, outside-click dismissal, and dragging from non-input areas.-- File drops on the notch attach to the active or most recent task.-- With `dev-overlay.json` enabled, interact with underlying applications while- the debug boxes are visible; clicks, typing, scrolling, dragging, and Donkey- prompt activation should continue to target the underlying app or Donkey UI.- Removing the config file or setting `"enabled": false` should hide the debug- overlay without relaunching.+Manually verify after overlay changes:++- Startup: welcome → sign-in → permission setup; Continue enables only when+ all three permissions are ready; no Desktop/Documents/Downloads prompts+ during startup.+- Activation: release opens focused text input without microphone capture;+ hold opens voice mode; the microphone affordance starts capture; unrelated+ Command use does not activate the overlay.+- Notch: renders top-center, respects physical notch safe areas, expands only+ from visible notch hover, accepts expanded controls and clicks; file drops+ attach to the right task.+- Spawn flow: cue → travel → tail-wag waiting → result label; retargeting when+ the target becomes visible; persistent labels for attention states; fade-out+ only for completed action-only turns; labels wrap without clipping; the+ inline editor opens, submits, and closes correctly.+- Multiple cursors: clicking selects; double-Command still opens the centered+ prompt and routes the turn to the selected/latest cursor's task without+ opening the inline editor.+- Turns: conversation answers without action failure; local-item opens launch+ the item and missing items report not-found with the lookup provider and+ reason; visual-only prompts animate without moving the real pointer;+ completion claims match the runtime verification state.+- Dev overlay: with `dev-overlay.json` enabled, clicks, typing, scrolling,+ dragging, and prompt activation still target the underlying app or Donkey+ UI; removing the config or setting `"enabled": false` hides the overlay+ without relaunching.## Source Entry Points- App orchestration starts in `apps/Donkey/Sources/Donkey/`.-- Typed prompt command handling lives in `apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift`.+- Typed prompt command handling lives in+ `apps/Donkey/Sources/Donkey/UserQueryCommandHandler.swift`.- Reusable SwiftUI rendering lives in `apps/Donkey/Sources/DonkeyUI/`.